babylon.1.14-beta-debug.js 1003 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.multiplyInPlace = function (otherVector) {
  238. this.x *= otherVector.x;
  239. this.y *= otherVector.y;
  240. };
  241. Vector2.prototype.multiply = function (otherVector) {
  242. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  243. };
  244. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  245. result.x = this.x * otherVector.x;
  246. result.y = this.y * otherVector.y;
  247. };
  248. Vector2.prototype.multiplyByFloats = function (x, y) {
  249. return new Vector2(this.x * x, this.y * y);
  250. };
  251. Vector2.prototype.divide = function (otherVector) {
  252. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  253. };
  254. Vector2.prototype.divideToRef = function (otherVector, result) {
  255. result.x = this.x / otherVector.x;
  256. result.y = this.y / otherVector.y;
  257. };
  258. Vector2.prototype.negate = function () {
  259. return new Vector2(-this.x, -this.y);
  260. };
  261. Vector2.prototype.scaleInPlace = function (scale) {
  262. this.x *= scale;
  263. this.y *= scale;
  264. };
  265. Vector2.prototype.scale = function (scale) {
  266. return new Vector2(this.x * scale, this.y * scale);
  267. };
  268. Vector2.prototype.equals = function (otherVector) {
  269. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  270. };
  271. Vector2.prototype.length = function () {
  272. return Math.sqrt(this.x * this.x + this.y * this.y);
  273. };
  274. Vector2.prototype.lengthSquared = function () {
  275. return (this.x * this.x + this.y * this.y);
  276. };
  277. Vector2.prototype.normalize = function () {
  278. var len = this.length();
  279. if (len === 0)
  280. return;
  281. var num = 1.0 / len;
  282. this.x *= num;
  283. this.y *= num;
  284. };
  285. Vector2.prototype.clone = function () {
  286. return new Vector2(this.x, this.y);
  287. };
  288. Vector2.Zero = function () {
  289. return new Vector2(0, 0);
  290. };
  291. Vector2.FromArray = function (array, offset) {
  292. if (!offset) {
  293. offset = 0;
  294. }
  295. return new Vector2(array[offset], array[offset + 1]);
  296. };
  297. Vector2.FromArrayToRef = function (array, offset, result) {
  298. result.x = array[offset];
  299. result.y = array[offset + 1];
  300. };
  301. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  302. var squared = amount * amount;
  303. var cubed = amount * squared;
  304. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  305. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  306. return new Vector2(x, y);
  307. };
  308. Vector2.Clamp = function (value, min, max) {
  309. var x = value.x;
  310. x = (x > max.x) ? max.x : x;
  311. x = (x < min.x) ? min.x : x;
  312. var y = value.y;
  313. y = (y > max.y) ? max.y : y;
  314. y = (y < min.y) ? min.y : y;
  315. return new Vector2(x, y);
  316. };
  317. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  318. var squared = amount * amount;
  319. var cubed = amount * squared;
  320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  322. var part3 = (cubed - (2.0 * squared)) + amount;
  323. var part4 = cubed - squared;
  324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  326. return new Vector2(x, y);
  327. };
  328. Vector2.Lerp = function (start, end, amount) {
  329. var x = start.x + ((end.x - start.x) * amount);
  330. var y = start.y + ((end.y - start.y) * amount);
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Dot = function (left, right) {
  334. return left.x * right.x + left.y * right.y;
  335. };
  336. Vector2.Normalize = function (vector) {
  337. var newVector = vector.clone();
  338. newVector.normalize();
  339. return newVector;
  340. };
  341. Vector2.Minimize = function (left, right) {
  342. var x = (left.x < right.x) ? left.x : right.x;
  343. var y = (left.y < right.y) ? left.y : right.y;
  344. return new Vector2(x, y);
  345. };
  346. Vector2.Maximize = function (left, right) {
  347. var x = (left.x > right.x) ? left.x : right.x;
  348. var y = (left.y > right.y) ? left.y : right.y;
  349. return new Vector2(x, y);
  350. };
  351. Vector2.Transform = function (vector, transformation) {
  352. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  353. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  354. return new Vector2(x, y);
  355. };
  356. Vector2.Distance = function (value1, value2) {
  357. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  358. };
  359. Vector2.DistanceSquared = function (value1, value2) {
  360. var x = value1.x - value2.x;
  361. var y = value1.y - value2.y;
  362. return (x * x) + (y * y);
  363. };
  364. return Vector2;
  365. })();
  366. BABYLON.Vector2 = Vector2;
  367. var Vector3 = (function () {
  368. function Vector3(x, y, z) {
  369. this.x = x;
  370. this.y = y;
  371. this.z = z;
  372. }
  373. Vector3.prototype.toString = function () {
  374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  375. };
  376. Vector3.prototype.asArray = function () {
  377. var result = [];
  378. this.toArray(result, 0);
  379. return result;
  380. };
  381. Vector3.prototype.toArray = function (array, index) {
  382. if (index === undefined) {
  383. index = 0;
  384. }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. array[index + 2] = this.z;
  388. };
  389. Vector3.prototype.addInPlace = function (otherVector) {
  390. this.x += otherVector.x;
  391. this.y += otherVector.y;
  392. this.z += otherVector.z;
  393. };
  394. Vector3.prototype.add = function (otherVector) {
  395. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  396. };
  397. Vector3.prototype.addToRef = function (otherVector, result) {
  398. result.x = this.x + otherVector.x;
  399. result.y = this.y + otherVector.y;
  400. result.z = this.z + otherVector.z;
  401. };
  402. Vector3.prototype.subtractInPlace = function (otherVector) {
  403. this.x -= otherVector.x;
  404. this.y -= otherVector.y;
  405. this.z -= otherVector.z;
  406. };
  407. Vector3.prototype.subtract = function (otherVector) {
  408. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  409. };
  410. Vector3.prototype.subtractToRef = function (otherVector, result) {
  411. result.x = this.x - otherVector.x;
  412. result.y = this.y - otherVector.y;
  413. result.z = this.z - otherVector.z;
  414. };
  415. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  416. return new Vector3(this.x - x, this.y - y, this.z - z);
  417. };
  418. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  419. result.x = this.x - x;
  420. result.y = this.y - y;
  421. result.z = this.z - z;
  422. };
  423. Vector3.prototype.negate = function () {
  424. return new Vector3(-this.x, -this.y, -this.z);
  425. };
  426. Vector3.prototype.scaleInPlace = function (scale) {
  427. this.x *= scale;
  428. this.y *= scale;
  429. this.z *= scale;
  430. };
  431. Vector3.prototype.scale = function (scale) {
  432. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  433. };
  434. Vector3.prototype.scaleToRef = function (scale, result) {
  435. result.x = this.x * scale;
  436. result.y = this.y * scale;
  437. result.z = this.z * scale;
  438. };
  439. Vector3.prototype.equals = function (otherVector) {
  440. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  441. };
  442. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  443. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  444. };
  445. Vector3.prototype.equalsToFloats = function (x, y, z) {
  446. return this.x === x && this.y === y && this.z === z;
  447. };
  448. Vector3.prototype.multiplyInPlace = function (otherVector) {
  449. this.x *= otherVector.x;
  450. this.y *= otherVector.y;
  451. this.z *= otherVector.z;
  452. };
  453. Vector3.prototype.multiply = function (otherVector) {
  454. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  455. };
  456. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  457. result.x = this.x * otherVector.x;
  458. result.y = this.y * otherVector.y;
  459. result.z = this.z * otherVector.z;
  460. };
  461. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  462. return new Vector3(this.x * x, this.y * y, this.z * z);
  463. };
  464. Vector3.prototype.divide = function (otherVector) {
  465. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  466. };
  467. Vector3.prototype.divideToRef = function (otherVector, result) {
  468. result.x = this.x / otherVector.x;
  469. result.y = this.y / otherVector.y;
  470. result.z = this.z / otherVector.z;
  471. };
  472. Vector3.prototype.MinimizeInPlace = function (other) {
  473. if (other.x < this.x)
  474. this.x = other.x;
  475. if (other.y < this.y)
  476. this.y = other.y;
  477. if (other.z < this.z)
  478. this.z = other.z;
  479. };
  480. Vector3.prototype.MaximizeInPlace = function (other) {
  481. if (other.x > this.x)
  482. this.x = other.x;
  483. if (other.y > this.y)
  484. this.y = other.y;
  485. if (other.z > this.z)
  486. this.z = other.z;
  487. };
  488. Vector3.prototype.length = function () {
  489. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  490. };
  491. Vector3.prototype.lengthSquared = function () {
  492. return (this.x * this.x + this.y * this.y + this.z * this.z);
  493. };
  494. Vector3.prototype.normalize = function () {
  495. var len = this.length();
  496. if (len === 0)
  497. return;
  498. var num = 1.0 / len;
  499. this.x *= num;
  500. this.y *= num;
  501. this.z *= num;
  502. };
  503. Vector3.prototype.clone = function () {
  504. return new Vector3(this.x, this.y, this.z);
  505. };
  506. Vector3.prototype.copyFrom = function (source) {
  507. this.x = source.x;
  508. this.y = source.y;
  509. this.z = source.z;
  510. };
  511. Vector3.prototype.copyFromFloats = function (x, y, z) {
  512. this.x = x;
  513. this.y = y;
  514. this.z = z;
  515. };
  516. Vector3.FromArray = function (array, offset) {
  517. if (!offset) {
  518. offset = 0;
  519. }
  520. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  521. };
  522. Vector3.FromArrayToRef = function (array, offset, result) {
  523. result.x = array[offset];
  524. result.y = array[offset + 1];
  525. result.z = array[offset + 2];
  526. };
  527. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  528. result.x = array[offset];
  529. result.y = array[offset + 1];
  530. result.z = array[offset + 2];
  531. };
  532. Vector3.FromFloatsToRef = function (x, y, z, result) {
  533. result.x = x;
  534. result.y = y;
  535. result.z = z;
  536. };
  537. Vector3.Zero = function () {
  538. return new Vector3(0, 0, 0);
  539. };
  540. Vector3.Up = function () {
  541. return new Vector3(0, 1.0, 0);
  542. };
  543. Vector3.TransformCoordinates = function (vector, transformation) {
  544. var result = Vector3.Zero();
  545. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  546. return result;
  547. };
  548. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  552. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  553. result.x = x / w;
  554. result.y = y / w;
  555. result.z = z / w;
  556. };
  557. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  558. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  559. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  560. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  561. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  562. result.x = rx / rw;
  563. result.y = ry / rw;
  564. result.z = rz / rw;
  565. };
  566. Vector3.TransformNormal = function (vector, transformation) {
  567. var result = Vector3.Zero();
  568. Vector3.TransformNormalToRef(vector, transformation, result);
  569. return result;
  570. };
  571. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  572. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  573. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  574. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  575. };
  576. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  577. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  578. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  579. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  580. };
  581. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  582. var squared = amount * amount;
  583. var cubed = amount * squared;
  584. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  586. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  587. return new Vector3(x, y, z);
  588. };
  589. Vector3.Clamp = function (value, min, max) {
  590. var x = value.x;
  591. x = (x > max.x) ? max.x : x;
  592. x = (x < min.x) ? min.x : x;
  593. var y = value.y;
  594. y = (y > max.y) ? max.y : y;
  595. y = (y < min.y) ? min.y : y;
  596. var z = value.z;
  597. z = (z > max.z) ? max.z : z;
  598. z = (z < min.z) ? min.z : z;
  599. return new Vector3(x, y, z);
  600. };
  601. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  602. var squared = amount * amount;
  603. var cubed = amount * squared;
  604. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  605. var part2 = (-2.0 * cubed) + (3.0 * squared);
  606. var part3 = (cubed - (2.0 * squared)) + amount;
  607. var part4 = cubed - squared;
  608. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  609. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  610. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  611. return new Vector3(x, y, z);
  612. };
  613. Vector3.Lerp = function (start, end, amount) {
  614. var x = start.x + ((end.x - start.x) * amount);
  615. var y = start.y + ((end.y - start.y) * amount);
  616. var z = start.z + ((end.z - start.z) * amount);
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Dot = function (left, right) {
  620. return (left.x * right.x + left.y * right.y + left.z * right.z);
  621. };
  622. Vector3.Cross = function (left, right) {
  623. var result = Vector3.Zero();
  624. Vector3.CrossToRef(left, right, result);
  625. return result;
  626. };
  627. Vector3.CrossToRef = function (left, right, result) {
  628. result.x = left.y * right.z - left.z * right.y;
  629. result.y = left.z * right.x - left.x * right.z;
  630. result.z = left.x * right.y - left.y * right.x;
  631. };
  632. Vector3.Normalize = function (vector) {
  633. var result = Vector3.Zero();
  634. Vector3.NormalizeToRef(vector, result);
  635. return result;
  636. };
  637. Vector3.NormalizeToRef = function (vector, result) {
  638. result.copyFrom(vector);
  639. result.normalize();
  640. };
  641. Vector3.Project = function (vector, world, transform, viewport) {
  642. var cw = viewport.width;
  643. var ch = viewport.height;
  644. var cx = viewport.x;
  645. var cy = viewport.y;
  646. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  647. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  648. return Vector3.TransformCoordinates(vector, finalMatrix);
  649. };
  650. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  651. var matrix = world.multiply(view).multiply(projection);
  652. matrix.invert();
  653. source.x = source.x / viewportWidth * 2 - 1;
  654. source.y = -(source.y / viewportHeight * 2 - 1);
  655. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  656. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  657. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  658. vector = vector.scale(1.0 / num);
  659. }
  660. return vector;
  661. };
  662. Vector3.Minimize = function (left, right) {
  663. var min = left.clone();
  664. min.MinimizeInPlace(right);
  665. return min;
  666. };
  667. Vector3.Maximize = function (left, right) {
  668. var max = left.clone();
  669. max.MaximizeInPlace(right);
  670. return max;
  671. };
  672. Vector3.Distance = function (value1, value2) {
  673. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  674. };
  675. Vector3.DistanceSquared = function (value1, value2) {
  676. var x = value1.x - value2.x;
  677. var y = value1.y - value2.y;
  678. var z = value1.z - value2.z;
  679. return (x * x) + (y * y) + (z * z);
  680. };
  681. Vector3.Center = function (value1, value2) {
  682. var center = value1.add(value2);
  683. center.scaleInPlace(0.5);
  684. return center;
  685. };
  686. return Vector3;
  687. })();
  688. BABYLON.Vector3 = Vector3;
  689. var Quaternion = (function () {
  690. function Quaternion(x, y, z, w) {
  691. if (typeof x === "undefined") { x = 0; }
  692. if (typeof y === "undefined") { y = 0; }
  693. if (typeof z === "undefined") { z = 0; }
  694. if (typeof w === "undefined") { w = 1; }
  695. this.x = x;
  696. this.y = y;
  697. this.z = z;
  698. this.w = w;
  699. }
  700. Quaternion.prototype.toString = function () {
  701. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  702. };
  703. Quaternion.prototype.asArray = function () {
  704. return [this.x, this.y, this.z, this.w];
  705. };
  706. Quaternion.prototype.equals = function (otherQuaternion) {
  707. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  708. };
  709. Quaternion.prototype.clone = function () {
  710. return new Quaternion(this.x, this.y, this.z, this.w);
  711. };
  712. Quaternion.prototype.copyFrom = function (other) {
  713. this.x = other.x;
  714. this.y = other.y;
  715. this.z = other.z;
  716. this.w = other.w;
  717. };
  718. Quaternion.prototype.add = function (other) {
  719. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  720. };
  721. Quaternion.prototype.subtract = function (other) {
  722. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  723. };
  724. Quaternion.prototype.scale = function (value) {
  725. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  726. };
  727. Quaternion.prototype.multiply = function (q1) {
  728. var result = new Quaternion(0, 0, 0, 1.0);
  729. this.multiplyToRef(q1, result);
  730. return result;
  731. };
  732. Quaternion.prototype.multiplyToRef = function (q1, result) {
  733. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  734. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  735. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  736. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  737. };
  738. Quaternion.prototype.length = function () {
  739. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  740. };
  741. Quaternion.prototype.normalize = function () {
  742. var length = 1.0 / this.length();
  743. this.x *= length;
  744. this.y *= length;
  745. this.z *= length;
  746. this.w *= length;
  747. };
  748. Quaternion.prototype.toEulerAngles = function () {
  749. var qx = this.x;
  750. var qy = this.y;
  751. var qz = this.z;
  752. var qw = this.w;
  753. var sqx = qx * qx;
  754. var sqy = qy * qy;
  755. var sqz = qz * qz;
  756. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  757. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  758. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  759. var gimbaLockTest = qx * qy + qz * qw;
  760. if (gimbaLockTest > 0.499) {
  761. yaw = 2.0 * Math.atan2(qx, qw);
  762. roll = 0;
  763. } else if (gimbaLockTest < -0.499) {
  764. yaw = -2.0 * Math.atan2(qx, qw);
  765. roll = 0;
  766. }
  767. return new Vector3(pitch, yaw, roll);
  768. };
  769. Quaternion.prototype.toRotationMatrix = function (result) {
  770. var xx = this.x * this.x;
  771. var yy = this.y * this.y;
  772. var zz = this.z * this.z;
  773. var xy = this.x * this.y;
  774. var zw = this.z * this.w;
  775. var zx = this.z * this.x;
  776. var yw = this.y * this.w;
  777. var yz = this.y * this.z;
  778. var xw = this.x * this.w;
  779. result.m[0] = 1.0 - (2.0 * (yy + zz));
  780. result.m[1] = 2.0 * (xy + zw);
  781. result.m[2] = 2.0 * (zx - yw);
  782. result.m[3] = 0;
  783. result.m[4] = 2.0 * (xy - zw);
  784. result.m[5] = 1.0 - (2.0 * (zz + xx));
  785. result.m[6] = 2.0 * (yz + xw);
  786. result.m[7] = 0;
  787. result.m[8] = 2.0 * (zx + yw);
  788. result.m[9] = 2.0 * (yz - xw);
  789. result.m[10] = 1.0 - (2.0 * (yy + xx));
  790. result.m[11] = 0;
  791. result.m[12] = 0;
  792. result.m[13] = 0;
  793. result.m[14] = 0;
  794. result.m[15] = 1.0;
  795. };
  796. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  797. var data = matrix.m;
  798. var m11 = data[0], m12 = data[4], m13 = data[8];
  799. var m21 = data[1], m22 = data[5], m23 = data[9];
  800. var m31 = data[2], m32 = data[6], m33 = data[10];
  801. var trace = m11 + m22 + m33;
  802. var s;
  803. if (trace > 0) {
  804. s = 0.5 / Math.sqrt(trace + 1.0);
  805. this.w = 0.25 / s;
  806. this.x = (m32 - m23) * s;
  807. this.y = (m13 - m31) * s;
  808. this.z = (m21 - m12) * s;
  809. return;
  810. }
  811. if (m11 > m22 && m11 > m33) {
  812. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  813. this.w = (m32 - m23) / s;
  814. this.x = 0.25 * s;
  815. this.y = (m12 + m21) / s;
  816. this.z = (m13 + m31) / s;
  817. return;
  818. }
  819. if (m22 > m33) {
  820. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  821. this.w = (m13 - m31) / s;
  822. this.x = (m12 + m21) / s;
  823. this.y = 0.25 * s;
  824. this.z = (m23 + m32) / s;
  825. return;
  826. }
  827. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  828. this.w = (m21 - m12) / s;
  829. this.x = (m13 + m31) / s;
  830. this.y = (m23 + m32) / s;
  831. this.z = 0.25 * s;
  832. };
  833. Quaternion.RotationAxis = function (axis, angle) {
  834. var result = new Quaternion();
  835. var sin = Math.sin(angle / 2);
  836. result.w = Math.cos(angle / 2);
  837. result.x = axis.x * sin;
  838. result.y = axis.y * sin;
  839. result.z = axis.z * sin;
  840. return result;
  841. };
  842. Quaternion.FromArray = function (array, offset) {
  843. if (!offset) {
  844. offset = 0;
  845. }
  846. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  847. };
  848. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  849. var result = new Quaternion();
  850. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  851. return result;
  852. };
  853. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  854. var halfRoll = roll * 0.5;
  855. var halfPitch = pitch * 0.5;
  856. var halfYaw = yaw * 0.5;
  857. var sinRoll = Math.sin(halfRoll);
  858. var cosRoll = Math.cos(halfRoll);
  859. var sinPitch = Math.sin(halfPitch);
  860. var cosPitch = Math.cos(halfPitch);
  861. var sinYaw = Math.sin(halfYaw);
  862. var cosYaw = Math.cos(halfYaw);
  863. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  864. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  865. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  866. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  867. };
  868. Quaternion.Slerp = function (left, right, amount) {
  869. var num2;
  870. var num3;
  871. var num = amount;
  872. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  873. var flag = false;
  874. if (num4 < 0) {
  875. flag = true;
  876. num4 = -num4;
  877. }
  878. if (num4 > 0.999999) {
  879. num3 = 1 - num;
  880. num2 = flag ? -num : num;
  881. } else {
  882. var num5 = Math.acos(num4);
  883. var num6 = (1.0 / Math.sin(num5));
  884. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  885. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  886. }
  887. 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));
  888. };
  889. return Quaternion;
  890. })();
  891. BABYLON.Quaternion = Quaternion;
  892. var Matrix = (function () {
  893. function Matrix() {
  894. this.m = new Float32Array(16);
  895. }
  896. Matrix.prototype.isIdentity = function () {
  897. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  898. return false;
  899. 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)
  900. return false;
  901. return true;
  902. };
  903. Matrix.prototype.determinant = function () {
  904. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  905. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  906. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  907. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  908. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  909. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  910. 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))));
  911. };
  912. Matrix.prototype.toArray = function () {
  913. return this.m;
  914. };
  915. Matrix.prototype.asArray = function () {
  916. return this.toArray();
  917. };
  918. Matrix.prototype.invert = function () {
  919. this.invertToRef(this);
  920. };
  921. Matrix.prototype.invertToRef = function (other) {
  922. var l1 = this.m[0];
  923. var l2 = this.m[1];
  924. var l3 = this.m[2];
  925. var l4 = this.m[3];
  926. var l5 = this.m[4];
  927. var l6 = this.m[5];
  928. var l7 = this.m[6];
  929. var l8 = this.m[7];
  930. var l9 = this.m[8];
  931. var l10 = this.m[9];
  932. var l11 = this.m[10];
  933. var l12 = this.m[11];
  934. var l13 = this.m[12];
  935. var l14 = this.m[13];
  936. var l15 = this.m[14];
  937. var l16 = this.m[15];
  938. var l17 = (l11 * l16) - (l12 * l15);
  939. var l18 = (l10 * l16) - (l12 * l14);
  940. var l19 = (l10 * l15) - (l11 * l14);
  941. var l20 = (l9 * l16) - (l12 * l13);
  942. var l21 = (l9 * l15) - (l11 * l13);
  943. var l22 = (l9 * l14) - (l10 * l13);
  944. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  945. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  946. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  947. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  948. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  949. var l28 = (l7 * l16) - (l8 * l15);
  950. var l29 = (l6 * l16) - (l8 * l14);
  951. var l30 = (l6 * l15) - (l7 * l14);
  952. var l31 = (l5 * l16) - (l8 * l13);
  953. var l32 = (l5 * l15) - (l7 * l13);
  954. var l33 = (l5 * l14) - (l6 * l13);
  955. var l34 = (l7 * l12) - (l8 * l11);
  956. var l35 = (l6 * l12) - (l8 * l10);
  957. var l36 = (l6 * l11) - (l7 * l10);
  958. var l37 = (l5 * l12) - (l8 * l9);
  959. var l38 = (l5 * l11) - (l7 * l9);
  960. var l39 = (l5 * l10) - (l6 * l9);
  961. other.m[0] = l23 * l27;
  962. other.m[4] = l24 * l27;
  963. other.m[8] = l25 * l27;
  964. other.m[12] = l26 * l27;
  965. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  966. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  967. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  968. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  969. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  970. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  971. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  972. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  973. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  974. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  975. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  976. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  977. };
  978. Matrix.prototype.setTranslation = function (vector3) {
  979. this.m[12] = vector3.x;
  980. this.m[13] = vector3.y;
  981. this.m[14] = vector3.z;
  982. };
  983. Matrix.prototype.multiply = function (other) {
  984. var result = new Matrix();
  985. this.multiplyToRef(other, result);
  986. return result;
  987. };
  988. Matrix.prototype.copyFrom = function (other) {
  989. for (var index = 0; index < 16; index++) {
  990. this.m[index] = other.m[index];
  991. }
  992. };
  993. Matrix.prototype.copyToArray = function (array, offset) {
  994. if (typeof offset === "undefined") { offset = 0; }
  995. for (var index = 0; index < 16; index++) {
  996. array[offset + index] = this.m[index];
  997. }
  998. };
  999. Matrix.prototype.multiplyToRef = function (other, result) {
  1000. this.multiplyToArray(other, result.m, 0);
  1001. };
  1002. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1003. var tm0 = this.m[0];
  1004. var tm1 = this.m[1];
  1005. var tm2 = this.m[2];
  1006. var tm3 = this.m[3];
  1007. var tm4 = this.m[4];
  1008. var tm5 = this.m[5];
  1009. var tm6 = this.m[6];
  1010. var tm7 = this.m[7];
  1011. var tm8 = this.m[8];
  1012. var tm9 = this.m[9];
  1013. var tm10 = this.m[10];
  1014. var tm11 = this.m[11];
  1015. var tm12 = this.m[12];
  1016. var tm13 = this.m[13];
  1017. var tm14 = this.m[14];
  1018. var tm15 = this.m[15];
  1019. var om0 = other.m[0];
  1020. var om1 = other.m[1];
  1021. var om2 = other.m[2];
  1022. var om3 = other.m[3];
  1023. var om4 = other.m[4];
  1024. var om5 = other.m[5];
  1025. var om6 = other.m[6];
  1026. var om7 = other.m[7];
  1027. var om8 = other.m[8];
  1028. var om9 = other.m[9];
  1029. var om10 = other.m[10];
  1030. var om11 = other.m[11];
  1031. var om12 = other.m[12];
  1032. var om13 = other.m[13];
  1033. var om14 = other.m[14];
  1034. var om15 = other.m[15];
  1035. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1036. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1037. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1038. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1039. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1040. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1041. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1042. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1043. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1044. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1045. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1046. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1047. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1048. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1049. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1050. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1051. };
  1052. Matrix.prototype.equals = function (value) {
  1053. 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]);
  1054. };
  1055. Matrix.prototype.clone = function () {
  1056. 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]);
  1057. };
  1058. Matrix.FromArray = function (array, offset) {
  1059. var result = new Matrix();
  1060. if (!offset) {
  1061. offset = 0;
  1062. }
  1063. Matrix.FromArrayToRef(array, offset, result);
  1064. return result;
  1065. };
  1066. Matrix.FromArrayToRef = function (array, offset, result) {
  1067. for (var index = 0; index < 16; index++) {
  1068. result.m[index] = array[index + offset];
  1069. }
  1070. };
  1071. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1072. result.m[0] = initialM11;
  1073. result.m[1] = initialM12;
  1074. result.m[2] = initialM13;
  1075. result.m[3] = initialM14;
  1076. result.m[4] = initialM21;
  1077. result.m[5] = initialM22;
  1078. result.m[6] = initialM23;
  1079. result.m[7] = initialM24;
  1080. result.m[8] = initialM31;
  1081. result.m[9] = initialM32;
  1082. result.m[10] = initialM33;
  1083. result.m[11] = initialM34;
  1084. result.m[12] = initialM41;
  1085. result.m[13] = initialM42;
  1086. result.m[14] = initialM43;
  1087. result.m[15] = initialM44;
  1088. };
  1089. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1090. var result = new Matrix();
  1091. result.m[0] = initialM11;
  1092. result.m[1] = initialM12;
  1093. result.m[2] = initialM13;
  1094. result.m[3] = initialM14;
  1095. result.m[4] = initialM21;
  1096. result.m[5] = initialM22;
  1097. result.m[6] = initialM23;
  1098. result.m[7] = initialM24;
  1099. result.m[8] = initialM31;
  1100. result.m[9] = initialM32;
  1101. result.m[10] = initialM33;
  1102. result.m[11] = initialM34;
  1103. result.m[12] = initialM41;
  1104. result.m[13] = initialM42;
  1105. result.m[14] = initialM43;
  1106. result.m[15] = initialM44;
  1107. return result;
  1108. };
  1109. Matrix.Identity = function () {
  1110. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1111. };
  1112. Matrix.IdentityToRef = function (result) {
  1113. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1114. };
  1115. Matrix.Zero = function () {
  1116. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1117. };
  1118. Matrix.RotationX = function (angle) {
  1119. var result = new Matrix();
  1120. Matrix.RotationXToRef(angle, result);
  1121. return result;
  1122. };
  1123. Matrix.RotationXToRef = function (angle, result) {
  1124. var s = Math.sin(angle);
  1125. var c = Math.cos(angle);
  1126. result.m[0] = 1.0;
  1127. result.m[15] = 1.0;
  1128. result.m[5] = c;
  1129. result.m[10] = c;
  1130. result.m[9] = -s;
  1131. result.m[6] = s;
  1132. result.m[1] = 0;
  1133. result.m[2] = 0;
  1134. result.m[3] = 0;
  1135. result.m[4] = 0;
  1136. result.m[7] = 0;
  1137. result.m[8] = 0;
  1138. result.m[11] = 0;
  1139. result.m[12] = 0;
  1140. result.m[13] = 0;
  1141. result.m[14] = 0;
  1142. };
  1143. Matrix.RotationY = function (angle) {
  1144. var result = new Matrix();
  1145. Matrix.RotationYToRef(angle, result);
  1146. return result;
  1147. };
  1148. Matrix.RotationYToRef = function (angle, result) {
  1149. var s = Math.sin(angle);
  1150. var c = Math.cos(angle);
  1151. result.m[5] = 1.0;
  1152. result.m[15] = 1.0;
  1153. result.m[0] = c;
  1154. result.m[2] = -s;
  1155. result.m[8] = s;
  1156. result.m[10] = c;
  1157. result.m[1] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[6] = 0;
  1161. result.m[7] = 0;
  1162. result.m[9] = 0;
  1163. result.m[11] = 0;
  1164. result.m[12] = 0;
  1165. result.m[13] = 0;
  1166. result.m[14] = 0;
  1167. };
  1168. Matrix.RotationZ = function (angle) {
  1169. var result = new Matrix();
  1170. Matrix.RotationZToRef(angle, result);
  1171. return result;
  1172. };
  1173. Matrix.RotationZToRef = function (angle, result) {
  1174. var s = Math.sin(angle);
  1175. var c = Math.cos(angle);
  1176. result.m[10] = 1.0;
  1177. result.m[15] = 1.0;
  1178. result.m[0] = c;
  1179. result.m[1] = s;
  1180. result.m[4] = -s;
  1181. result.m[5] = c;
  1182. result.m[2] = 0;
  1183. result.m[3] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[8] = 0;
  1187. result.m[9] = 0;
  1188. result.m[11] = 0;
  1189. result.m[12] = 0;
  1190. result.m[13] = 0;
  1191. result.m[14] = 0;
  1192. };
  1193. Matrix.RotationAxis = function (axis, angle) {
  1194. var s = Math.sin(-angle);
  1195. var c = Math.cos(-angle);
  1196. var c1 = 1 - c;
  1197. axis.normalize();
  1198. var result = Matrix.Zero();
  1199. result.m[0] = (axis.x * axis.x) * c1 + c;
  1200. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1201. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1202. result.m[3] = 0.0;
  1203. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1204. result.m[5] = (axis.y * axis.y) * c1 + c;
  1205. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1206. result.m[7] = 0.0;
  1207. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1208. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1209. result.m[10] = (axis.z * axis.z) * c1 + c;
  1210. result.m[11] = 0.0;
  1211. result.m[15] = 1.0;
  1212. return result;
  1213. };
  1214. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1215. var result = new Matrix();
  1216. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1217. return result;
  1218. };
  1219. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1220. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1221. this._tempQuaternion.toRotationMatrix(result);
  1222. };
  1223. Matrix.Scaling = function (x, y, z) {
  1224. var result = Matrix.Zero();
  1225. Matrix.ScalingToRef(x, y, z, result);
  1226. return result;
  1227. };
  1228. Matrix.ScalingToRef = function (x, y, z, result) {
  1229. result.m[0] = x;
  1230. result.m[1] = 0;
  1231. result.m[2] = 0;
  1232. result.m[3] = 0;
  1233. result.m[4] = 0;
  1234. result.m[5] = y;
  1235. result.m[6] = 0;
  1236. result.m[7] = 0;
  1237. result.m[8] = 0;
  1238. result.m[9] = 0;
  1239. result.m[10] = z;
  1240. result.m[11] = 0;
  1241. result.m[12] = 0;
  1242. result.m[13] = 0;
  1243. result.m[14] = 0;
  1244. result.m[15] = 1.0;
  1245. };
  1246. Matrix.Translation = function (x, y, z) {
  1247. var result = Matrix.Identity();
  1248. Matrix.TranslationToRef(x, y, z, result);
  1249. return result;
  1250. };
  1251. Matrix.TranslationToRef = function (x, y, z, result) {
  1252. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1253. };
  1254. Matrix.LookAtLH = function (eye, target, up) {
  1255. var result = Matrix.Zero();
  1256. Matrix.LookAtLHToRef(eye, target, up, result);
  1257. return result;
  1258. };
  1259. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1260. target.subtractToRef(eye, this._zAxis);
  1261. this._zAxis.normalize();
  1262. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1263. this._xAxis.normalize();
  1264. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1265. this._yAxis.normalize();
  1266. var ex = -Vector3.Dot(this._xAxis, eye);
  1267. var ey = -Vector3.Dot(this._yAxis, eye);
  1268. var ez = -Vector3.Dot(this._zAxis, eye);
  1269. 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);
  1270. };
  1271. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1272. var hw = 2.0 / width;
  1273. var hh = 2.0 / height;
  1274. var id = 1.0 / (zfar - znear);
  1275. var nid = znear / (znear - zfar);
  1276. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1277. };
  1278. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1279. var matrix = Matrix.Zero();
  1280. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1281. return matrix;
  1282. };
  1283. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1284. result.m[0] = 2.0 / (right - left);
  1285. result.m[1] = result.m[2] = result.m[3] = 0;
  1286. result.m[5] = 2.0 / (top - bottom);
  1287. result.m[4] = result.m[6] = result.m[7] = 0;
  1288. result.m[10] = -1.0 / (znear - zfar);
  1289. result.m[8] = result.m[9] = result.m[11] = 0;
  1290. result.m[12] = (left + right) / (left - right);
  1291. result.m[13] = (top + bottom) / (bottom - top);
  1292. result.m[14] = znear / (znear - zfar);
  1293. result.m[15] = 1.0;
  1294. };
  1295. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1296. var matrix = Matrix.Zero();
  1297. matrix.m[0] = (2.0 * znear) / width;
  1298. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1299. matrix.m[5] = (2.0 * znear) / height;
  1300. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1301. matrix.m[10] = -zfar / (znear - zfar);
  1302. matrix.m[8] = matrix.m[9] = 0.0;
  1303. matrix.m[11] = 1.0;
  1304. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1305. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1306. return matrix;
  1307. };
  1308. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1309. var matrix = Matrix.Zero();
  1310. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1311. return matrix;
  1312. };
  1313. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1314. var tan = 1.0 / (Math.tan(fov * 0.5));
  1315. result.m[0] = tan / aspect;
  1316. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1317. result.m[5] = tan;
  1318. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1319. result.m[8] = result.m[9] = 0.0;
  1320. result.m[10] = -zfar / (znear - zfar);
  1321. result.m[11] = 1.0;
  1322. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1323. result.m[14] = (znear * zfar) / (znear - zfar);
  1324. };
  1325. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1326. var cw = viewport.width;
  1327. var ch = viewport.height;
  1328. var cx = viewport.x;
  1329. var cy = viewport.y;
  1330. 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);
  1331. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1332. };
  1333. Matrix.Transpose = function (matrix) {
  1334. var result = new Matrix();
  1335. result.m[0] = matrix.m[0];
  1336. result.m[1] = matrix.m[4];
  1337. result.m[2] = matrix.m[8];
  1338. result.m[3] = matrix.m[12];
  1339. result.m[4] = matrix.m[1];
  1340. result.m[5] = matrix.m[5];
  1341. result.m[6] = matrix.m[9];
  1342. result.m[7] = matrix.m[13];
  1343. result.m[8] = matrix.m[2];
  1344. result.m[9] = matrix.m[6];
  1345. result.m[10] = matrix.m[10];
  1346. result.m[11] = matrix.m[14];
  1347. result.m[12] = matrix.m[3];
  1348. result.m[13] = matrix.m[7];
  1349. result.m[14] = matrix.m[11];
  1350. result.m[15] = matrix.m[15];
  1351. return result;
  1352. };
  1353. Matrix.Reflection = function (plane) {
  1354. var matrix = new Matrix();
  1355. Matrix.ReflectionToRef(plane, matrix);
  1356. return matrix;
  1357. };
  1358. Matrix.ReflectionToRef = function (plane, result) {
  1359. plane.normalize();
  1360. var x = plane.normal.x;
  1361. var y = plane.normal.y;
  1362. var z = plane.normal.z;
  1363. var temp = -2 * x;
  1364. var temp2 = -2 * y;
  1365. var temp3 = -2 * z;
  1366. result.m[0] = (temp * x) + 1;
  1367. result.m[1] = temp2 * x;
  1368. result.m[2] = temp3 * x;
  1369. result.m[3] = 0.0;
  1370. result.m[4] = temp * y;
  1371. result.m[5] = (temp2 * y) + 1;
  1372. result.m[6] = temp3 * y;
  1373. result.m[7] = 0.0;
  1374. result.m[8] = temp * z;
  1375. result.m[9] = temp2 * z;
  1376. result.m[10] = (temp3 * z) + 1;
  1377. result.m[11] = 0.0;
  1378. result.m[12] = temp * plane.d;
  1379. result.m[13] = temp2 * plane.d;
  1380. result.m[14] = temp3 * plane.d;
  1381. result.m[15] = 1.0;
  1382. };
  1383. Matrix._tempQuaternion = new Quaternion();
  1384. Matrix._xAxis = Vector3.Zero();
  1385. Matrix._yAxis = Vector3.Zero();
  1386. Matrix._zAxis = Vector3.Zero();
  1387. return Matrix;
  1388. })();
  1389. BABYLON.Matrix = Matrix;
  1390. var Plane = (function () {
  1391. function Plane(a, b, c, d) {
  1392. this.normal = new Vector3(a, b, c);
  1393. this.d = d;
  1394. }
  1395. Plane.prototype.asArray = function () {
  1396. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1397. };
  1398. Plane.prototype.clone = function () {
  1399. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1400. };
  1401. Plane.prototype.normalize = function () {
  1402. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1403. var magnitude = 0;
  1404. if (norm != 0) {
  1405. magnitude = 1.0 / norm;
  1406. }
  1407. this.normal.x *= magnitude;
  1408. this.normal.y *= magnitude;
  1409. this.normal.z *= magnitude;
  1410. this.d *= magnitude;
  1411. };
  1412. Plane.prototype.transform = function (transformation) {
  1413. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1414. var x = this.normal.x;
  1415. var y = this.normal.y;
  1416. var z = this.normal.z;
  1417. var d = this.d;
  1418. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1419. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1420. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1421. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1422. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1423. };
  1424. Plane.prototype.dotCoordinate = function (point) {
  1425. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1426. };
  1427. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1428. var x1 = point2.x - point1.x;
  1429. var y1 = point2.y - point1.y;
  1430. var z1 = point2.z - point1.z;
  1431. var x2 = point3.x - point1.x;
  1432. var y2 = point3.y - point1.y;
  1433. var z2 = point3.z - point1.z;
  1434. var yz = (y1 * z2) - (z1 * y2);
  1435. var xz = (z1 * x2) - (x1 * z2);
  1436. var xy = (x1 * y2) - (y1 * x2);
  1437. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1438. var invPyth;
  1439. if (pyth != 0) {
  1440. invPyth = 1.0 / pyth;
  1441. } else {
  1442. invPyth = 0;
  1443. }
  1444. this.normal.x = yz * invPyth;
  1445. this.normal.y = xz * invPyth;
  1446. this.normal.z = xy * invPyth;
  1447. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1448. };
  1449. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1450. var dot = Vector3.Dot(this.normal, direction);
  1451. return (dot <= epsilon);
  1452. };
  1453. Plane.prototype.signedDistanceTo = function (point) {
  1454. return Vector3.Dot(point, this.normal) + this.d;
  1455. };
  1456. Plane.FromArray = function (array) {
  1457. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1458. };
  1459. Plane.FromPoints = function (point1, point2, point3) {
  1460. var result = new BABYLON.Plane(0, 0, 0, 0);
  1461. result.copyFromPoints(point1, point2, point3);
  1462. return result;
  1463. };
  1464. Plane.FromPositionAndNormal = function (origin, normal) {
  1465. var result = new BABYLON.Plane(0, 0, 0, 0);
  1466. normal.normalize();
  1467. result.normal = normal;
  1468. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1469. return result;
  1470. };
  1471. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1472. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1473. return Vector3.Dot(point, normal) + d;
  1474. };
  1475. return Plane;
  1476. })();
  1477. BABYLON.Plane = Plane;
  1478. var Viewport = (function () {
  1479. function Viewport(x, y, width, height) {
  1480. this.x = x;
  1481. this.y = y;
  1482. this.width = width;
  1483. this.height = height;
  1484. }
  1485. Viewport.prototype.toGlobal = function (engine) {
  1486. var width = engine.getRenderWidth();
  1487. var height = engine.getRenderHeight();
  1488. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1489. };
  1490. return Viewport;
  1491. })();
  1492. BABYLON.Viewport = Viewport;
  1493. var Frustum = (function () {
  1494. function Frustum() {
  1495. }
  1496. Frustum.GetPlanes = function (transform) {
  1497. var frustumPlanes = [];
  1498. for (var index = 0; index < 6; index++) {
  1499. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1500. }
  1501. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1502. return frustumPlanes;
  1503. };
  1504. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1505. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1506. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1507. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1508. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1509. frustumPlanes[0].normalize();
  1510. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1511. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1512. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1513. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1514. frustumPlanes[1].normalize();
  1515. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1516. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1517. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1518. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1519. frustumPlanes[2].normalize();
  1520. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1521. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1522. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1523. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1524. frustumPlanes[3].normalize();
  1525. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1526. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1527. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1528. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1529. frustumPlanes[4].normalize();
  1530. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1531. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1532. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1533. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1534. frustumPlanes[5].normalize();
  1535. };
  1536. return Frustum;
  1537. })();
  1538. BABYLON.Frustum = Frustum;
  1539. var Ray = (function () {
  1540. function Ray(origin, direction) {
  1541. this.origin = origin;
  1542. this.direction = direction;
  1543. }
  1544. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1545. var d = 0.0;
  1546. var maxValue = Number.MAX_VALUE;
  1547. if (Math.abs(this.direction.x) < 0.0000001) {
  1548. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1549. return false;
  1550. }
  1551. } else {
  1552. var inv = 1.0 / this.direction.x;
  1553. var min = (minimum.x - this.origin.x) * inv;
  1554. var max = (maximum.x - this.origin.x) * inv;
  1555. if (min > max) {
  1556. var temp = min;
  1557. min = max;
  1558. max = temp;
  1559. }
  1560. d = Math.max(min, d);
  1561. maxValue = Math.min(max, maxValue);
  1562. if (d > maxValue) {
  1563. return false;
  1564. }
  1565. }
  1566. if (Math.abs(this.direction.y) < 0.0000001) {
  1567. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1568. return false;
  1569. }
  1570. } else {
  1571. inv = 1.0 / this.direction.y;
  1572. min = (minimum.y - this.origin.y) * inv;
  1573. max = (maximum.y - this.origin.y) * inv;
  1574. if (min > max) {
  1575. temp = min;
  1576. min = max;
  1577. max = temp;
  1578. }
  1579. d = Math.max(min, d);
  1580. maxValue = Math.min(max, maxValue);
  1581. if (d > maxValue) {
  1582. return false;
  1583. }
  1584. }
  1585. if (Math.abs(this.direction.z) < 0.0000001) {
  1586. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1587. return false;
  1588. }
  1589. } else {
  1590. inv = 1.0 / this.direction.z;
  1591. min = (minimum.z - this.origin.z) * inv;
  1592. max = (maximum.z - this.origin.z) * inv;
  1593. if (min > max) {
  1594. temp = min;
  1595. min = max;
  1596. max = temp;
  1597. }
  1598. d = Math.max(min, d);
  1599. maxValue = Math.min(max, maxValue);
  1600. if (d > maxValue) {
  1601. return false;
  1602. }
  1603. }
  1604. return true;
  1605. };
  1606. Ray.prototype.intersectsBox = function (box) {
  1607. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1608. };
  1609. Ray.prototype.intersectsSphere = function (sphere) {
  1610. var x = sphere.center.x - this.origin.x;
  1611. var y = sphere.center.y - this.origin.y;
  1612. var z = sphere.center.z - this.origin.z;
  1613. var pyth = (x * x) + (y * y) + (z * z);
  1614. var rr = sphere.radius * sphere.radius;
  1615. if (pyth <= rr) {
  1616. return true;
  1617. }
  1618. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1619. if (dot < 0.0) {
  1620. return false;
  1621. }
  1622. var temp = pyth - (dot * dot);
  1623. return temp <= rr;
  1624. };
  1625. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1626. if (!this._edge1) {
  1627. this._edge1 = BABYLON.Vector3.Zero();
  1628. this._edge2 = BABYLON.Vector3.Zero();
  1629. this._pvec = BABYLON.Vector3.Zero();
  1630. this._tvec = BABYLON.Vector3.Zero();
  1631. this._qvec = BABYLON.Vector3.Zero();
  1632. }
  1633. vertex1.subtractToRef(vertex0, this._edge1);
  1634. vertex2.subtractToRef(vertex0, this._edge2);
  1635. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1636. var det = Vector3.Dot(this._edge1, this._pvec);
  1637. if (det === 0) {
  1638. return null;
  1639. }
  1640. var invdet = 1 / det;
  1641. this.origin.subtractToRef(vertex0, this._tvec);
  1642. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1643. if (bu < 0 || bu > 1.0) {
  1644. return null;
  1645. }
  1646. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1647. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1648. if (bv < 0 || bu + bv > 1.0) {
  1649. return null;
  1650. }
  1651. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1652. };
  1653. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1654. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1655. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1656. var direction = end.subtract(start);
  1657. direction.normalize();
  1658. return new Ray(start, direction);
  1659. };
  1660. Ray.Transform = function (ray, matrix) {
  1661. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1662. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1663. return new Ray(newOrigin, newDirection);
  1664. };
  1665. return Ray;
  1666. })();
  1667. BABYLON.Ray = Ray;
  1668. (function (Space) {
  1669. Space[Space["LOCAL"] = 0] = "LOCAL";
  1670. Space[Space["WORLD"] = 1] = "WORLD";
  1671. })(BABYLON.Space || (BABYLON.Space = {}));
  1672. var Space = BABYLON.Space;
  1673. var Axis = (function () {
  1674. function Axis() {
  1675. }
  1676. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1677. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1678. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1679. return Axis;
  1680. })();
  1681. BABYLON.Axis = Axis;
  1682. ;
  1683. })(BABYLON || (BABYLON = {}));
  1684. var BABYLON;
  1685. (function (BABYLON) {
  1686. var screenshotCanvas;
  1687. var fpsRange = 60;
  1688. var previousFramesDuration = [];
  1689. var fps = 60;
  1690. var deltaTime = 0;
  1691. var cloneValue = function (source, destinationObject) {
  1692. if (!source)
  1693. return null;
  1694. if (source instanceof BABYLON.Mesh) {
  1695. return null;
  1696. }
  1697. if (source instanceof BABYLON.SubMesh) {
  1698. return source.clone(destinationObject);
  1699. } else if (source.clone) {
  1700. return source.clone();
  1701. }
  1702. return null;
  1703. };
  1704. var Tools = (function () {
  1705. function Tools() {
  1706. }
  1707. Tools.GetFilename = function (path) {
  1708. var index = path.lastIndexOf("/");
  1709. if (index < 0)
  1710. return path;
  1711. return path.substring(index + 1);
  1712. };
  1713. Tools.GetDOMTextContent = function (element) {
  1714. var result = "";
  1715. var child = element.firstChild;
  1716. while (child) {
  1717. if (child.nodeType == 3) {
  1718. result += child.textContent;
  1719. }
  1720. child = child.nextSibling;
  1721. }
  1722. return result;
  1723. };
  1724. Tools.ToDegrees = function (angle) {
  1725. return angle * 180 / Math.PI;
  1726. };
  1727. Tools.ToRadians = function (angle) {
  1728. return angle * Math.PI / 180;
  1729. };
  1730. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1731. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1732. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1733. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1734. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1735. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1736. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1737. }
  1738. return {
  1739. minimum: minimum,
  1740. maximum: maximum
  1741. };
  1742. };
  1743. Tools.ExtractMinAndMax = function (positions, start, count) {
  1744. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1745. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1746. for (var index = start; index < start + count; index++) {
  1747. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1748. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1749. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1750. }
  1751. return {
  1752. minimum: minimum,
  1753. maximum: maximum
  1754. };
  1755. };
  1756. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1757. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1758. return undefined;
  1759. return Array.isArray(obj) ? obj : [obj];
  1760. };
  1761. Tools.GetPointerPrefix = function () {
  1762. var eventPrefix = "pointer";
  1763. if (!navigator.pointerEnabled) {
  1764. eventPrefix = "mouse";
  1765. }
  1766. return eventPrefix;
  1767. };
  1768. Tools.QueueNewFrame = function (func) {
  1769. if (window.requestAnimationFrame)
  1770. window.requestAnimationFrame(func);
  1771. else if (window.msRequestAnimationFrame)
  1772. window.msRequestAnimationFrame(func);
  1773. else if (window.webkitRequestAnimationFrame)
  1774. window.webkitRequestAnimationFrame(func);
  1775. else if (window.mozRequestAnimationFrame)
  1776. window.mozRequestAnimationFrame(func);
  1777. else if (window.oRequestAnimationFrame)
  1778. window.oRequestAnimationFrame(func);
  1779. else {
  1780. window.setTimeout(func, 16);
  1781. }
  1782. };
  1783. Tools.RequestFullscreen = function (element) {
  1784. if (element.requestFullscreen)
  1785. element.requestFullscreen();
  1786. else if (element.msRequestFullscreen)
  1787. element.msRequestFullscreen();
  1788. else if (element.webkitRequestFullscreen)
  1789. element.webkitRequestFullscreen();
  1790. else if (element.mozRequestFullScreen)
  1791. element.mozRequestFullScreen();
  1792. };
  1793. Tools.ExitFullscreen = function () {
  1794. if (document.exitFullscreen) {
  1795. document.exitFullscreen();
  1796. } else if (document.mozCancelFullScreen) {
  1797. document.mozCancelFullScreen();
  1798. } else if (document.webkitCancelFullScreen) {
  1799. document.webkitCancelFullScreen();
  1800. } else if (document.msCancelFullScreen) {
  1801. document.msCancelFullScreen();
  1802. }
  1803. };
  1804. Tools.CleanUrl = function (url) {
  1805. url = url.replace(/#/mg, "%23");
  1806. return url;
  1807. };
  1808. Tools.LoadImage = function (url, onload, onerror, database) {
  1809. url = Tools.CleanUrl(url);
  1810. var img = new Image();
  1811. img.crossOrigin = 'anonymous';
  1812. img.onload = function () {
  1813. onload(img);
  1814. };
  1815. img.onerror = function (err) {
  1816. onerror(img, err);
  1817. };
  1818. var noIndexedDB = function () {
  1819. img.src = url;
  1820. };
  1821. var loadFromIndexedDB = function () {
  1822. database.loadImageFromDB(url, img);
  1823. };
  1824. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1825. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1826. } else {
  1827. if (url.indexOf("file:") === -1) {
  1828. noIndexedDB();
  1829. } else {
  1830. try {
  1831. var textureName = url.substring(5);
  1832. var blobURL;
  1833. try {
  1834. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1835. } catch (ex) {
  1836. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1837. }
  1838. img.src = blobURL;
  1839. } catch (e) {
  1840. Tools.Log("Error while trying to load texture: " + textureName);
  1841. img.src = null;
  1842. }
  1843. }
  1844. }
  1845. return img;
  1846. };
  1847. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1848. url = Tools.CleanUrl(url);
  1849. var noIndexedDB = function () {
  1850. var request = new XMLHttpRequest();
  1851. var loadUrl = Tools.BaseUrl + url;
  1852. request.open('GET', loadUrl, true);
  1853. if (useArrayBuffer) {
  1854. request.responseType = "arraybuffer";
  1855. }
  1856. request.onprogress = progressCallBack;
  1857. request.onreadystatechange = function () {
  1858. if (request.readyState == 4) {
  1859. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1860. callback(!useArrayBuffer ? request.responseText : request.response);
  1861. } else {
  1862. if (onError) {
  1863. onError();
  1864. } else {
  1865. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1866. }
  1867. }
  1868. }
  1869. };
  1870. request.send(null);
  1871. };
  1872. var loadFromIndexedDB = function () {
  1873. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1874. };
  1875. if (url.indexOf("file:") !== -1) {
  1876. var fileName = url.substring(5);
  1877. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1878. } else {
  1879. if (database && database.enableSceneOffline) {
  1880. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1881. } else {
  1882. noIndexedDB();
  1883. }
  1884. }
  1885. };
  1886. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1887. var reader = new FileReader();
  1888. reader.onload = function (e) {
  1889. callback(e.target.result);
  1890. };
  1891. reader.onprogress = progressCallBack;
  1892. if (!useArrayBuffer) {
  1893. reader.readAsText(fileToLoad);
  1894. } else {
  1895. reader.readAsArrayBuffer(fileToLoad);
  1896. }
  1897. };
  1898. Tools.CheckExtends = function (v, min, max) {
  1899. if (v.x < min.x)
  1900. min.x = v.x;
  1901. if (v.y < min.y)
  1902. min.y = v.y;
  1903. if (v.z < min.z)
  1904. min.z = v.z;
  1905. if (v.x > max.x)
  1906. max.x = v.x;
  1907. if (v.y > max.y)
  1908. max.y = v.y;
  1909. if (v.z > max.z)
  1910. max.z = v.z;
  1911. };
  1912. Tools.WithinEpsilon = function (a, b) {
  1913. var num = a - b;
  1914. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1915. };
  1916. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1917. for (var prop in source) {
  1918. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1919. continue;
  1920. }
  1921. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1922. continue;
  1923. }
  1924. var sourceValue = source[prop];
  1925. var typeOfSourceValue = typeof sourceValue;
  1926. if (typeOfSourceValue == "function") {
  1927. continue;
  1928. }
  1929. if (typeOfSourceValue == "object") {
  1930. if (sourceValue instanceof Array) {
  1931. destination[prop] = [];
  1932. if (sourceValue.length > 0) {
  1933. if (typeof sourceValue[0] == "object") {
  1934. for (var index = 0; index < sourceValue.length; index++) {
  1935. var clonedValue = cloneValue(sourceValue[index], destination);
  1936. if (destination[prop].indexOf(clonedValue) === -1) {
  1937. destination[prop].push(clonedValue);
  1938. }
  1939. }
  1940. } else {
  1941. destination[prop] = sourceValue.slice(0);
  1942. }
  1943. }
  1944. } else {
  1945. destination[prop] = cloneValue(sourceValue, destination);
  1946. }
  1947. } else {
  1948. destination[prop] = sourceValue;
  1949. }
  1950. }
  1951. };
  1952. Tools.IsEmpty = function (obj) {
  1953. for (var i in obj) {
  1954. return false;
  1955. }
  1956. return true;
  1957. };
  1958. Tools.RegisterTopRootEvents = function (events) {
  1959. for (var index = 0; index < events.length; index++) {
  1960. var event = events[index];
  1961. window.addEventListener(event.name, event.handler, false);
  1962. try {
  1963. if (window.parent) {
  1964. window.parent.addEventListener(event.name, event.handler, false);
  1965. }
  1966. } catch (e) {
  1967. }
  1968. }
  1969. };
  1970. Tools.UnregisterTopRootEvents = function (events) {
  1971. for (var index = 0; index < events.length; index++) {
  1972. var event = events[index];
  1973. window.removeEventListener(event.name, event.handler);
  1974. try {
  1975. if (window.parent) {
  1976. window.parent.removeEventListener(event.name, event.handler);
  1977. }
  1978. } catch (e) {
  1979. }
  1980. }
  1981. };
  1982. Tools.GetFps = function () {
  1983. return fps;
  1984. };
  1985. Tools.GetDeltaTime = function () {
  1986. return deltaTime;
  1987. };
  1988. Tools._MeasureFps = function () {
  1989. previousFramesDuration.push((new Date).getTime());
  1990. var length = previousFramesDuration.length;
  1991. if (length >= 2) {
  1992. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  1993. }
  1994. if (length >= fpsRange) {
  1995. if (length > fpsRange) {
  1996. previousFramesDuration.splice(0, 1);
  1997. length = previousFramesDuration.length;
  1998. }
  1999. var sum = 0;
  2000. for (var id = 0; id < length - 1; id++) {
  2001. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2002. }
  2003. fps = 1000.0 / (sum / (length - 1));
  2004. }
  2005. };
  2006. Tools.CreateScreenshot = function (engine, camera, size) {
  2007. var width;
  2008. var height;
  2009. var scene = camera.getScene();
  2010. var previousCamera = null;
  2011. if (scene.activeCamera !== camera) {
  2012. previousCamera = scene.activeCamera;
  2013. scene.activeCamera = camera;
  2014. }
  2015. if (size.precision) {
  2016. width = Math.round(engine.getRenderWidth() * size.precision);
  2017. height = Math.round(width / engine.getAspectRatio(camera));
  2018. size = { width: width, height: height };
  2019. } else if (size.width && size.height) {
  2020. width = size.width;
  2021. height = size.height;
  2022. } else if (size.width && !size.height) {
  2023. width = size.width;
  2024. height = Math.round(width / engine.getAspectRatio(camera));
  2025. size = { width: width, height: height };
  2026. } else if (size.height && !size.width) {
  2027. height = size.height;
  2028. width = Math.round(height * engine.getAspectRatio(camera));
  2029. size = { width: width, height: height };
  2030. } else if (!isNaN(size)) {
  2031. height = size;
  2032. width = size;
  2033. } else {
  2034. Tools.Error("Invalid 'size' parameter !");
  2035. return;
  2036. }
  2037. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2038. texture.renderList = engine.scenes[0].meshes;
  2039. texture.onAfterRender = function () {
  2040. var numberOfChannelsByLine = width * 4;
  2041. var halfHeight = height / 2;
  2042. var data = engine.readPixels(0, 0, width, height);
  2043. for (var i = 0; i < halfHeight; i++) {
  2044. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2045. var currentCell = j + i * numberOfChannelsByLine;
  2046. var targetLine = height - i - 1;
  2047. var targetCell = j + targetLine * numberOfChannelsByLine;
  2048. var temp = data[currentCell];
  2049. data[currentCell] = data[targetCell];
  2050. data[targetCell] = temp;
  2051. }
  2052. }
  2053. if (!screenshotCanvas) {
  2054. screenshotCanvas = document.createElement('canvas');
  2055. }
  2056. screenshotCanvas.width = width;
  2057. screenshotCanvas.height = height;
  2058. var context = screenshotCanvas.getContext('2d');
  2059. var imageData = context.createImageData(width, height);
  2060. imageData.data.set(data);
  2061. context.putImageData(imageData, 0, 0);
  2062. var base64Image = screenshotCanvas.toDataURL();
  2063. if (("download" in document.createElement("a"))) {
  2064. var a = window.document.createElement("a");
  2065. a.href = base64Image;
  2066. var date = new Date();
  2067. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2068. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2069. window.document.body.appendChild(a);
  2070. a.addEventListener("click", function () {
  2071. a.parentElement.removeChild(a);
  2072. });
  2073. a.click();
  2074. } else {
  2075. var newWindow = window.open("");
  2076. var img = newWindow.document.createElement("img");
  2077. img.src = base64Image;
  2078. newWindow.document.body.appendChild(img);
  2079. }
  2080. };
  2081. texture.render(true);
  2082. texture.dispose();
  2083. if (previousCamera) {
  2084. scene.activeCamera = previousCamera;
  2085. }
  2086. };
  2087. Tools.ValidateXHRData = function (xhr, dataType) {
  2088. if (typeof dataType === "undefined") { dataType = 7; }
  2089. try {
  2090. if (dataType & 1) {
  2091. if (xhr.responseText && xhr.responseText.length > 0) {
  2092. return true;
  2093. } else if (dataType === 1) {
  2094. return false;
  2095. }
  2096. }
  2097. if (dataType & 2) {
  2098. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2099. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2100. return true;
  2101. } else if (dataType === 2) {
  2102. return false;
  2103. }
  2104. }
  2105. if (dataType & 4) {
  2106. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2107. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2108. return true;
  2109. } else {
  2110. return false;
  2111. }
  2112. }
  2113. } catch (e) {
  2114. }
  2115. return false;
  2116. };
  2117. Object.defineProperty(Tools, "NoneLogLevel", {
  2118. get: function () {
  2119. return Tools._NoneLogLevel;
  2120. },
  2121. enumerable: true,
  2122. configurable: true
  2123. });
  2124. Object.defineProperty(Tools, "MessageLogLevel", {
  2125. get: function () {
  2126. return Tools._MessageLogLevel;
  2127. },
  2128. enumerable: true,
  2129. configurable: true
  2130. });
  2131. Object.defineProperty(Tools, "WarningLogLevel", {
  2132. get: function () {
  2133. return Tools._WarningLogLevel;
  2134. },
  2135. enumerable: true,
  2136. configurable: true
  2137. });
  2138. Object.defineProperty(Tools, "ErrorLogLevel", {
  2139. get: function () {
  2140. return Tools._ErrorLogLevel;
  2141. },
  2142. enumerable: true,
  2143. configurable: true
  2144. });
  2145. Object.defineProperty(Tools, "AllLogLevel", {
  2146. get: function () {
  2147. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2148. },
  2149. enumerable: true,
  2150. configurable: true
  2151. });
  2152. Tools._FormatMessage = function (message) {
  2153. var padStr = function (i) {
  2154. return (i < 10) ? "0" + i : "" + i;
  2155. };
  2156. var date = new Date();
  2157. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2158. };
  2159. Tools._LogDisabled = function (message) {
  2160. };
  2161. Tools._LogEnabled = function (message) {
  2162. console.log(Tools._FormatMessage(message));
  2163. };
  2164. Tools._WarnDisabled = function (message) {
  2165. };
  2166. Tools._WarnEnabled = function (message) {
  2167. console.warn(Tools._FormatMessage(message));
  2168. };
  2169. Tools._ErrorDisabled = function (message) {
  2170. };
  2171. Tools._ErrorEnabled = function (message) {
  2172. console.error(Tools._FormatMessage(message));
  2173. };
  2174. Object.defineProperty(Tools, "LogLevels", {
  2175. set: function (level) {
  2176. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2177. Tools.Log = Tools._LogEnabled;
  2178. } else {
  2179. Tools.Log = Tools._LogDisabled;
  2180. }
  2181. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2182. Tools.Warn = Tools._WarnEnabled;
  2183. } else {
  2184. Tools.Warn = Tools._WarnDisabled;
  2185. }
  2186. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2187. Tools.Error = Tools._ErrorEnabled;
  2188. } else {
  2189. Tools.Error = Tools._ErrorDisabled;
  2190. }
  2191. },
  2192. enumerable: true,
  2193. configurable: true
  2194. });
  2195. Tools.BaseUrl = "";
  2196. Tools._NoneLogLevel = 0;
  2197. Tools._MessageLogLevel = 1;
  2198. Tools._WarningLogLevel = 2;
  2199. Tools._ErrorLogLevel = 4;
  2200. Tools.Log = Tools._LogEnabled;
  2201. Tools.Warn = Tools._WarnEnabled;
  2202. Tools.Error = Tools._ErrorEnabled;
  2203. return Tools;
  2204. })();
  2205. BABYLON.Tools = Tools;
  2206. })(BABYLON || (BABYLON = {}));
  2207. var BABYLON;
  2208. (function (BABYLON) {
  2209. var _DepthCullingState = (function () {
  2210. function _DepthCullingState() {
  2211. this._isDepthTestDirty = false;
  2212. this._isDepthMaskDirty = false;
  2213. this._isDepthFuncDirty = false;
  2214. this._isCullFaceDirty = false;
  2215. this._isCullDirty = false;
  2216. }
  2217. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2218. get: function () {
  2219. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2220. },
  2221. enumerable: true,
  2222. configurable: true
  2223. });
  2224. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2225. get: function () {
  2226. return this._cullFace;
  2227. },
  2228. set: function (value) {
  2229. if (this._cullFace === value) {
  2230. return;
  2231. }
  2232. this._cullFace = value;
  2233. this._isCullFaceDirty = true;
  2234. },
  2235. enumerable: true,
  2236. configurable: true
  2237. });
  2238. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2239. get: function () {
  2240. return this._cull;
  2241. },
  2242. set: function (value) {
  2243. if (this._cull === value) {
  2244. return;
  2245. }
  2246. this._cull = value;
  2247. this._isCullDirty = true;
  2248. },
  2249. enumerable: true,
  2250. configurable: true
  2251. });
  2252. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2253. get: function () {
  2254. return this._depthFunc;
  2255. },
  2256. set: function (value) {
  2257. if (this._depthFunc === value) {
  2258. return;
  2259. }
  2260. this._depthFunc = value;
  2261. this._isDepthFuncDirty = true;
  2262. },
  2263. enumerable: true,
  2264. configurable: true
  2265. });
  2266. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2267. get: function () {
  2268. return this._depthMask;
  2269. },
  2270. set: function (value) {
  2271. if (this._depthMask === value) {
  2272. return;
  2273. }
  2274. this._depthMask = value;
  2275. this._isDepthMaskDirty = true;
  2276. },
  2277. enumerable: true,
  2278. configurable: true
  2279. });
  2280. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2281. get: function () {
  2282. return this._depthTest;
  2283. },
  2284. set: function (value) {
  2285. if (this._depthTest === value) {
  2286. return;
  2287. }
  2288. this._depthTest = value;
  2289. this._isDepthTestDirty = true;
  2290. },
  2291. enumerable: true,
  2292. configurable: true
  2293. });
  2294. _DepthCullingState.prototype.reset = function () {
  2295. this._depthMask = true;
  2296. this._depthTest = true;
  2297. this._depthFunc = null;
  2298. this._cull = null;
  2299. this._cullFace = null;
  2300. this._isDepthTestDirty = true;
  2301. this._isDepthMaskDirty = true;
  2302. this._isDepthFuncDirty = false;
  2303. this._isCullFaceDirty = false;
  2304. this._isCullDirty = false;
  2305. };
  2306. _DepthCullingState.prototype.apply = function (gl) {
  2307. if (!this.isDirty) {
  2308. return;
  2309. }
  2310. if (this._isCullDirty) {
  2311. if (this.cull === true) {
  2312. gl.enable(gl.CULL_FACE);
  2313. } else if (this.cull === false) {
  2314. gl.disable(gl.CULL_FACE);
  2315. }
  2316. this._isCullDirty = false;
  2317. }
  2318. if (this._isCullFaceDirty) {
  2319. gl.cullFace(this.cullFace);
  2320. this._isCullFaceDirty = false;
  2321. }
  2322. if (this._isDepthMaskDirty) {
  2323. gl.depthMask(this.depthMask);
  2324. this._isDepthMaskDirty = false;
  2325. }
  2326. if (this._isDepthTestDirty) {
  2327. if (this.depthTest === true) {
  2328. gl.enable(gl.DEPTH_TEST);
  2329. } else if (this.depthTest === false) {
  2330. gl.disable(gl.DEPTH_TEST);
  2331. }
  2332. this._isDepthTestDirty = false;
  2333. }
  2334. if (this._isDepthFuncDirty) {
  2335. gl.depthFunc(this.depthFunc);
  2336. this._isDepthFuncDirty = false;
  2337. }
  2338. };
  2339. return _DepthCullingState;
  2340. })();
  2341. BABYLON._DepthCullingState = _DepthCullingState;
  2342. var _AlphaState = (function () {
  2343. function _AlphaState() {
  2344. this._isAlphaBlendDirty = false;
  2345. this._isBlendFunctionParametersDirty = false;
  2346. this._alphaBlend = false;
  2347. this._blendFunctionParameters = new Array(4);
  2348. }
  2349. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2350. get: function () {
  2351. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2352. },
  2353. enumerable: true,
  2354. configurable: true
  2355. });
  2356. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2357. get: function () {
  2358. return this._alphaBlend;
  2359. },
  2360. set: function (value) {
  2361. if (this._alphaBlend === value) {
  2362. return;
  2363. }
  2364. this._alphaBlend = value;
  2365. this._isAlphaBlendDirty = true;
  2366. },
  2367. enumerable: true,
  2368. configurable: true
  2369. });
  2370. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2371. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2372. return;
  2373. }
  2374. this._blendFunctionParameters[0] = value0;
  2375. this._blendFunctionParameters[1] = value1;
  2376. this._blendFunctionParameters[2] = value2;
  2377. this._blendFunctionParameters[3] = value3;
  2378. this._isBlendFunctionParametersDirty = true;
  2379. };
  2380. _AlphaState.prototype.reset = function () {
  2381. this._alphaBlend = false;
  2382. this._blendFunctionParameters[0] = null;
  2383. this._blendFunctionParameters[1] = null;
  2384. this._blendFunctionParameters[2] = null;
  2385. this._blendFunctionParameters[3] = null;
  2386. this._isAlphaBlendDirty = true;
  2387. this._isBlendFunctionParametersDirty = false;
  2388. };
  2389. _AlphaState.prototype.apply = function (gl) {
  2390. if (!this.isDirty) {
  2391. return;
  2392. }
  2393. if (this._isAlphaBlendDirty) {
  2394. if (this._alphaBlend === true) {
  2395. gl.enable(gl.BLEND);
  2396. } else if (this._alphaBlend === false) {
  2397. gl.disable(gl.BLEND);
  2398. }
  2399. this._isAlphaBlendDirty = false;
  2400. }
  2401. if (this._isBlendFunctionParametersDirty) {
  2402. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2403. this._isBlendFunctionParametersDirty = false;
  2404. }
  2405. };
  2406. return _AlphaState;
  2407. })();
  2408. BABYLON._AlphaState = _AlphaState;
  2409. var compileShader = function (gl, source, type, defines) {
  2410. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2411. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2412. gl.compileShader(shader);
  2413. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2414. throw new Error(gl.getShaderInfoLog(shader));
  2415. }
  2416. return shader;
  2417. };
  2418. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2419. var magFilter = gl.NEAREST;
  2420. var minFilter = gl.NEAREST;
  2421. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2422. magFilter = gl.LINEAR;
  2423. if (generateMipMaps) {
  2424. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2425. } else {
  2426. minFilter = gl.LINEAR;
  2427. }
  2428. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2429. magFilter = gl.LINEAR;
  2430. if (generateMipMaps) {
  2431. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2432. } else {
  2433. minFilter = gl.LINEAR;
  2434. }
  2435. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2436. magFilter = gl.NEAREST;
  2437. if (generateMipMaps) {
  2438. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2439. } else {
  2440. minFilter = gl.NEAREST;
  2441. }
  2442. }
  2443. return {
  2444. min: minFilter,
  2445. mag: magFilter
  2446. };
  2447. };
  2448. var getExponantOfTwo = function (value, max) {
  2449. var count = 1;
  2450. do {
  2451. count *= 2;
  2452. } while(count < value);
  2453. if (count > max)
  2454. count = max;
  2455. return count;
  2456. };
  2457. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2458. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2459. var engine = scene.getEngine();
  2460. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2461. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2462. gl.bindTexture(gl.TEXTURE_2D, texture);
  2463. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2464. processFunction(potWidth, potHeight);
  2465. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2468. if (!noMipmap && !isCompressed) {
  2469. gl.generateMipmap(gl.TEXTURE_2D);
  2470. }
  2471. gl.bindTexture(gl.TEXTURE_2D, null);
  2472. engine._activeTexturesCache = [];
  2473. texture._baseWidth = width;
  2474. texture._baseHeight = height;
  2475. texture._width = potWidth;
  2476. texture._height = potHeight;
  2477. texture.isReady = true;
  2478. scene._removePendingData(texture);
  2479. };
  2480. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2481. var img;
  2482. var onload = function () {
  2483. loadedImages.push(img);
  2484. scene._removePendingData(img);
  2485. if (index != extensions.length - 1) {
  2486. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2487. } else {
  2488. onfinish(loadedImages);
  2489. }
  2490. };
  2491. var onerror = function () {
  2492. scene._removePendingData(img);
  2493. };
  2494. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2495. scene._addPendingData(img);
  2496. };
  2497. var EngineCapabilities = (function () {
  2498. function EngineCapabilities() {
  2499. }
  2500. return EngineCapabilities;
  2501. })();
  2502. BABYLON.EngineCapabilities = EngineCapabilities;
  2503. var Engine = (function () {
  2504. function Engine(canvas, antialias, options) {
  2505. var _this = this;
  2506. this.isFullscreen = false;
  2507. this.isPointerLock = false;
  2508. this.forceWireframe = false;
  2509. this.cullBackFaces = true;
  2510. this.renderEvenInBackground = true;
  2511. this.scenes = new Array();
  2512. this._windowIsBackground = false;
  2513. this._runningLoop = false;
  2514. this._loadingDivBackgroundColor = "black";
  2515. this._depthCullingState = new _DepthCullingState();
  2516. this._alphaState = new _AlphaState();
  2517. this._loadedTexturesCache = new Array();
  2518. this._activeTexturesCache = new Array();
  2519. this._compiledEffects = {};
  2520. this._renderingCanvas = canvas;
  2521. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2522. options = options || {};
  2523. options.antialias = antialias;
  2524. try {
  2525. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2526. } catch (e) {
  2527. throw new Error("WebGL not supported");
  2528. }
  2529. if (!this._gl) {
  2530. throw new Error("WebGL not supported");
  2531. }
  2532. this._onBlur = function () {
  2533. _this._windowIsBackground = true;
  2534. };
  2535. this._onFocus = function () {
  2536. _this._windowIsBackground = false;
  2537. };
  2538. window.addEventListener("blur", this._onBlur);
  2539. window.addEventListener("focus", this._onFocus);
  2540. this._workingCanvas = document.createElement("canvas");
  2541. this._workingContext = this._workingCanvas.getContext("2d");
  2542. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2543. this.resize();
  2544. this._caps = new EngineCapabilities();
  2545. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2546. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2547. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2548. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2549. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2550. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2551. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2552. 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');
  2553. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2554. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2555. this.setDepthBuffer(true);
  2556. this.setDepthFunctionToLessOrEqual();
  2557. this.setDepthWrite(true);
  2558. this._onFullscreenChange = function () {
  2559. if (document.fullscreen !== undefined) {
  2560. _this.isFullscreen = document.fullscreen;
  2561. } else if (document.mozFullScreen !== undefined) {
  2562. _this.isFullscreen = document.mozFullScreen;
  2563. } else if (document.webkitIsFullScreen !== undefined) {
  2564. _this.isFullscreen = document.webkitIsFullScreen;
  2565. } else if (document.msIsFullScreen !== undefined) {
  2566. _this.isFullscreen = document.msIsFullScreen;
  2567. }
  2568. if (_this.isFullscreen && _this._pointerLockRequested) {
  2569. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2570. if (canvas.requestPointerLock) {
  2571. canvas.requestPointerLock();
  2572. }
  2573. }
  2574. };
  2575. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2576. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2577. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2578. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2579. this._onPointerLockChange = function () {
  2580. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2581. };
  2582. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2583. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2584. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2585. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2586. }
  2587. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2588. get: function () {
  2589. return Engine._ALPHA_DISABLE;
  2590. },
  2591. enumerable: true,
  2592. configurable: true
  2593. });
  2594. Object.defineProperty(Engine, "ALPHA_ADD", {
  2595. get: function () {
  2596. return Engine._ALPHA_ADD;
  2597. },
  2598. enumerable: true,
  2599. configurable: true
  2600. });
  2601. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2602. get: function () {
  2603. return Engine._ALPHA_COMBINE;
  2604. },
  2605. enumerable: true,
  2606. configurable: true
  2607. });
  2608. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2609. get: function () {
  2610. return Engine._DELAYLOADSTATE_NONE;
  2611. },
  2612. enumerable: true,
  2613. configurable: true
  2614. });
  2615. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2616. get: function () {
  2617. return Engine._DELAYLOADSTATE_LOADED;
  2618. },
  2619. enumerable: true,
  2620. configurable: true
  2621. });
  2622. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2623. get: function () {
  2624. return Engine._DELAYLOADSTATE_LOADING;
  2625. },
  2626. enumerable: true,
  2627. configurable: true
  2628. });
  2629. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2630. get: function () {
  2631. return Engine._DELAYLOADSTATE_NOTLOADED;
  2632. },
  2633. enumerable: true,
  2634. configurable: true
  2635. });
  2636. Object.defineProperty(Engine, "Version", {
  2637. get: function () {
  2638. return "1.14.0";
  2639. },
  2640. enumerable: true,
  2641. configurable: true
  2642. });
  2643. Engine.prototype.getAspectRatio = function (camera) {
  2644. var viewport = camera.viewport;
  2645. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2646. };
  2647. Engine.prototype.getRenderWidth = function () {
  2648. if (this._currentRenderTarget) {
  2649. return this._currentRenderTarget._width;
  2650. }
  2651. return this._renderingCanvas.width;
  2652. };
  2653. Engine.prototype.getRenderHeight = function () {
  2654. if (this._currentRenderTarget) {
  2655. return this._currentRenderTarget._height;
  2656. }
  2657. return this._renderingCanvas.height;
  2658. };
  2659. Engine.prototype.getRenderingCanvas = function () {
  2660. return this._renderingCanvas;
  2661. };
  2662. Engine.prototype.getRenderingCanvasClientRect = function () {
  2663. return this._renderingCanvas.getBoundingClientRect();
  2664. };
  2665. Engine.prototype.setHardwareScalingLevel = function (level) {
  2666. this._hardwareScalingLevel = level;
  2667. this.resize();
  2668. };
  2669. Engine.prototype.getHardwareScalingLevel = function () {
  2670. return this._hardwareScalingLevel;
  2671. };
  2672. Engine.prototype.getLoadedTexturesCache = function () {
  2673. return this._loadedTexturesCache;
  2674. };
  2675. Engine.prototype.getCaps = function () {
  2676. return this._caps;
  2677. };
  2678. Engine.prototype.setDepthFunctionToGreater = function () {
  2679. this._depthCullingState.depthFunc = this._gl.GREATER;
  2680. };
  2681. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2682. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2683. };
  2684. Engine.prototype.setDepthFunctionToLess = function () {
  2685. this._depthCullingState.depthFunc = this._gl.LESS;
  2686. };
  2687. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2688. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2689. };
  2690. Engine.prototype.stopRenderLoop = function () {
  2691. this._renderFunction = null;
  2692. this._runningLoop = false;
  2693. };
  2694. Engine.prototype._renderLoop = function () {
  2695. var _this = this;
  2696. var shouldRender = true;
  2697. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2698. shouldRender = false;
  2699. }
  2700. if (shouldRender) {
  2701. this.beginFrame();
  2702. if (this._renderFunction) {
  2703. this._renderFunction();
  2704. }
  2705. this.endFrame();
  2706. }
  2707. if (this._runningLoop) {
  2708. BABYLON.Tools.QueueNewFrame(function () {
  2709. _this._renderLoop();
  2710. });
  2711. }
  2712. };
  2713. Engine.prototype.runRenderLoop = function (renderFunction) {
  2714. var _this = this;
  2715. this._runningLoop = true;
  2716. this._renderFunction = renderFunction;
  2717. BABYLON.Tools.QueueNewFrame(function () {
  2718. _this._renderLoop();
  2719. });
  2720. };
  2721. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2722. if (this.isFullscreen) {
  2723. BABYLON.Tools.ExitFullscreen();
  2724. } else {
  2725. this._pointerLockRequested = requestPointerLock;
  2726. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2727. }
  2728. };
  2729. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2730. this.applyStates();
  2731. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2732. if (this._depthCullingState.depthMask) {
  2733. this._gl.clearDepth(1.0);
  2734. }
  2735. var mode = 0;
  2736. if (backBuffer)
  2737. mode |= this._gl.COLOR_BUFFER_BIT;
  2738. if (depthStencil && this._depthCullingState.depthMask)
  2739. mode |= this._gl.DEPTH_BUFFER_BIT;
  2740. this._gl.clear(mode);
  2741. };
  2742. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2743. var width = requiredWidth || this._renderingCanvas.width;
  2744. var height = requiredHeight || this._renderingCanvas.height;
  2745. var x = viewport.x || 0;
  2746. var y = viewport.y || 0;
  2747. this._cachedViewport = viewport;
  2748. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2749. };
  2750. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2751. this._cachedViewport = null;
  2752. this._gl.viewport(x, y, width, height);
  2753. };
  2754. Engine.prototype.beginFrame = function () {
  2755. BABYLON.Tools._MeasureFps();
  2756. };
  2757. Engine.prototype.endFrame = function () {
  2758. this.flushFramebuffer();
  2759. };
  2760. Engine.prototype.resize = function () {
  2761. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2762. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2763. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2764. };
  2765. Engine.prototype.bindFramebuffer = function (texture) {
  2766. this._currentRenderTarget = texture;
  2767. var gl = this._gl;
  2768. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2769. this._gl.viewport(0, 0, texture._width, texture._height);
  2770. this.wipeCaches();
  2771. };
  2772. Engine.prototype.unBindFramebuffer = function (texture) {
  2773. this._currentRenderTarget = null;
  2774. if (texture.generateMipMaps) {
  2775. var gl = this._gl;
  2776. gl.bindTexture(gl.TEXTURE_2D, texture);
  2777. gl.generateMipmap(gl.TEXTURE_2D);
  2778. gl.bindTexture(gl.TEXTURE_2D, null);
  2779. }
  2780. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2781. };
  2782. Engine.prototype.flushFramebuffer = function () {
  2783. this._gl.flush();
  2784. };
  2785. Engine.prototype.restoreDefaultFramebuffer = function () {
  2786. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2787. this.setViewport(this._cachedViewport);
  2788. this.wipeCaches();
  2789. };
  2790. Engine.prototype._resetVertexBufferBinding = function () {
  2791. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2792. this._cachedVertexBuffers = null;
  2793. };
  2794. Engine.prototype.createVertexBuffer = function (vertices) {
  2795. var vbo = this._gl.createBuffer();
  2796. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2797. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2798. this._resetVertexBufferBinding();
  2799. vbo.references = 1;
  2800. return vbo;
  2801. };
  2802. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2803. var vbo = this._gl.createBuffer();
  2804. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2805. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2806. this._resetVertexBufferBinding();
  2807. vbo.references = 1;
  2808. return vbo;
  2809. };
  2810. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2811. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2812. if (vertices instanceof Float32Array) {
  2813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2814. } else {
  2815. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2816. }
  2817. this._resetVertexBufferBinding();
  2818. };
  2819. Engine.prototype._resetIndexBufferBinding = function () {
  2820. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2821. this._cachedIndexBuffer = null;
  2822. };
  2823. Engine.prototype.createIndexBuffer = function (indices) {
  2824. var vbo = this._gl.createBuffer();
  2825. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2826. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2827. this._resetIndexBufferBinding();
  2828. vbo.references = 1;
  2829. return vbo;
  2830. };
  2831. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2832. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2833. this._cachedVertexBuffers = vertexBuffer;
  2834. this._cachedEffectForVertexBuffers = effect;
  2835. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2836. var offset = 0;
  2837. for (var index = 0; index < vertexDeclaration.length; index++) {
  2838. var order = effect.getAttributeLocation(index);
  2839. if (order >= 0) {
  2840. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2841. }
  2842. offset += vertexDeclaration[index] * 4;
  2843. }
  2844. }
  2845. if (this._cachedIndexBuffer !== indexBuffer) {
  2846. this._cachedIndexBuffer = indexBuffer;
  2847. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2848. }
  2849. };
  2850. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2851. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2852. this._cachedVertexBuffers = vertexBuffers;
  2853. this._cachedEffectForVertexBuffers = effect;
  2854. var attributes = effect.getAttributesNames();
  2855. for (var index = 0; index < attributes.length; index++) {
  2856. var order = effect.getAttributeLocation(index);
  2857. if (order >= 0) {
  2858. var vertexBuffer = vertexBuffers[attributes[index]];
  2859. if (!vertexBuffer) {
  2860. continue;
  2861. }
  2862. var stride = vertexBuffer.getStrideSize();
  2863. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2864. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2865. }
  2866. }
  2867. }
  2868. if (this._cachedIndexBuffer !== indexBuffer) {
  2869. this._cachedIndexBuffer = indexBuffer;
  2870. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2871. }
  2872. };
  2873. Engine.prototype._releaseBuffer = function (buffer) {
  2874. buffer.references--;
  2875. if (buffer.references === 0) {
  2876. this._gl.deleteBuffer(buffer);
  2877. return true;
  2878. }
  2879. return false;
  2880. };
  2881. Engine.prototype.createInstancesBuffer = function (capacity) {
  2882. var buffer = this._gl.createBuffer();
  2883. buffer.capacity = capacity;
  2884. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2885. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2886. return buffer;
  2887. };
  2888. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2889. this._gl.deleteBuffer(buffer);
  2890. };
  2891. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2893. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2894. for (var index = 0; index < 4; index++) {
  2895. var offsetLocation = offsetLocations[index];
  2896. this._gl.enableVertexAttribArray(offsetLocation);
  2897. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2898. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2899. }
  2900. };
  2901. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2902. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2903. for (var index = 0; index < 4; index++) {
  2904. var offsetLocation = offsetLocations[index];
  2905. this._gl.disableVertexAttribArray(offsetLocation);
  2906. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2907. }
  2908. };
  2909. Engine.prototype.applyStates = function () {
  2910. this._depthCullingState.apply(this._gl);
  2911. this._alphaState.apply(this._gl);
  2912. };
  2913. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2914. this.applyStates();
  2915. if (instancesCount) {
  2916. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2917. return;
  2918. }
  2919. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2920. };
  2921. Engine.prototype._releaseEffect = function (effect) {
  2922. if (this._compiledEffects[effect._key]) {
  2923. delete this._compiledEffects[effect._key];
  2924. if (effect.getProgram()) {
  2925. this._gl.deleteProgram(effect.getProgram());
  2926. }
  2927. }
  2928. };
  2929. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2930. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2931. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2932. var name = vertex + "+" + fragment + "@" + defines;
  2933. if (this._compiledEffects[name]) {
  2934. return this._compiledEffects[name];
  2935. }
  2936. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2937. effect._key = name;
  2938. this._compiledEffects[name] = effect;
  2939. return effect;
  2940. };
  2941. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2942. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2943. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2944. var shaderProgram = this._gl.createProgram();
  2945. this._gl.attachShader(shaderProgram, vertexShader);
  2946. this._gl.attachShader(shaderProgram, fragmentShader);
  2947. this._gl.linkProgram(shaderProgram);
  2948. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2949. if (!linked) {
  2950. var error = this._gl.getProgramInfoLog(shaderProgram);
  2951. if (error) {
  2952. throw new Error(error);
  2953. }
  2954. }
  2955. this._gl.deleteShader(vertexShader);
  2956. this._gl.deleteShader(fragmentShader);
  2957. return shaderProgram;
  2958. };
  2959. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2960. var results = [];
  2961. for (var index = 0; index < uniformsNames.length; index++) {
  2962. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2963. }
  2964. return results;
  2965. };
  2966. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2967. var results = [];
  2968. for (var index = 0; index < attributesNames.length; index++) {
  2969. try {
  2970. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2971. } catch (e) {
  2972. results.push(-1);
  2973. }
  2974. }
  2975. return results;
  2976. };
  2977. Engine.prototype.enableEffect = function (effect) {
  2978. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  2979. return;
  2980. }
  2981. this._vertexAttribArrays = this._vertexAttribArrays || [];
  2982. this._gl.useProgram(effect.getProgram());
  2983. for (var i in this._vertexAttribArrays) {
  2984. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  2985. continue;
  2986. }
  2987. this._vertexAttribArrays[i] = false;
  2988. this._gl.disableVertexAttribArray(i);
  2989. }
  2990. var attributesCount = effect.getAttributesCount();
  2991. for (var index = 0; index < attributesCount; index++) {
  2992. var order = effect.getAttributeLocation(index);
  2993. if (order >= 0) {
  2994. this._vertexAttribArrays[order] = true;
  2995. this._gl.enableVertexAttribArray(order);
  2996. }
  2997. }
  2998. this._currentEffect = effect;
  2999. };
  3000. Engine.prototype.setArray = function (uniform, array) {
  3001. if (!uniform)
  3002. return;
  3003. this._gl.uniform1fv(uniform, array);
  3004. };
  3005. Engine.prototype.setMatrices = function (uniform, matrices) {
  3006. if (!uniform)
  3007. return;
  3008. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3009. };
  3010. Engine.prototype.setMatrix = function (uniform, matrix) {
  3011. if (!uniform)
  3012. return;
  3013. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3014. };
  3015. Engine.prototype.setFloat = function (uniform, value) {
  3016. if (!uniform)
  3017. return;
  3018. this._gl.uniform1f(uniform, value);
  3019. };
  3020. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3021. if (!uniform)
  3022. return;
  3023. this._gl.uniform2f(uniform, x, y);
  3024. };
  3025. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3026. if (!uniform)
  3027. return;
  3028. this._gl.uniform3f(uniform, x, y, z);
  3029. };
  3030. Engine.prototype.setBool = function (uniform, bool) {
  3031. if (!uniform)
  3032. return;
  3033. this._gl.uniform1i(uniform, bool);
  3034. };
  3035. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3036. if (!uniform)
  3037. return;
  3038. this._gl.uniform4f(uniform, x, y, z, w);
  3039. };
  3040. Engine.prototype.setColor3 = function (uniform, color3) {
  3041. if (!uniform)
  3042. return;
  3043. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3044. };
  3045. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3046. if (!uniform)
  3047. return;
  3048. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3049. };
  3050. Engine.prototype.setState = function (culling, force) {
  3051. if (this._depthCullingState.cull !== culling || force) {
  3052. if (culling) {
  3053. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3054. this._depthCullingState.cull = true;
  3055. } else {
  3056. this._depthCullingState.cull = false;
  3057. }
  3058. }
  3059. };
  3060. Engine.prototype.setDepthBuffer = function (enable) {
  3061. this._depthCullingState.depthTest = enable;
  3062. };
  3063. Engine.prototype.getDepthWrite = function () {
  3064. return this._depthCullingState.depthMask;
  3065. };
  3066. Engine.prototype.setDepthWrite = function (enable) {
  3067. this._depthCullingState.depthMask = enable;
  3068. };
  3069. Engine.prototype.setColorWrite = function (enable) {
  3070. this._gl.colorMask(enable, enable, enable, enable);
  3071. };
  3072. Engine.prototype.setAlphaMode = function (mode) {
  3073. switch (mode) {
  3074. case BABYLON.Engine.ALPHA_DISABLE:
  3075. this.setDepthWrite(true);
  3076. this._alphaState.alphaBlend = false;
  3077. break;
  3078. case BABYLON.Engine.ALPHA_COMBINE:
  3079. this.setDepthWrite(false);
  3080. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3081. this._alphaState.alphaBlend = true;
  3082. break;
  3083. case BABYLON.Engine.ALPHA_ADD:
  3084. this.setDepthWrite(false);
  3085. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3086. this._alphaState.alphaBlend = true;
  3087. break;
  3088. }
  3089. };
  3090. Engine.prototype.setAlphaTesting = function (enable) {
  3091. this._alphaTest = enable;
  3092. };
  3093. Engine.prototype.getAlphaTesting = function () {
  3094. return this._alphaTest;
  3095. };
  3096. Engine.prototype.wipeCaches = function () {
  3097. this._activeTexturesCache = [];
  3098. this._currentEffect = null;
  3099. this._depthCullingState.reset();
  3100. this._alphaState.reset();
  3101. this._cachedVertexBuffers = null;
  3102. this._cachedIndexBuffer = null;
  3103. this._cachedEffectForVertexBuffers = null;
  3104. };
  3105. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3106. var gl = this._gl;
  3107. gl.bindTexture(gl.TEXTURE_2D, texture);
  3108. var magFilter = gl.NEAREST;
  3109. var minFilter = gl.NEAREST;
  3110. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3111. magFilter = gl.LINEAR;
  3112. minFilter = gl.LINEAR;
  3113. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3114. magFilter = gl.LINEAR;
  3115. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3116. }
  3117. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3118. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3119. gl.bindTexture(gl.TEXTURE_2D, null);
  3120. };
  3121. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  3122. var _this = this;
  3123. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3124. var texture = this._gl.createTexture();
  3125. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3126. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3127. var isTGA = (extension === ".tga");
  3128. scene._addPendingData(texture);
  3129. texture.url = url;
  3130. texture.noMipmap = noMipmap;
  3131. texture.references = 1;
  3132. this._loadedTexturesCache.push(texture);
  3133. if (isTGA) {
  3134. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3135. var data = new Uint8Array(arrayBuffer);
  3136. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3137. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3138. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3139. }, samplingMode);
  3140. }, null, scene.database, true);
  3141. } else if (isDDS) {
  3142. BABYLON.Tools.LoadFile(url, function (data) {
  3143. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3144. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3145. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3146. console.log("loading " + url);
  3147. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3148. }, samplingMode);
  3149. }, null, scene.database, true);
  3150. } else {
  3151. var onload = function (img) {
  3152. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3153. var isPot = (img.width == potWidth && img.height == potHeight);
  3154. if (!isPot) {
  3155. _this._workingCanvas.width = potWidth;
  3156. _this._workingCanvas.height = potHeight;
  3157. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3158. }
  3159. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3160. }, samplingMode);
  3161. };
  3162. var onerror = function () {
  3163. scene._removePendingData(texture);
  3164. };
  3165. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3166. }
  3167. return texture;
  3168. };
  3169. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3170. var texture = this._gl.createTexture();
  3171. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  3172. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  3173. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3174. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3175. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3176. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3177. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3178. this._activeTexturesCache = [];
  3179. texture._baseWidth = width;
  3180. texture._baseHeight = height;
  3181. texture._width = width;
  3182. texture._height = height;
  3183. texture.isReady = false;
  3184. texture.generateMipMaps = generateMipMaps;
  3185. texture.references = 1;
  3186. this._loadedTexturesCache.push(texture);
  3187. return texture;
  3188. };
  3189. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3190. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3191. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3192. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3193. if (texture.generateMipMaps) {
  3194. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3195. }
  3196. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3197. this._activeTexturesCache = [];
  3198. texture.isReady = true;
  3199. };
  3200. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3201. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3202. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3203. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3204. if (!texture._workingCanvas) {
  3205. texture._workingCanvas = document.createElement("canvas");
  3206. texture._workingContext = texture._workingCanvas.getContext("2d");
  3207. texture._workingCanvas.width = texture._width;
  3208. texture._workingCanvas.height = texture._height;
  3209. }
  3210. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3211. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3212. } else {
  3213. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3214. }
  3215. if (texture.generateMipMaps) {
  3216. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3217. }
  3218. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3219. this._activeTexturesCache = [];
  3220. texture.isReady = true;
  3221. };
  3222. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3223. var generateMipMaps = false;
  3224. var generateDepthBuffer = true;
  3225. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3226. if (options !== undefined) {
  3227. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3228. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3229. if (options.samplingMode !== undefined) {
  3230. samplingMode = options.samplingMode;
  3231. }
  3232. }
  3233. var gl = this._gl;
  3234. var texture = gl.createTexture();
  3235. gl.bindTexture(gl.TEXTURE_2D, texture);
  3236. var width = size.width || size;
  3237. var height = size.height || size;
  3238. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3243. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3244. var depthBuffer;
  3245. if (generateDepthBuffer) {
  3246. depthBuffer = gl.createRenderbuffer();
  3247. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3248. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3249. }
  3250. var framebuffer = gl.createFramebuffer();
  3251. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3252. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3253. if (generateDepthBuffer) {
  3254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3255. }
  3256. gl.bindTexture(gl.TEXTURE_2D, null);
  3257. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3258. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3259. texture._framebuffer = framebuffer;
  3260. if (generateDepthBuffer) {
  3261. texture._depthBuffer = depthBuffer;
  3262. }
  3263. texture._width = width;
  3264. texture._height = height;
  3265. texture.isReady = true;
  3266. texture.generateMipMaps = generateMipMaps;
  3267. texture.references = 1;
  3268. this._activeTexturesCache = [];
  3269. this._loadedTexturesCache.push(texture);
  3270. return texture;
  3271. };
  3272. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3273. var _this = this;
  3274. var gl = this._gl;
  3275. var texture = gl.createTexture();
  3276. texture.isCube = true;
  3277. texture.url = rootUrl;
  3278. texture.references = 1;
  3279. this._loadedTexturesCache.push(texture);
  3280. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3281. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3282. if (isDDS) {
  3283. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3284. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3285. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3286. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3287. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3288. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3289. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3290. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3291. }
  3292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3296. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3297. _this._activeTexturesCache = [];
  3298. texture._width = info.width;
  3299. texture._height = info.height;
  3300. texture.isReady = true;
  3301. });
  3302. } else {
  3303. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3304. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3305. var height = width;
  3306. _this._workingCanvas.width = width;
  3307. _this._workingCanvas.height = height;
  3308. var faces = [
  3309. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3310. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3311. ];
  3312. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3313. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3314. for (var index = 0; index < faces.length; index++) {
  3315. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3316. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3317. }
  3318. if (!noMipmap) {
  3319. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3320. }
  3321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3324. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3325. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3326. _this._activeTexturesCache = [];
  3327. texture._width = width;
  3328. texture._height = height;
  3329. texture.isReady = true;
  3330. }, extensions);
  3331. }
  3332. return texture;
  3333. };
  3334. Engine.prototype._releaseTexture = function (texture) {
  3335. var gl = this._gl;
  3336. if (texture._framebuffer) {
  3337. gl.deleteFramebuffer(texture._framebuffer);
  3338. }
  3339. if (texture._depthBuffer) {
  3340. gl.deleteRenderbuffer(texture._depthBuffer);
  3341. }
  3342. gl.deleteTexture(texture);
  3343. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3344. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3345. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3346. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3347. this._activeTexturesCache[channel] = null;
  3348. }
  3349. var index = this._loadedTexturesCache.indexOf(texture);
  3350. if (index !== -1) {
  3351. this._loadedTexturesCache.splice(index, 1);
  3352. }
  3353. };
  3354. Engine.prototype.bindSamplers = function (effect) {
  3355. this._gl.useProgram(effect.getProgram());
  3356. var samplers = effect.getSamplers();
  3357. for (var index = 0; index < samplers.length; index++) {
  3358. var uniform = effect.getUniform(samplers[index]);
  3359. this._gl.uniform1i(uniform, index);
  3360. }
  3361. this._currentEffect = null;
  3362. };
  3363. Engine.prototype._bindTexture = function (channel, texture) {
  3364. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3365. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3366. this._activeTexturesCache[channel] = null;
  3367. };
  3368. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3369. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3370. };
  3371. Engine.prototype.setTexture = function (channel, texture) {
  3372. if (channel < 0) {
  3373. return;
  3374. }
  3375. if (!texture || !texture.isReady()) {
  3376. if (this._activeTexturesCache[channel] != null) {
  3377. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3378. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3379. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3380. this._activeTexturesCache[channel] = null;
  3381. }
  3382. return;
  3383. }
  3384. if (texture instanceof BABYLON.VideoTexture) {
  3385. if (texture.update()) {
  3386. this._activeTexturesCache[channel] = null;
  3387. }
  3388. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3389. texture.delayLoad();
  3390. return;
  3391. }
  3392. if (this._activeTexturesCache[channel] == texture) {
  3393. return;
  3394. }
  3395. this._activeTexturesCache[channel] = texture;
  3396. var internalTexture = texture.getInternalTexture();
  3397. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3398. if (internalTexture.isCube) {
  3399. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3400. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3401. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3402. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3403. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3404. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3405. }
  3406. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3407. } else {
  3408. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3409. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3410. internalTexture._cachedWrapU = texture.wrapU;
  3411. switch (texture.wrapU) {
  3412. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3413. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3414. break;
  3415. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3416. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3417. break;
  3418. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3419. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3420. break;
  3421. }
  3422. }
  3423. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3424. internalTexture._cachedWrapV = texture.wrapV;
  3425. switch (texture.wrapV) {
  3426. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3427. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3428. break;
  3429. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3430. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3431. break;
  3432. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3433. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3434. break;
  3435. }
  3436. }
  3437. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3438. }
  3439. };
  3440. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3441. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3442. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3443. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3444. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3445. }
  3446. };
  3447. Engine.prototype.readPixels = function (x, y, width, height) {
  3448. var data = new Uint8Array(height * width * 4);
  3449. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3450. return data;
  3451. };
  3452. Engine.prototype.dispose = function () {
  3453. this.hideLoadingUI();
  3454. this.stopRenderLoop();
  3455. while (this.scenes.length) {
  3456. this.scenes[0].dispose();
  3457. }
  3458. for (var name in this._compiledEffects) {
  3459. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3460. }
  3461. for (var i in this._vertexAttribArrays) {
  3462. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3463. continue;
  3464. }
  3465. this._gl.disableVertexAttribArray(i);
  3466. }
  3467. window.removeEventListener("blur", this._onBlur);
  3468. window.removeEventListener("focus", this._onFocus);
  3469. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3470. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3471. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3472. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3473. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3474. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3475. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3476. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3477. };
  3478. Engine.prototype.displayLoadingUI = function () {
  3479. var _this = this;
  3480. this._loadingDiv = document.createElement("div");
  3481. this._loadingDiv.style.opacity = "0";
  3482. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3483. this._loadingTextDiv = document.createElement("div");
  3484. this._loadingTextDiv.style.position = "absolute";
  3485. this._loadingTextDiv.style.left = "0";
  3486. this._loadingTextDiv.style.top = "50%";
  3487. this._loadingTextDiv.style.marginTop = "80px";
  3488. this._loadingTextDiv.style.width = "100%";
  3489. this._loadingTextDiv.style.height = "20px";
  3490. this._loadingTextDiv.style.fontFamily = "Arial";
  3491. this._loadingTextDiv.style.fontSize = "14px";
  3492. this._loadingTextDiv.style.color = "white";
  3493. this._loadingTextDiv.style.textAlign = "center";
  3494. this._loadingTextDiv.innerHTML = "Loading";
  3495. this._loadingDiv.appendChild(this._loadingTextDiv);
  3496. var imgBack = new Image();
  3497. 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==";
  3498. imgBack.style.position = "absolute";
  3499. imgBack.style.left = "50%";
  3500. imgBack.style.top = "50%";
  3501. imgBack.style.marginLeft = "-50px";
  3502. imgBack.style.marginTop = "-50px";
  3503. imgBack.style.transition = "transform 1.0s ease";
  3504. var deg = 360;
  3505. imgBack.addEventListener("transitionend", function () {
  3506. deg += 360;
  3507. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3508. });
  3509. this._loadingDiv.appendChild(imgBack);
  3510. var imgFront = new Image();
  3511. 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=";
  3512. imgFront.style.position = "absolute";
  3513. imgFront.style.left = "50%";
  3514. imgFront.style.top = "50%";
  3515. imgFront.style.marginLeft = "-50px";
  3516. imgFront.style.marginTop = "-50px";
  3517. this._loadingDiv.appendChild(imgFront);
  3518. this._resizeLoadingUI = function () {
  3519. var canvasRect = _this.getRenderingCanvasClientRect();
  3520. _this._loadingDiv.style.position = "absolute";
  3521. _this._loadingDiv.style.left = canvasRect.left + "px";
  3522. _this._loadingDiv.style.top = canvasRect.top + "px";
  3523. _this._loadingDiv.style.width = canvasRect.width + "px";
  3524. _this._loadingDiv.style.height = canvasRect.height + "px";
  3525. };
  3526. this._resizeLoadingUI();
  3527. window.addEventListener("resize", this._resizeLoadingUI);
  3528. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3529. document.body.appendChild(this._loadingDiv);
  3530. setTimeout(function () {
  3531. _this._loadingDiv.style.opacity = "1";
  3532. imgBack.style.transform = "rotateZ(360deg)";
  3533. }, 0);
  3534. };
  3535. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3536. set: function (text) {
  3537. if (!this._loadingDiv) {
  3538. return;
  3539. }
  3540. this._loadingTextDiv.innerHTML = text;
  3541. },
  3542. enumerable: true,
  3543. configurable: true
  3544. });
  3545. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3546. get: function () {
  3547. return this._loadingDivBackgroundColor;
  3548. },
  3549. set: function (color) {
  3550. this._loadingDivBackgroundColor = color;
  3551. if (!this._loadingDiv) {
  3552. return;
  3553. }
  3554. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3555. },
  3556. enumerable: true,
  3557. configurable: true
  3558. });
  3559. Engine.prototype.hideLoadingUI = function () {
  3560. var _this = this;
  3561. if (!this._loadingDiv) {
  3562. return;
  3563. }
  3564. var onTransitionEnd = function () {
  3565. if (!_this._loadingDiv) {
  3566. return;
  3567. }
  3568. document.body.removeChild(_this._loadingDiv);
  3569. window.removeEventListener("resize", _this._resizeLoadingUI);
  3570. _this._loadingDiv = null;
  3571. };
  3572. this._loadingDiv.style.opacity = "0";
  3573. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3574. };
  3575. Engine.isSupported = function () {
  3576. try {
  3577. var tempcanvas = document.createElement("canvas");
  3578. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3579. return gl != null && !!window.WebGLRenderingContext;
  3580. } catch (e) {
  3581. return false;
  3582. }
  3583. };
  3584. Engine._ALPHA_DISABLE = 0;
  3585. Engine._ALPHA_ADD = 1;
  3586. Engine._ALPHA_COMBINE = 2;
  3587. Engine._DELAYLOADSTATE_NONE = 0;
  3588. Engine._DELAYLOADSTATE_LOADED = 1;
  3589. Engine._DELAYLOADSTATE_LOADING = 2;
  3590. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3591. Engine.Epsilon = 0.001;
  3592. Engine.CollisionsEpsilon = 0.001;
  3593. Engine.ShadersRepository = "Babylon/Shaders/";
  3594. return Engine;
  3595. })();
  3596. BABYLON.Engine = Engine;
  3597. })(BABYLON || (BABYLON = {}));
  3598. var BABYLON;
  3599. (function (BABYLON) {
  3600. var Node = (function () {
  3601. function Node(name, scene) {
  3602. this.state = "";
  3603. this.animations = new Array();
  3604. this._childrenFlag = -1;
  3605. this._isEnabled = true;
  3606. this._isReady = true;
  3607. this._currentRenderId = -1;
  3608. this.name = name;
  3609. this.id = name;
  3610. this._scene = scene;
  3611. this._initCache();
  3612. }
  3613. Node.prototype.getScene = function () {
  3614. return this._scene;
  3615. };
  3616. Node.prototype.getEngine = function () {
  3617. return this._scene.getEngine();
  3618. };
  3619. Node.prototype.getWorldMatrix = function () {
  3620. return BABYLON.Matrix.Identity();
  3621. };
  3622. Node.prototype._initCache = function () {
  3623. this._cache = {};
  3624. this._cache.parent = undefined;
  3625. };
  3626. Node.prototype.updateCache = function (force) {
  3627. if (!force && this.isSynchronized())
  3628. return;
  3629. this._cache.parent = this.parent;
  3630. this._updateCache();
  3631. };
  3632. Node.prototype._updateCache = function (ignoreParentClass) {
  3633. };
  3634. Node.prototype._isSynchronized = function () {
  3635. return true;
  3636. };
  3637. Node.prototype.isSynchronizedWithParent = function () {
  3638. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3639. };
  3640. Node.prototype.isSynchronized = function (updateCache) {
  3641. var check = this.hasNewParent();
  3642. check = check || !this.isSynchronizedWithParent();
  3643. check = check || !this._isSynchronized();
  3644. if (updateCache)
  3645. this.updateCache(true);
  3646. return !check;
  3647. };
  3648. Node.prototype.hasNewParent = function (update) {
  3649. if (this._cache.parent === this.parent)
  3650. return false;
  3651. if (update)
  3652. this._cache.parent = this.parent;
  3653. return true;
  3654. };
  3655. Node.prototype.isReady = function () {
  3656. return this._isReady;
  3657. };
  3658. Node.prototype.isEnabled = function () {
  3659. if (!this._isEnabled) {
  3660. return false;
  3661. }
  3662. if (this.parent) {
  3663. return this.parent.isEnabled();
  3664. }
  3665. return true;
  3666. };
  3667. Node.prototype.setEnabled = function (value) {
  3668. this._isEnabled = value;
  3669. };
  3670. Node.prototype.isDescendantOf = function (ancestor) {
  3671. if (this.parent) {
  3672. if (this.parent === ancestor) {
  3673. return true;
  3674. }
  3675. return this.parent.isDescendantOf(ancestor);
  3676. }
  3677. return false;
  3678. };
  3679. Node.prototype._getDescendants = function (list, results) {
  3680. for (var index = 0; index < list.length; index++) {
  3681. var item = list[index];
  3682. if (item.isDescendantOf(this)) {
  3683. results.push(item);
  3684. }
  3685. }
  3686. };
  3687. Node.prototype.getDescendants = function () {
  3688. var results = [];
  3689. this._getDescendants(this._scene.meshes, results);
  3690. this._getDescendants(this._scene.lights, results);
  3691. this._getDescendants(this._scene.cameras, results);
  3692. return results;
  3693. };
  3694. Node.prototype._setReady = function (state) {
  3695. if (state == this._isReady) {
  3696. return;
  3697. }
  3698. if (!state) {
  3699. this._isReady = false;
  3700. return;
  3701. }
  3702. this._isReady = true;
  3703. if (this.onReady) {
  3704. this.onReady(this);
  3705. }
  3706. };
  3707. return Node;
  3708. })();
  3709. BABYLON.Node = Node;
  3710. })(BABYLON || (BABYLON = {}));
  3711. var BABYLON;
  3712. (function (BABYLON) {
  3713. var BoundingSphere = (function () {
  3714. function BoundingSphere(minimum, maximum) {
  3715. this.minimum = minimum;
  3716. this.maximum = maximum;
  3717. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3718. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3719. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3720. this.radius = distance * 0.5;
  3721. this.centerWorld = BABYLON.Vector3.Zero();
  3722. this._update(BABYLON.Matrix.Identity());
  3723. }
  3724. BoundingSphere.prototype._update = function (world) {
  3725. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3726. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3727. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3728. };
  3729. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3730. for (var i = 0; i < 6; i++) {
  3731. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3732. return false;
  3733. }
  3734. return true;
  3735. };
  3736. BoundingSphere.prototype.intersectsPoint = function (point) {
  3737. var x = this.centerWorld.x - point.x;
  3738. var y = this.centerWorld.y - point.y;
  3739. var z = this.centerWorld.z - point.z;
  3740. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3741. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3742. return false;
  3743. return true;
  3744. };
  3745. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3746. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3747. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3748. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3749. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3750. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3751. return false;
  3752. return true;
  3753. };
  3754. return BoundingSphere;
  3755. })();
  3756. BABYLON.BoundingSphere = BoundingSphere;
  3757. })(BABYLON || (BABYLON = {}));
  3758. var BABYLON;
  3759. (function (BABYLON) {
  3760. var BoundingBox = (function () {
  3761. function BoundingBox(minimum, maximum) {
  3762. this.minimum = minimum;
  3763. this.maximum = maximum;
  3764. this.vectors = new Array();
  3765. this.vectorsWorld = new Array();
  3766. this.vectors.push(this.minimum.clone());
  3767. this.vectors.push(this.maximum.clone());
  3768. this.vectors.push(this.minimum.clone());
  3769. this.vectors[2].x = this.maximum.x;
  3770. this.vectors.push(this.minimum.clone());
  3771. this.vectors[3].y = this.maximum.y;
  3772. this.vectors.push(this.minimum.clone());
  3773. this.vectors[4].z = this.maximum.z;
  3774. this.vectors.push(this.maximum.clone());
  3775. this.vectors[5].z = this.minimum.z;
  3776. this.vectors.push(this.maximum.clone());
  3777. this.vectors[6].x = this.minimum.x;
  3778. this.vectors.push(this.maximum.clone());
  3779. this.vectors[7].y = this.minimum.y;
  3780. this.center = this.maximum.add(this.minimum).scale(0.5);
  3781. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3782. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3783. for (var index = 0; index < this.vectors.length; index++) {
  3784. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3785. }
  3786. this.minimumWorld = BABYLON.Vector3.Zero();
  3787. this.maximumWorld = BABYLON.Vector3.Zero();
  3788. this._update(BABYLON.Matrix.Identity());
  3789. }
  3790. BoundingBox.prototype.getWorldMatrix = function () {
  3791. return this._worldMatrix;
  3792. };
  3793. BoundingBox.prototype._update = function (world) {
  3794. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3795. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3796. for (var index = 0; index < this.vectors.length; index++) {
  3797. var v = this.vectorsWorld[index];
  3798. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3799. if (v.x < this.minimumWorld.x)
  3800. this.minimumWorld.x = v.x;
  3801. if (v.y < this.minimumWorld.y)
  3802. this.minimumWorld.y = v.y;
  3803. if (v.z < this.minimumWorld.z)
  3804. this.minimumWorld.z = v.z;
  3805. if (v.x > this.maximumWorld.x)
  3806. this.maximumWorld.x = v.x;
  3807. if (v.y > this.maximumWorld.y)
  3808. this.maximumWorld.y = v.y;
  3809. if (v.z > this.maximumWorld.z)
  3810. this.maximumWorld.z = v.z;
  3811. }
  3812. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3813. this.center.scaleInPlace(0.5);
  3814. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3815. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3816. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3817. this._worldMatrix = world;
  3818. };
  3819. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3820. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3821. };
  3822. BoundingBox.prototype.intersectsPoint = function (point) {
  3823. var delta = BABYLON.Engine.Epsilon;
  3824. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3825. return false;
  3826. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3827. return false;
  3828. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3829. return false;
  3830. return true;
  3831. };
  3832. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3833. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3834. };
  3835. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3836. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3837. return false;
  3838. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3839. return false;
  3840. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3841. return false;
  3842. return true;
  3843. };
  3844. BoundingBox.Intersects = function (box0, box1) {
  3845. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3846. return false;
  3847. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3848. return false;
  3849. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3850. return false;
  3851. return true;
  3852. };
  3853. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3854. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3855. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3856. return (num <= (sphereRadius * sphereRadius));
  3857. };
  3858. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3859. for (var p = 0; p < 6; p++) {
  3860. var inCount = 8;
  3861. for (var i = 0; i < 8; i++) {
  3862. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3863. --inCount;
  3864. } else {
  3865. break;
  3866. }
  3867. }
  3868. if (inCount == 0)
  3869. return false;
  3870. }
  3871. return true;
  3872. };
  3873. return BoundingBox;
  3874. })();
  3875. BABYLON.BoundingBox = BoundingBox;
  3876. })(BABYLON || (BABYLON = {}));
  3877. var BABYLON;
  3878. (function (BABYLON) {
  3879. var computeBoxExtents = function (axis, box) {
  3880. var p = BABYLON.Vector3.Dot(box.center, axis);
  3881. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3882. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3883. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3884. var r = r0 + r1 + r2;
  3885. return {
  3886. min: p - r,
  3887. max: p + r
  3888. };
  3889. };
  3890. var extentsOverlap = function (min0, max0, min1, max1) {
  3891. return !(min0 > max1 || min1 > max0);
  3892. };
  3893. var axisOverlap = function (axis, box0, box1) {
  3894. var result0 = computeBoxExtents(axis, box0);
  3895. var result1 = computeBoxExtents(axis, box1);
  3896. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3897. };
  3898. var BoundingInfo = (function () {
  3899. function BoundingInfo(minimum, maximum) {
  3900. this.minimum = minimum;
  3901. this.maximum = maximum;
  3902. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3903. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3904. }
  3905. BoundingInfo.prototype._update = function (world) {
  3906. this.boundingBox._update(world);
  3907. this.boundingSphere._update(world);
  3908. };
  3909. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3910. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3911. return false;
  3912. return this.boundingBox.isInFrustum(frustumPlanes);
  3913. };
  3914. BoundingInfo.prototype._checkCollision = function (collider) {
  3915. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3916. };
  3917. BoundingInfo.prototype.intersectsPoint = function (point) {
  3918. if (!this.boundingSphere.centerWorld) {
  3919. return false;
  3920. }
  3921. if (!this.boundingSphere.intersectsPoint(point)) {
  3922. return false;
  3923. }
  3924. if (!this.boundingBox.intersectsPoint(point)) {
  3925. return false;
  3926. }
  3927. return true;
  3928. };
  3929. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3930. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3931. return false;
  3932. }
  3933. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3934. return false;
  3935. }
  3936. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3937. return false;
  3938. }
  3939. if (!precise) {
  3940. return true;
  3941. }
  3942. var box0 = this.boundingBox;
  3943. var box1 = boundingInfo.boundingBox;
  3944. if (!axisOverlap(box0.directions[0], box0, box1))
  3945. return false;
  3946. if (!axisOverlap(box0.directions[1], box0, box1))
  3947. return false;
  3948. if (!axisOverlap(box0.directions[2], box0, box1))
  3949. return false;
  3950. if (!axisOverlap(box1.directions[0], box0, box1))
  3951. return false;
  3952. if (!axisOverlap(box1.directions[1], box0, box1))
  3953. return false;
  3954. if (!axisOverlap(box1.directions[2], box0, box1))
  3955. return false;
  3956. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3957. return false;
  3958. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3959. return false;
  3960. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3961. return false;
  3962. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3963. return false;
  3964. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3965. return false;
  3966. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3967. return false;
  3968. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3969. return false;
  3970. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  3971. return false;
  3972. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  3973. return false;
  3974. return true;
  3975. };
  3976. return BoundingInfo;
  3977. })();
  3978. BABYLON.BoundingInfo = BoundingInfo;
  3979. })(BABYLON || (BABYLON = {}));
  3980. var __extends = this.__extends || function (d, b) {
  3981. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3982. function __() { this.constructor = d; }
  3983. __.prototype = b.prototype;
  3984. d.prototype = new __();
  3985. };
  3986. var BABYLON;
  3987. (function (BABYLON) {
  3988. var Light = (function (_super) {
  3989. __extends(Light, _super);
  3990. function Light(name, scene) {
  3991. _super.call(this, name, scene);
  3992. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  3993. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  3994. this.intensity = 1.0;
  3995. this.range = Number.MAX_VALUE;
  3996. this.includedOnlyMeshes = new Array();
  3997. this.excludedMeshes = new Array();
  3998. this._excludedMeshesIds = new Array();
  3999. this._includedOnlyMeshesIds = new Array();
  4000. scene.lights.push(this);
  4001. }
  4002. Light.prototype.getShadowGenerator = function () {
  4003. return this._shadowGenerator;
  4004. };
  4005. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4006. };
  4007. Light.prototype._getWorldMatrix = function () {
  4008. return BABYLON.Matrix.Identity();
  4009. };
  4010. Light.prototype.canAffectMesh = function (mesh) {
  4011. if (!mesh) {
  4012. return true;
  4013. }
  4014. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4015. return false;
  4016. }
  4017. if (this.includedOnlyMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4018. return false;
  4019. }
  4020. return true;
  4021. };
  4022. Light.prototype.getWorldMatrix = function () {
  4023. this._currentRenderId = this.getScene().getRenderId();
  4024. var worldMatrix = this._getWorldMatrix();
  4025. if (this.parent && this.parent.getWorldMatrix) {
  4026. if (!this._parentedWorldMatrix) {
  4027. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4028. }
  4029. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4030. return this._parentedWorldMatrix;
  4031. }
  4032. return worldMatrix;
  4033. };
  4034. Light.prototype.dispose = function () {
  4035. if (this._shadowGenerator) {
  4036. this._shadowGenerator.dispose();
  4037. this._shadowGenerator = null;
  4038. }
  4039. var index = this.getScene().lights.indexOf(this);
  4040. this.getScene().lights.splice(index, 1);
  4041. };
  4042. return Light;
  4043. })(BABYLON.Node);
  4044. BABYLON.Light = Light;
  4045. })(BABYLON || (BABYLON = {}));
  4046. var __extends = this.__extends || function (d, b) {
  4047. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4048. function __() { this.constructor = d; }
  4049. __.prototype = b.prototype;
  4050. d.prototype = new __();
  4051. };
  4052. var BABYLON;
  4053. (function (BABYLON) {
  4054. var PointLight = (function (_super) {
  4055. __extends(PointLight, _super);
  4056. function PointLight(name, position, scene) {
  4057. _super.call(this, name, scene);
  4058. this.position = position;
  4059. }
  4060. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4061. if (this.parent && this.parent.getWorldMatrix) {
  4062. if (!this._transformedPosition) {
  4063. this._transformedPosition = BABYLON.Vector3.Zero();
  4064. }
  4065. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4066. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4067. return;
  4068. }
  4069. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4070. };
  4071. PointLight.prototype.getShadowGenerator = function () {
  4072. return null;
  4073. };
  4074. PointLight.prototype._getWorldMatrix = function () {
  4075. if (!this._worldMatrix) {
  4076. this._worldMatrix = BABYLON.Matrix.Identity();
  4077. }
  4078. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4079. return this._worldMatrix;
  4080. };
  4081. return PointLight;
  4082. })(BABYLON.Light);
  4083. BABYLON.PointLight = PointLight;
  4084. })(BABYLON || (BABYLON = {}));
  4085. var __extends = this.__extends || function (d, b) {
  4086. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4087. function __() { this.constructor = d; }
  4088. __.prototype = b.prototype;
  4089. d.prototype = new __();
  4090. };
  4091. var BABYLON;
  4092. (function (BABYLON) {
  4093. var SpotLight = (function (_super) {
  4094. __extends(SpotLight, _super);
  4095. function SpotLight(name, position, direction, angle, exponent, scene) {
  4096. _super.call(this, name, scene);
  4097. this.position = position;
  4098. this.direction = direction;
  4099. this.angle = angle;
  4100. this.exponent = exponent;
  4101. }
  4102. SpotLight.prototype.setDirectionToTarget = function (target) {
  4103. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4104. return this.direction;
  4105. };
  4106. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4107. var normalizeDirection;
  4108. if (this.parent && this.parent.getWorldMatrix) {
  4109. if (!this._transformedDirection) {
  4110. this._transformedDirection = BABYLON.Vector3.Zero();
  4111. }
  4112. if (!this._transformedPosition) {
  4113. this._transformedPosition = BABYLON.Vector3.Zero();
  4114. }
  4115. var parentWorldMatrix = this.parent.getWorldMatrix();
  4116. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4117. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4118. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4119. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4120. } else {
  4121. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4122. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4123. }
  4124. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4125. };
  4126. SpotLight.prototype._getWorldMatrix = function () {
  4127. if (!this._worldMatrix) {
  4128. this._worldMatrix = BABYLON.Matrix.Identity();
  4129. }
  4130. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4131. return this._worldMatrix;
  4132. };
  4133. return SpotLight;
  4134. })(BABYLON.Light);
  4135. BABYLON.SpotLight = SpotLight;
  4136. })(BABYLON || (BABYLON = {}));
  4137. var __extends = this.__extends || function (d, b) {
  4138. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4139. function __() { this.constructor = d; }
  4140. __.prototype = b.prototype;
  4141. d.prototype = new __();
  4142. };
  4143. var BABYLON;
  4144. (function (BABYLON) {
  4145. var DirectionalLight = (function (_super) {
  4146. __extends(DirectionalLight, _super);
  4147. function DirectionalLight(name, direction, scene) {
  4148. _super.call(this, name, scene);
  4149. this.direction = direction;
  4150. this.position = direction.scale(-1);
  4151. }
  4152. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4153. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4154. return this.direction;
  4155. };
  4156. DirectionalLight.prototype._computeTransformedPosition = function () {
  4157. if (this.parent && this.parent.getWorldMatrix) {
  4158. if (!this._transformedPosition) {
  4159. this._transformedPosition = BABYLON.Vector3.Zero();
  4160. }
  4161. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4162. return true;
  4163. }
  4164. return false;
  4165. };
  4166. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4167. if (this.parent && this.parent.getWorldMatrix) {
  4168. if (!this._transformedDirection) {
  4169. this._transformedDirection = BABYLON.Vector3.Zero();
  4170. }
  4171. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4172. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4173. return;
  4174. }
  4175. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4176. };
  4177. DirectionalLight.prototype._getWorldMatrix = function () {
  4178. if (!this._worldMatrix) {
  4179. this._worldMatrix = BABYLON.Matrix.Identity();
  4180. }
  4181. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4182. return this._worldMatrix;
  4183. };
  4184. return DirectionalLight;
  4185. })(BABYLON.Light);
  4186. BABYLON.DirectionalLight = DirectionalLight;
  4187. })(BABYLON || (BABYLON = {}));
  4188. var BABYLON;
  4189. (function (BABYLON) {
  4190. var ShadowGenerator = (function () {
  4191. function ShadowGenerator(mapSize, light) {
  4192. var _this = this;
  4193. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4194. this._darkness = 0;
  4195. this._transparencyShadow = false;
  4196. this._viewMatrix = BABYLON.Matrix.Zero();
  4197. this._projectionMatrix = BABYLON.Matrix.Zero();
  4198. this._transformMatrix = BABYLON.Matrix.Zero();
  4199. this._worldViewProjection = BABYLON.Matrix.Zero();
  4200. this._light = light;
  4201. this._scene = light.getScene();
  4202. light._shadowGenerator = this;
  4203. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4204. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4205. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4206. this._shadowMap.renderParticles = false;
  4207. var renderSubMesh = function (subMesh) {
  4208. var mesh = subMesh.getRenderingMesh();
  4209. var scene = _this._scene;
  4210. var engine = scene.getEngine();
  4211. engine.setState(subMesh.getMaterial().backFaceCulling);
  4212. var batch = mesh._getInstancesRenderList(subMesh._id);
  4213. if (batch.mustReturn) {
  4214. return;
  4215. }
  4216. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  4217. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4218. engine.enableEffect(_this._effect);
  4219. mesh._bind(subMesh, _this._effect, false);
  4220. var material = subMesh.getMaterial();
  4221. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4222. if (material && material.needAlphaTesting()) {
  4223. var alphaTexture = material.getAlphaTestTexture();
  4224. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4225. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4226. }
  4227. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4228. if (useBones) {
  4229. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4230. }
  4231. if (hardwareInstancedRendering) {
  4232. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4233. } else {
  4234. if (batch.renderSelf[subMesh._id]) {
  4235. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4236. mesh._draw(subMesh, true);
  4237. }
  4238. if (batch.visibleInstances[subMesh._id]) {
  4239. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4240. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4241. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4242. mesh._draw(subMesh, true);
  4243. }
  4244. }
  4245. }
  4246. } else {
  4247. _this._shadowMap.resetRefreshCounter();
  4248. }
  4249. };
  4250. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4251. var index;
  4252. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4253. renderSubMesh(opaqueSubMeshes.data[index]);
  4254. }
  4255. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4256. renderSubMesh(alphaTestSubMeshes.data[index]);
  4257. }
  4258. if (_this._transparencyShadow) {
  4259. for (index = 0; index < transparentSubMeshes.length; index++) {
  4260. renderSubMesh(transparentSubMeshes.data[index]);
  4261. }
  4262. }
  4263. };
  4264. }
  4265. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4266. get: function () {
  4267. return ShadowGenerator._FILTER_NONE;
  4268. },
  4269. enumerable: true,
  4270. configurable: true
  4271. });
  4272. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4273. get: function () {
  4274. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4275. },
  4276. enumerable: true,
  4277. configurable: true
  4278. });
  4279. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4280. get: function () {
  4281. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4282. },
  4283. enumerable: true,
  4284. configurable: true
  4285. });
  4286. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4287. get: function () {
  4288. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4289. },
  4290. set: function (value) {
  4291. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4292. },
  4293. enumerable: true,
  4294. configurable: true
  4295. });
  4296. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4297. get: function () {
  4298. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4299. },
  4300. set: function (value) {
  4301. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4302. },
  4303. enumerable: true,
  4304. configurable: true
  4305. });
  4306. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4307. var defines = [];
  4308. if (this.useVarianceShadowMap) {
  4309. defines.push("#define VSM");
  4310. }
  4311. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4312. var mesh = subMesh.getMesh();
  4313. var material = subMesh.getMaterial();
  4314. if (material && material.needAlphaTesting()) {
  4315. defines.push("#define ALPHATEST");
  4316. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4317. attribs.push(BABYLON.VertexBuffer.UVKind);
  4318. defines.push("#define UV1");
  4319. }
  4320. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4321. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4322. defines.push("#define UV2");
  4323. }
  4324. }
  4325. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4326. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4327. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4328. defines.push("#define BONES");
  4329. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4330. }
  4331. if (useInstances) {
  4332. defines.push("#define INSTANCES");
  4333. attribs.push("world0");
  4334. attribs.push("world1");
  4335. attribs.push("world2");
  4336. attribs.push("world3");
  4337. }
  4338. var join = defines.join("\n");
  4339. if (this._cachedDefines != join) {
  4340. this._cachedDefines = join;
  4341. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4342. }
  4343. return this._effect.isReady();
  4344. };
  4345. ShadowGenerator.prototype.getShadowMap = function () {
  4346. return this._shadowMap;
  4347. };
  4348. ShadowGenerator.prototype.getLight = function () {
  4349. return this._light;
  4350. };
  4351. ShadowGenerator.prototype.getTransformMatrix = function () {
  4352. var lightPosition = this._light.position;
  4353. var lightDirection = this._light.direction;
  4354. if (this._light._computeTransformedPosition()) {
  4355. lightPosition = this._light._transformedPosition;
  4356. }
  4357. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4358. this._cachedPosition = lightPosition.clone();
  4359. this._cachedDirection = lightDirection.clone();
  4360. var activeCamera = this._scene.activeCamera;
  4361. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4362. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4363. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4364. }
  4365. return this._transformMatrix;
  4366. };
  4367. ShadowGenerator.prototype.getDarkness = function () {
  4368. return this._darkness;
  4369. };
  4370. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4371. if (darkness >= 1.0)
  4372. this._darkness = 1.0;
  4373. else if (darkness <= 0.0)
  4374. this._darkness = 0.0;
  4375. else
  4376. this._darkness = darkness;
  4377. };
  4378. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4379. this._transparencyShadow = hasShadow;
  4380. };
  4381. ShadowGenerator.prototype.dispose = function () {
  4382. this._shadowMap.dispose();
  4383. };
  4384. ShadowGenerator._FILTER_NONE = 0;
  4385. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4386. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4387. return ShadowGenerator;
  4388. })();
  4389. BABYLON.ShadowGenerator = ShadowGenerator;
  4390. })(BABYLON || (BABYLON = {}));
  4391. var __extends = this.__extends || function (d, b) {
  4392. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4393. function __() { this.constructor = d; }
  4394. __.prototype = b.prototype;
  4395. d.prototype = new __();
  4396. };
  4397. var BABYLON;
  4398. (function (BABYLON) {
  4399. var HemisphericLight = (function (_super) {
  4400. __extends(HemisphericLight, _super);
  4401. function HemisphericLight(name, direction, scene) {
  4402. _super.call(this, name, scene);
  4403. this.direction = direction;
  4404. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4405. }
  4406. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4407. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4408. return this.direction;
  4409. };
  4410. HemisphericLight.prototype.getShadowGenerator = function () {
  4411. return null;
  4412. };
  4413. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4414. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4415. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4416. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4417. };
  4418. HemisphericLight.prototype._getWorldMatrix = function () {
  4419. if (!this._worldMatrix) {
  4420. this._worldMatrix = BABYLON.Matrix.Identity();
  4421. }
  4422. return this._worldMatrix;
  4423. };
  4424. return HemisphericLight;
  4425. })(BABYLON.Light);
  4426. BABYLON.HemisphericLight = HemisphericLight;
  4427. })(BABYLON || (BABYLON = {}));
  4428. var BABYLON;
  4429. (function (BABYLON) {
  4430. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4431. if (boxMin.x > sphereCenter.x + sphereRadius)
  4432. return false;
  4433. if (sphereCenter.x - sphereRadius > boxMax.x)
  4434. return false;
  4435. if (boxMin.y > sphereCenter.y + sphereRadius)
  4436. return false;
  4437. if (sphereCenter.y - sphereRadius > boxMax.y)
  4438. return false;
  4439. if (boxMin.z > sphereCenter.z + sphereRadius)
  4440. return false;
  4441. if (sphereCenter.z - sphereRadius > boxMax.z)
  4442. return false;
  4443. return true;
  4444. };
  4445. var getLowestRoot = function (a, b, c, maxR) {
  4446. var determinant = b * b - 4.0 * a * c;
  4447. var result = { root: 0, found: false };
  4448. if (determinant < 0)
  4449. return result;
  4450. var sqrtD = Math.sqrt(determinant);
  4451. var r1 = (-b - sqrtD) / (2.0 * a);
  4452. var r2 = (-b + sqrtD) / (2.0 * a);
  4453. if (r1 > r2) {
  4454. var temp = r2;
  4455. r2 = r1;
  4456. r1 = temp;
  4457. }
  4458. if (r1 > 0 && r1 < maxR) {
  4459. result.root = r1;
  4460. result.found = true;
  4461. return result;
  4462. }
  4463. if (r2 > 0 && r2 < maxR) {
  4464. result.root = r2;
  4465. result.found = true;
  4466. return result;
  4467. }
  4468. return result;
  4469. };
  4470. var Collider = (function () {
  4471. function Collider() {
  4472. this.radius = new BABYLON.Vector3(1, 1, 1);
  4473. this.retry = 0;
  4474. this.basePointWorld = BABYLON.Vector3.Zero();
  4475. this.velocityWorld = BABYLON.Vector3.Zero();
  4476. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4477. this._collisionPoint = BABYLON.Vector3.Zero();
  4478. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4479. this._tempVector = BABYLON.Vector3.Zero();
  4480. this._tempVector2 = BABYLON.Vector3.Zero();
  4481. this._tempVector3 = BABYLON.Vector3.Zero();
  4482. this._tempVector4 = BABYLON.Vector3.Zero();
  4483. this._edge = BABYLON.Vector3.Zero();
  4484. this._baseToVertex = BABYLON.Vector3.Zero();
  4485. this._destinationPoint = BABYLON.Vector3.Zero();
  4486. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4487. this._displacementVector = BABYLON.Vector3.Zero();
  4488. }
  4489. Collider.prototype._initialize = function (source, dir, e) {
  4490. this.velocity = dir;
  4491. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4492. this.basePoint = source;
  4493. source.multiplyToRef(this.radius, this.basePointWorld);
  4494. dir.multiplyToRef(this.radius, this.velocityWorld);
  4495. this.velocityWorldLength = this.velocityWorld.length();
  4496. this.epsilon = e;
  4497. this.collisionFound = false;
  4498. };
  4499. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4500. pa.subtractToRef(point, this._tempVector);
  4501. pb.subtractToRef(point, this._tempVector2);
  4502. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4503. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4504. if (d < 0)
  4505. return false;
  4506. pc.subtractToRef(point, this._tempVector3);
  4507. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4508. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4509. if (d < 0)
  4510. return false;
  4511. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4512. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4513. return d >= 0;
  4514. };
  4515. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4516. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4517. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4518. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4519. return false;
  4520. }
  4521. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4522. return false;
  4523. return true;
  4524. };
  4525. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4526. var t0;
  4527. var embeddedInPlane = false;
  4528. if (!subMesh._trianglePlanes) {
  4529. subMesh._trianglePlanes = [];
  4530. }
  4531. if (!subMesh._trianglePlanes[faceIndex]) {
  4532. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4533. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4534. }
  4535. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4536. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4537. return;
  4538. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4539. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4540. if (normalDotVelocity == 0) {
  4541. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4542. return;
  4543. embeddedInPlane = true;
  4544. t0 = 0;
  4545. } else {
  4546. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4547. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4548. if (t0 > t1) {
  4549. var temp = t1;
  4550. t1 = t0;
  4551. t0 = temp;
  4552. }
  4553. if (t0 > 1.0 || t1 < 0.0)
  4554. return;
  4555. if (t0 < 0)
  4556. t0 = 0;
  4557. if (t0 > 1.0)
  4558. t0 = 1.0;
  4559. }
  4560. this._collisionPoint.copyFromFloats(0, 0, 0);
  4561. var found = false;
  4562. var t = 1.0;
  4563. if (!embeddedInPlane) {
  4564. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4565. this.velocity.scaleToRef(t0, this._tempVector);
  4566. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4567. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4568. found = true;
  4569. t = t0;
  4570. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4571. }
  4572. }
  4573. if (!found) {
  4574. var velocitySquaredLength = this.velocity.lengthSquared();
  4575. var a = velocitySquaredLength;
  4576. this.basePoint.subtractToRef(p1, this._tempVector);
  4577. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4578. var c = this._tempVector.lengthSquared() - 1.0;
  4579. var lowestRoot = getLowestRoot(a, b, c, t);
  4580. if (lowestRoot.found) {
  4581. t = lowestRoot.root;
  4582. found = true;
  4583. this._collisionPoint.copyFrom(p1);
  4584. }
  4585. this.basePoint.subtractToRef(p2, this._tempVector);
  4586. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4587. c = this._tempVector.lengthSquared() - 1.0;
  4588. lowestRoot = getLowestRoot(a, b, c, t);
  4589. if (lowestRoot.found) {
  4590. t = lowestRoot.root;
  4591. found = true;
  4592. this._collisionPoint.copyFrom(p2);
  4593. }
  4594. this.basePoint.subtractToRef(p3, this._tempVector);
  4595. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4596. c = this._tempVector.lengthSquared() - 1.0;
  4597. lowestRoot = getLowestRoot(a, b, c, t);
  4598. if (lowestRoot.found) {
  4599. t = lowestRoot.root;
  4600. found = true;
  4601. this._collisionPoint.copyFrom(p3);
  4602. }
  4603. p2.subtractToRef(p1, this._edge);
  4604. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4605. var edgeSquaredLength = this._edge.lengthSquared();
  4606. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4607. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4608. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4609. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4610. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4611. lowestRoot = getLowestRoot(a, b, c, t);
  4612. if (lowestRoot.found) {
  4613. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4614. if (f >= 0.0 && f <= 1.0) {
  4615. t = lowestRoot.root;
  4616. found = true;
  4617. this._edge.scaleInPlace(f);
  4618. p1.addToRef(this._edge, this._collisionPoint);
  4619. }
  4620. }
  4621. p3.subtractToRef(p2, this._edge);
  4622. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4623. edgeSquaredLength = this._edge.lengthSquared();
  4624. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4625. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4626. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4627. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4628. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4629. lowestRoot = getLowestRoot(a, b, c, t);
  4630. if (lowestRoot.found) {
  4631. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4632. if (f >= 0.0 && f <= 1.0) {
  4633. t = lowestRoot.root;
  4634. found = true;
  4635. this._edge.scaleInPlace(f);
  4636. p2.addToRef(this._edge, this._collisionPoint);
  4637. }
  4638. }
  4639. p1.subtractToRef(p3, this._edge);
  4640. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4641. edgeSquaredLength = this._edge.lengthSquared();
  4642. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4643. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4644. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4645. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4646. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4647. lowestRoot = getLowestRoot(a, b, c, t);
  4648. if (lowestRoot.found) {
  4649. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4650. if (f >= 0.0 && f <= 1.0) {
  4651. t = lowestRoot.root;
  4652. found = true;
  4653. this._edge.scaleInPlace(f);
  4654. p3.addToRef(this._edge, this._collisionPoint);
  4655. }
  4656. }
  4657. }
  4658. if (found) {
  4659. var distToCollision = t * this.velocity.length();
  4660. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4661. if (!this.intersectionPoint) {
  4662. this.intersectionPoint = this._collisionPoint.clone();
  4663. } else {
  4664. this.intersectionPoint.copyFrom(this._collisionPoint);
  4665. }
  4666. this.nearestDistance = distToCollision;
  4667. this.collisionFound = true;
  4668. this.collidedMesh = subMesh.getMesh();
  4669. }
  4670. }
  4671. };
  4672. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4673. for (var i = indexStart; i < indexEnd; i += 3) {
  4674. var p1 = pts[indices[i] - decal];
  4675. var p2 = pts[indices[i + 1] - decal];
  4676. var p3 = pts[indices[i + 2] - decal];
  4677. this._testTriangle(i, subMesh, p3, p2, p1);
  4678. }
  4679. };
  4680. Collider.prototype._getResponse = function (pos, vel) {
  4681. pos.addToRef(vel, this._destinationPoint);
  4682. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4683. this.basePoint.addToRef(vel, pos);
  4684. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4685. this._slidePlaneNormal.normalize();
  4686. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4687. pos.addInPlace(this._displacementVector);
  4688. this.intersectionPoint.addInPlace(this._displacementVector);
  4689. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4690. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4691. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4692. };
  4693. return Collider;
  4694. })();
  4695. BABYLON.Collider = Collider;
  4696. })(BABYLON || (BABYLON = {}));
  4697. var __extends = this.__extends || function (d, b) {
  4698. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4699. function __() { this.constructor = d; }
  4700. __.prototype = b.prototype;
  4701. d.prototype = new __();
  4702. };
  4703. var BABYLON;
  4704. (function (BABYLON) {
  4705. var Camera = (function (_super) {
  4706. __extends(Camera, _super);
  4707. function Camera(name, position, scene) {
  4708. _super.call(this, name, scene);
  4709. this.position = position;
  4710. this.upVector = BABYLON.Vector3.Up();
  4711. this.orthoLeft = null;
  4712. this.orthoRight = null;
  4713. this.orthoBottom = null;
  4714. this.orthoTop = null;
  4715. this.fov = 0.8;
  4716. this.minZ = 0.1;
  4717. this.maxZ = 1000.0;
  4718. this.inertia = 0.9;
  4719. this.mode = Camera.PERSPECTIVE_CAMERA;
  4720. this.isIntermediate = false;
  4721. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4722. this.subCameras = [];
  4723. this.layerMask = 0xFFFFFFFF;
  4724. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4725. this._projectionMatrix = new BABYLON.Matrix();
  4726. this._postProcesses = new Array();
  4727. this._postProcessesTakenIndices = [];
  4728. scene.cameras.push(this);
  4729. if (!scene.activeCamera) {
  4730. scene.activeCamera = this;
  4731. }
  4732. }
  4733. Camera.prototype._initCache = function () {
  4734. _super.prototype._initCache.call(this);
  4735. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4736. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4737. this._cache.mode = undefined;
  4738. this._cache.minZ = undefined;
  4739. this._cache.maxZ = undefined;
  4740. this._cache.fov = undefined;
  4741. this._cache.aspectRatio = undefined;
  4742. this._cache.orthoLeft = undefined;
  4743. this._cache.orthoRight = undefined;
  4744. this._cache.orthoBottom = undefined;
  4745. this._cache.orthoTop = undefined;
  4746. this._cache.renderWidth = undefined;
  4747. this._cache.renderHeight = undefined;
  4748. };
  4749. Camera.prototype._updateCache = function (ignoreParentClass) {
  4750. if (!ignoreParentClass) {
  4751. _super.prototype._updateCache.call(this);
  4752. }
  4753. var engine = this.getEngine();
  4754. this._cache.position.copyFrom(this.position);
  4755. this._cache.upVector.copyFrom(this.upVector);
  4756. this._cache.mode = this.mode;
  4757. this._cache.minZ = this.minZ;
  4758. this._cache.maxZ = this.maxZ;
  4759. this._cache.fov = this.fov;
  4760. this._cache.aspectRatio = engine.getAspectRatio(this);
  4761. this._cache.orthoLeft = this.orthoLeft;
  4762. this._cache.orthoRight = this.orthoRight;
  4763. this._cache.orthoBottom = this.orthoBottom;
  4764. this._cache.orthoTop = this.orthoTop;
  4765. this._cache.renderWidth = engine.getRenderWidth();
  4766. this._cache.renderHeight = engine.getRenderHeight();
  4767. };
  4768. Camera.prototype._updateFromScene = function () {
  4769. this.updateCache();
  4770. this._update();
  4771. };
  4772. Camera.prototype._isSynchronized = function () {
  4773. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4774. };
  4775. Camera.prototype._isSynchronizedViewMatrix = function () {
  4776. if (!_super.prototype._isSynchronized.call(this))
  4777. return false;
  4778. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4779. };
  4780. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4781. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4782. if (!check) {
  4783. return false;
  4784. }
  4785. var engine = this.getEngine();
  4786. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4787. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4788. } else {
  4789. 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();
  4790. }
  4791. return check;
  4792. };
  4793. Camera.prototype.attachControl = function (element) {
  4794. };
  4795. Camera.prototype.detachControl = function (element) {
  4796. };
  4797. Camera.prototype._update = function () {
  4798. };
  4799. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4800. if (typeof insertAt === "undefined") { insertAt = null; }
  4801. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4802. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4803. return 0;
  4804. }
  4805. if (insertAt == null || insertAt < 0) {
  4806. this._postProcesses.push(postProcess);
  4807. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4808. return this._postProcesses.length - 1;
  4809. }
  4810. var add = 0;
  4811. if (this._postProcesses[insertAt]) {
  4812. var start = this._postProcesses.length - 1;
  4813. for (var i = start; i >= insertAt + 1; --i) {
  4814. this._postProcesses[i + 1] = this._postProcesses[i];
  4815. }
  4816. add = 1;
  4817. }
  4818. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4819. if (this._postProcessesTakenIndices[i] < insertAt) {
  4820. continue;
  4821. }
  4822. start = this._postProcessesTakenIndices.length - 1;
  4823. for (var j = start; j >= i; --j) {
  4824. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4825. }
  4826. this._postProcessesTakenIndices[i] = insertAt;
  4827. break;
  4828. }
  4829. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4830. this._postProcessesTakenIndices.push(insertAt);
  4831. }
  4832. var result = insertAt + add;
  4833. this._postProcesses[result] = postProcess;
  4834. return result;
  4835. };
  4836. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4837. if (typeof atIndices === "undefined") { atIndices = null; }
  4838. var result = [];
  4839. if (!atIndices) {
  4840. var length = this._postProcesses.length;
  4841. for (var i = 0; i < length; i++) {
  4842. if (this._postProcesses[i] !== postProcess) {
  4843. continue;
  4844. }
  4845. delete this._postProcesses[i];
  4846. var index = this._postProcessesTakenIndices.indexOf(i);
  4847. this._postProcessesTakenIndices.splice(index, 1);
  4848. }
  4849. } else {
  4850. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4851. for (i = 0; i < atIndices.length; i++) {
  4852. var foundPostProcess = this._postProcesses[atIndices[i]];
  4853. if (foundPostProcess !== postProcess) {
  4854. result.push(i);
  4855. continue;
  4856. }
  4857. delete this._postProcesses[atIndices[i]];
  4858. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4859. this._postProcessesTakenIndices.splice(index, 1);
  4860. }
  4861. }
  4862. return result;
  4863. };
  4864. Camera.prototype.getWorldMatrix = function () {
  4865. if (!this._worldMatrix) {
  4866. this._worldMatrix = BABYLON.Matrix.Identity();
  4867. }
  4868. var viewMatrix = this.getViewMatrix();
  4869. viewMatrix.invertToRef(this._worldMatrix);
  4870. return this._worldMatrix;
  4871. };
  4872. Camera.prototype._getViewMatrix = function () {
  4873. return BABYLON.Matrix.Identity();
  4874. };
  4875. Camera.prototype.getViewMatrix = function () {
  4876. this._computedViewMatrix = this._computeViewMatrix();
  4877. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4878. return this._computedViewMatrix;
  4879. }
  4880. if (!this._worldMatrix) {
  4881. this._worldMatrix = BABYLON.Matrix.Identity();
  4882. }
  4883. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4884. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4885. this._computedViewMatrix.invert();
  4886. this._currentRenderId = this.getScene().getRenderId();
  4887. return this._computedViewMatrix;
  4888. };
  4889. Camera.prototype._computeViewMatrix = function (force) {
  4890. if (!force && this._isSynchronizedViewMatrix()) {
  4891. return this._computedViewMatrix;
  4892. }
  4893. this._computedViewMatrix = this._getViewMatrix();
  4894. if (!this.parent || !this.parent.getWorldMatrix) {
  4895. this._currentRenderId = this.getScene().getRenderId();
  4896. }
  4897. return this._computedViewMatrix;
  4898. };
  4899. Camera.prototype.getProjectionMatrix = function (force) {
  4900. if (!force && this._isSynchronizedProjectionMatrix()) {
  4901. return this._projectionMatrix;
  4902. }
  4903. var engine = this.getEngine();
  4904. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4905. if (this.minZ <= 0) {
  4906. this.minZ = 0.1;
  4907. }
  4908. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4909. return this._projectionMatrix;
  4910. }
  4911. var halfWidth = engine.getRenderWidth() / 2.0;
  4912. var halfHeight = engine.getRenderHeight() / 2.0;
  4913. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4914. return this._projectionMatrix;
  4915. };
  4916. Camera.prototype.dispose = function () {
  4917. var index = this.getScene().cameras.indexOf(this);
  4918. this.getScene().cameras.splice(index, 1);
  4919. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4920. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4921. }
  4922. };
  4923. Camera.PERSPECTIVE_CAMERA = 0;
  4924. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4925. return Camera;
  4926. })(BABYLON.Node);
  4927. BABYLON.Camera = Camera;
  4928. })(BABYLON || (BABYLON = {}));
  4929. var __extends = this.__extends || function (d, b) {
  4930. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4931. function __() { this.constructor = d; }
  4932. __.prototype = b.prototype;
  4933. d.prototype = new __();
  4934. };
  4935. var BABYLON;
  4936. (function (BABYLON) {
  4937. var TargetCamera = (function (_super) {
  4938. __extends(TargetCamera, _super);
  4939. function TargetCamera(name, position, scene) {
  4940. _super.call(this, name, position, scene);
  4941. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4942. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4943. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4944. this.speed = 2.0;
  4945. this.noRotationConstraint = false;
  4946. this.lockedTarget = null;
  4947. this._currentTarget = BABYLON.Vector3.Zero();
  4948. this._viewMatrix = BABYLON.Matrix.Zero();
  4949. this._camMatrix = BABYLON.Matrix.Zero();
  4950. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4951. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4952. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4953. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4954. this._lookAtTemp = BABYLON.Matrix.Zero();
  4955. this._tempMatrix = BABYLON.Matrix.Zero();
  4956. }
  4957. TargetCamera.prototype._getLockedTargetPosition = function () {
  4958. if (!this.lockedTarget) {
  4959. return null;
  4960. }
  4961. return this.lockedTarget.position || this.lockedTarget;
  4962. };
  4963. TargetCamera.prototype._initCache = function () {
  4964. _super.prototype._initCache.call(this);
  4965. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4966. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4967. };
  4968. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4969. if (!ignoreParentClass) {
  4970. _super.prototype._updateCache.call(this);
  4971. }
  4972. var lockedTargetPosition = this._getLockedTargetPosition();
  4973. if (!lockedTargetPosition) {
  4974. this._cache.lockedTarget = null;
  4975. } else {
  4976. if (!this._cache.lockedTarget) {
  4977. this._cache.lockedTarget = lockedTargetPosition.clone();
  4978. } else {
  4979. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  4980. }
  4981. }
  4982. this._cache.rotation.copyFrom(this.rotation);
  4983. };
  4984. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  4985. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  4986. return false;
  4987. }
  4988. var lockedTargetPosition = this._getLockedTargetPosition();
  4989. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  4990. };
  4991. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  4992. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  4993. };
  4994. TargetCamera.prototype.setTarget = function (target) {
  4995. this.upVector.normalize();
  4996. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  4997. this._camMatrix.invert();
  4998. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  4999. var vDir = target.subtract(this.position);
  5000. if (vDir.x >= 0.0) {
  5001. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5002. } else {
  5003. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5004. }
  5005. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5006. if (isNaN(this.rotation.x)) {
  5007. this.rotation.x = 0;
  5008. }
  5009. if (isNaN(this.rotation.y)) {
  5010. this.rotation.y = 0;
  5011. }
  5012. if (isNaN(this.rotation.z)) {
  5013. this.rotation.z = 0;
  5014. }
  5015. };
  5016. TargetCamera.prototype.getTarget = function () {
  5017. return this._currentTarget;
  5018. };
  5019. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5020. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5021. };
  5022. TargetCamera.prototype._updatePosition = function () {
  5023. this.position.addInPlace(this.cameraDirection);
  5024. };
  5025. TargetCamera.prototype._update = function () {
  5026. var needToMove = this._decideIfNeedsToMove();
  5027. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5028. if (needToMove) {
  5029. this._updatePosition();
  5030. }
  5031. if (needToRotate) {
  5032. this.rotation.x += this.cameraRotation.x;
  5033. this.rotation.y += this.cameraRotation.y;
  5034. if (!this.noRotationConstraint) {
  5035. var limit = (Math.PI / 2) * 0.95;
  5036. if (this.rotation.x > limit)
  5037. this.rotation.x = limit;
  5038. if (this.rotation.x < -limit)
  5039. this.rotation.x = -limit;
  5040. }
  5041. }
  5042. if (needToMove) {
  5043. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5044. this.cameraDirection.x = 0;
  5045. }
  5046. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5047. this.cameraDirection.y = 0;
  5048. }
  5049. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5050. this.cameraDirection.z = 0;
  5051. }
  5052. this.cameraDirection.scaleInPlace(this.inertia);
  5053. }
  5054. if (needToRotate) {
  5055. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5056. this.cameraRotation.x = 0;
  5057. }
  5058. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5059. this.cameraRotation.y = 0;
  5060. }
  5061. this.cameraRotation.scaleInPlace(this.inertia);
  5062. }
  5063. };
  5064. TargetCamera.prototype._getViewMatrix = function () {
  5065. if (!this.lockedTarget) {
  5066. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5067. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5068. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5069. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5070. this._lookAtTemp.invert();
  5071. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5072. } else {
  5073. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5074. }
  5075. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5076. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5077. } else {
  5078. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5079. }
  5080. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5081. return this._viewMatrix;
  5082. };
  5083. return TargetCamera;
  5084. })(BABYLON.Camera);
  5085. BABYLON.TargetCamera = TargetCamera;
  5086. })(BABYLON || (BABYLON = {}));
  5087. var __extends = this.__extends || function (d, b) {
  5088. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5089. function __() { this.constructor = d; }
  5090. __.prototype = b.prototype;
  5091. d.prototype = new __();
  5092. };
  5093. var BABYLON;
  5094. (function (BABYLON) {
  5095. var FollowCamera = (function (_super) {
  5096. __extends(FollowCamera, _super);
  5097. function FollowCamera(name, position, scene) {
  5098. _super.call(this, name, position, scene);
  5099. this.radius = 12;
  5100. this.rotationOffset = 0;
  5101. this.heightOffset = 4;
  5102. this.cameraAcceleration = 0.05;
  5103. this.maxCameraSpeed = 20;
  5104. }
  5105. FollowCamera.prototype.getRadians = function (degrees) {
  5106. return degrees * Math.PI / 180;
  5107. };
  5108. FollowCamera.prototype.follow = function (cameraTarget) {
  5109. if (!cameraTarget)
  5110. return;
  5111. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5112. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5113. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5114. var dx = targetX - this.position.x;
  5115. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5116. var dz = (targetZ) - this.position.z;
  5117. var vx = dx * this.cameraAcceleration * 2;
  5118. var vy = dy * this.cameraAcceleration;
  5119. var vz = dz * this.cameraAcceleration * 2;
  5120. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5121. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5122. }
  5123. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5124. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5125. }
  5126. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5127. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5128. }
  5129. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5130. this.setTarget(cameraTarget.position);
  5131. };
  5132. FollowCamera.prototype._update = function () {
  5133. _super.prototype._update.call(this);
  5134. this.follow(this.target);
  5135. };
  5136. return FollowCamera;
  5137. })(BABYLON.TargetCamera);
  5138. BABYLON.FollowCamera = FollowCamera;
  5139. })(BABYLON || (BABYLON = {}));
  5140. var __extends = this.__extends || function (d, b) {
  5141. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5142. function __() { this.constructor = d; }
  5143. __.prototype = b.prototype;
  5144. d.prototype = new __();
  5145. };
  5146. var BABYLON;
  5147. (function (BABYLON) {
  5148. var FreeCamera = (function (_super) {
  5149. __extends(FreeCamera, _super);
  5150. function FreeCamera(name, position, scene) {
  5151. _super.call(this, name, position, scene);
  5152. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5153. this.keysUp = [38];
  5154. this.keysDown = [40];
  5155. this.keysLeft = [37];
  5156. this.keysRight = [39];
  5157. this.checkCollisions = false;
  5158. this.applyGravity = false;
  5159. this.angularSensibility = 2000.0;
  5160. this._keys = [];
  5161. this._collider = new BABYLON.Collider();
  5162. this._needMoveForGravity = true;
  5163. this._oldPosition = BABYLON.Vector3.Zero();
  5164. this._diffPosition = BABYLON.Vector3.Zero();
  5165. this._newPosition = BABYLON.Vector3.Zero();
  5166. }
  5167. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5168. var _this = this;
  5169. var previousPosition;
  5170. var engine = this.getEngine();
  5171. if (this._attachedElement) {
  5172. return;
  5173. }
  5174. this._attachedElement = element;
  5175. if (this._onMouseDown === undefined) {
  5176. this._onMouseDown = function (evt) {
  5177. previousPosition = {
  5178. x: evt.clientX,
  5179. y: evt.clientY
  5180. };
  5181. if (!noPreventDefault) {
  5182. evt.preventDefault();
  5183. }
  5184. };
  5185. this._onMouseUp = function (evt) {
  5186. previousPosition = null;
  5187. if (!noPreventDefault) {
  5188. evt.preventDefault();
  5189. }
  5190. };
  5191. this._onMouseOut = function (evt) {
  5192. previousPosition = null;
  5193. _this._keys = [];
  5194. if (!noPreventDefault) {
  5195. evt.preventDefault();
  5196. }
  5197. };
  5198. this._onMouseMove = function (evt) {
  5199. if (!previousPosition && !engine.isPointerLock) {
  5200. return;
  5201. }
  5202. var offsetX;
  5203. var offsetY;
  5204. if (!engine.isPointerLock) {
  5205. offsetX = evt.clientX - previousPosition.x;
  5206. offsetY = evt.clientY - previousPosition.y;
  5207. } else {
  5208. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5209. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5210. }
  5211. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5212. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5213. previousPosition = {
  5214. x: evt.clientX,
  5215. y: evt.clientY
  5216. };
  5217. if (!noPreventDefault) {
  5218. evt.preventDefault();
  5219. }
  5220. };
  5221. this._onKeyDown = function (evt) {
  5222. 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) {
  5223. var index = _this._keys.indexOf(evt.keyCode);
  5224. if (index === -1) {
  5225. _this._keys.push(evt.keyCode);
  5226. }
  5227. if (!noPreventDefault) {
  5228. evt.preventDefault();
  5229. }
  5230. }
  5231. };
  5232. this._onKeyUp = function (evt) {
  5233. 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) {
  5234. var index = _this._keys.indexOf(evt.keyCode);
  5235. if (index >= 0) {
  5236. _this._keys.splice(index, 1);
  5237. }
  5238. if (!noPreventDefault) {
  5239. evt.preventDefault();
  5240. }
  5241. }
  5242. };
  5243. this._onLostFocus = function () {
  5244. _this._keys = [];
  5245. };
  5246. this._reset = function () {
  5247. _this._keys = [];
  5248. previousPosition = null;
  5249. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5250. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5251. };
  5252. }
  5253. element.addEventListener("mousedown", this._onMouseDown, false);
  5254. element.addEventListener("mouseup", this._onMouseUp, false);
  5255. element.addEventListener("mouseout", this._onMouseOut, false);
  5256. element.addEventListener("mousemove", this._onMouseMove, false);
  5257. BABYLON.Tools.RegisterTopRootEvents([
  5258. { name: "keydown", handler: this._onKeyDown },
  5259. { name: "keyup", handler: this._onKeyUp },
  5260. { name: "blur", handler: this._onLostFocus }
  5261. ]);
  5262. };
  5263. FreeCamera.prototype.detachControl = function (element) {
  5264. if (this._attachedElement != element) {
  5265. return;
  5266. }
  5267. element.removeEventListener("mousedown", this._onMouseDown);
  5268. element.removeEventListener("mouseup", this._onMouseUp);
  5269. element.removeEventListener("mouseout", this._onMouseOut);
  5270. element.removeEventListener("mousemove", this._onMouseMove);
  5271. BABYLON.Tools.UnregisterTopRootEvents([
  5272. { name: "keydown", handler: this._onKeyDown },
  5273. { name: "keyup", handler: this._onKeyUp },
  5274. { name: "blur", handler: this._onLostFocus }
  5275. ]);
  5276. this._attachedElement = null;
  5277. if (this._reset) {
  5278. this._reset();
  5279. }
  5280. };
  5281. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5282. var globalPosition;
  5283. if (this.parent) {
  5284. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5285. } else {
  5286. globalPosition = this.position;
  5287. }
  5288. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5289. this._collider.radius = this.ellipsoid;
  5290. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5291. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5292. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5293. this.position.addInPlace(this._diffPosition);
  5294. if (this.onCollide) {
  5295. this.onCollide(this._collider.collidedMesh);
  5296. }
  5297. }
  5298. };
  5299. FreeCamera.prototype._checkInputs = function () {
  5300. if (!this._localDirection) {
  5301. this._localDirection = BABYLON.Vector3.Zero();
  5302. this._transformedDirection = BABYLON.Vector3.Zero();
  5303. }
  5304. for (var index = 0; index < this._keys.length; index++) {
  5305. var keyCode = this._keys[index];
  5306. var speed = this._computeLocalCameraSpeed();
  5307. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5308. this._localDirection.copyFromFloats(-speed, 0, 0);
  5309. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5310. this._localDirection.copyFromFloats(0, 0, speed);
  5311. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5312. this._localDirection.copyFromFloats(speed, 0, 0);
  5313. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5314. this._localDirection.copyFromFloats(0, 0, -speed);
  5315. }
  5316. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5317. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5318. this.cameraDirection.addInPlace(this._transformedDirection);
  5319. }
  5320. };
  5321. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5322. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5323. };
  5324. FreeCamera.prototype._updatePosition = function () {
  5325. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5326. this._collideWithWorld(this.cameraDirection);
  5327. if (this.applyGravity) {
  5328. var oldPosition = this.position;
  5329. this._collideWithWorld(this.getScene().gravity);
  5330. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5331. }
  5332. } else {
  5333. this.position.addInPlace(this.cameraDirection);
  5334. }
  5335. };
  5336. FreeCamera.prototype._update = function () {
  5337. this._checkInputs();
  5338. _super.prototype._update.call(this);
  5339. };
  5340. return FreeCamera;
  5341. })(BABYLON.TargetCamera);
  5342. BABYLON.FreeCamera = FreeCamera;
  5343. })(BABYLON || (BABYLON = {}));
  5344. var __extends = this.__extends || function (d, b) {
  5345. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5346. function __() { this.constructor = d; }
  5347. __.prototype = b.prototype;
  5348. d.prototype = new __();
  5349. };
  5350. var BABYLON;
  5351. (function (BABYLON) {
  5352. var TouchCamera = (function (_super) {
  5353. __extends(TouchCamera, _super);
  5354. function TouchCamera(name, position, scene) {
  5355. _super.call(this, name, position, scene);
  5356. this._offsetX = null;
  5357. this._offsetY = null;
  5358. this._pointerCount = 0;
  5359. this._pointerPressed = [];
  5360. this.angularSensibility = 200000.0;
  5361. this.moveSensibility = 500.0;
  5362. }
  5363. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5364. var _this = this;
  5365. var previousPosition;
  5366. if (this._attachedCanvas) {
  5367. return;
  5368. }
  5369. this._attachedCanvas = canvas;
  5370. if (this._onPointerDown === undefined) {
  5371. this._onPointerDown = function (evt) {
  5372. if (!noPreventDefault) {
  5373. evt.preventDefault();
  5374. }
  5375. _this._pointerPressed.push(evt.pointerId);
  5376. if (_this._pointerPressed.length !== 1) {
  5377. return;
  5378. }
  5379. previousPosition = {
  5380. x: evt.clientX,
  5381. y: evt.clientY
  5382. };
  5383. };
  5384. this._onPointerUp = function (evt) {
  5385. if (!noPreventDefault) {
  5386. evt.preventDefault();
  5387. }
  5388. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5389. if (index === -1) {
  5390. return;
  5391. }
  5392. _this._pointerPressed.splice(index, 1);
  5393. if (index != 0) {
  5394. return;
  5395. }
  5396. previousPosition = null;
  5397. _this._offsetX = null;
  5398. _this._offsetY = null;
  5399. };
  5400. this._onPointerMove = function (evt) {
  5401. if (!noPreventDefault) {
  5402. evt.preventDefault();
  5403. }
  5404. if (!previousPosition) {
  5405. return;
  5406. }
  5407. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5408. if (index != 0) {
  5409. return;
  5410. }
  5411. _this._offsetX = evt.clientX - previousPosition.x;
  5412. _this._offsetY = -(evt.clientY - previousPosition.y);
  5413. };
  5414. this._onLostFocus = function () {
  5415. _this._offsetX = null;
  5416. _this._offsetY = null;
  5417. };
  5418. }
  5419. canvas.addEventListener("pointerdown", this._onPointerDown);
  5420. canvas.addEventListener("pointerup", this._onPointerUp);
  5421. canvas.addEventListener("pointerout", this._onPointerUp);
  5422. canvas.addEventListener("pointermove", this._onPointerMove);
  5423. BABYLON.Tools.RegisterTopRootEvents([
  5424. { name: "blur", handler: this._onLostFocus }
  5425. ]);
  5426. };
  5427. TouchCamera.prototype.detachControl = function (canvas) {
  5428. if (this._attachedCanvas != canvas) {
  5429. return;
  5430. }
  5431. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5432. canvas.removeEventListener("pointerup", this._onPointerUp);
  5433. canvas.removeEventListener("pointerout", this._onPointerUp);
  5434. canvas.removeEventListener("pointermove", this._onPointerMove);
  5435. BABYLON.Tools.UnregisterTopRootEvents([
  5436. { name: "blur", handler: this._onLostFocus }
  5437. ]);
  5438. this._attachedCanvas = null;
  5439. };
  5440. TouchCamera.prototype._checkInputs = function () {
  5441. if (!this._offsetX) {
  5442. return;
  5443. }
  5444. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5445. if (this._pointerPressed.length > 1) {
  5446. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5447. } else {
  5448. var speed = this._computeLocalCameraSpeed();
  5449. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5450. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5451. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5452. }
  5453. };
  5454. return TouchCamera;
  5455. })(BABYLON.FreeCamera);
  5456. BABYLON.TouchCamera = TouchCamera;
  5457. })(BABYLON || (BABYLON = {}));
  5458. var __extends = this.__extends || function (d, b) {
  5459. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5460. function __() { this.constructor = d; }
  5461. __.prototype = b.prototype;
  5462. d.prototype = new __();
  5463. };
  5464. var BABYLON;
  5465. (function (BABYLON) {
  5466. var DeviceOrientationCamera = (function (_super) {
  5467. __extends(DeviceOrientationCamera, _super);
  5468. function DeviceOrientationCamera(name, position, scene) {
  5469. var _this = this;
  5470. _super.call(this, name, position, scene);
  5471. this._offsetX = null;
  5472. this._offsetY = null;
  5473. this._orientationGamma = 0;
  5474. this._orientationBeta = 0;
  5475. this._initialOrientationGamma = 0;
  5476. this._initialOrientationBeta = 0;
  5477. this.angularSensibility = 10000.0;
  5478. this.moveSensibility = 50.0;
  5479. window.addEventListener("resize", function () {
  5480. _this._initialOrientationGamma = null;
  5481. }, false);
  5482. }
  5483. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5484. var _this = this;
  5485. if (this._attachedCanvas) {
  5486. return;
  5487. }
  5488. this._attachedCanvas = canvas;
  5489. if (!this._orientationChanged) {
  5490. this._orientationChanged = function (evt) {
  5491. if (!_this._initialOrientationGamma) {
  5492. _this._initialOrientationGamma = evt.gamma;
  5493. _this._initialOrientationBeta = evt.beta;
  5494. }
  5495. _this._orientationGamma = evt.gamma;
  5496. _this._orientationBeta = evt.beta;
  5497. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5498. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5499. };
  5500. }
  5501. window.addEventListener("deviceorientation", this._orientationChanged);
  5502. };
  5503. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5504. if (this._attachedCanvas != canvas) {
  5505. return;
  5506. }
  5507. window.removeEventListener("deviceorientation", this._orientationChanged);
  5508. this._attachedCanvas = null;
  5509. this._orientationGamma = 0;
  5510. this._orientationBeta = 0;
  5511. this._initialOrientationGamma = 0;
  5512. this._initialOrientationBeta = 0;
  5513. };
  5514. DeviceOrientationCamera.prototype._checkInputs = function () {
  5515. if (!this._offsetX) {
  5516. return;
  5517. }
  5518. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5519. var speed = this._computeLocalCameraSpeed();
  5520. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5521. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5522. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5523. };
  5524. return DeviceOrientationCamera;
  5525. })(BABYLON.FreeCamera);
  5526. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5527. })(BABYLON || (BABYLON = {}));
  5528. var __extends = this.__extends || function (d, b) {
  5529. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5530. function __() { this.constructor = d; }
  5531. __.prototype = b.prototype;
  5532. d.prototype = new __();
  5533. };
  5534. var BABYLON;
  5535. (function (BABYLON) {
  5536. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5537. var ArcRotateCamera = (function (_super) {
  5538. __extends(ArcRotateCamera, _super);
  5539. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5540. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5541. this.alpha = alpha;
  5542. this.beta = beta;
  5543. this.radius = radius;
  5544. this.target = target;
  5545. this.inertialAlphaOffset = 0;
  5546. this.inertialBetaOffset = 0;
  5547. this.inertialRadiusOffset = 0;
  5548. this.lowerAlphaLimit = null;
  5549. this.upperAlphaLimit = null;
  5550. this.lowerBetaLimit = 0.01;
  5551. this.upperBetaLimit = Math.PI;
  5552. this.lowerRadiusLimit = null;
  5553. this.upperRadiusLimit = null;
  5554. this.angularSensibility = 1000.0;
  5555. this.wheelPrecision = 3.0;
  5556. this.keysUp = [38];
  5557. this.keysDown = [40];
  5558. this.keysLeft = [37];
  5559. this.keysRight = [39];
  5560. this.zoomOnFactor = 1;
  5561. this._keys = [];
  5562. this._viewMatrix = new BABYLON.Matrix();
  5563. this.checkCollisions = false;
  5564. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5565. this._collider = new BABYLON.Collider();
  5566. this._previousPosition = BABYLON.Vector3.Zero();
  5567. this._collisionVelocity = BABYLON.Vector3.Zero();
  5568. this._newPosition = BABYLON.Vector3.Zero();
  5569. this.getViewMatrix();
  5570. }
  5571. ArcRotateCamera.prototype._getTargetPosition = function () {
  5572. return this.target.position || this.target;
  5573. };
  5574. ArcRotateCamera.prototype._initCache = function () {
  5575. _super.prototype._initCache.call(this);
  5576. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5577. this._cache.alpha = undefined;
  5578. this._cache.beta = undefined;
  5579. this._cache.radius = undefined;
  5580. };
  5581. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5582. if (!ignoreParentClass) {
  5583. _super.prototype._updateCache.call(this);
  5584. }
  5585. this._cache.target.copyFrom(this._getTargetPosition());
  5586. this._cache.alpha = this.alpha;
  5587. this._cache.beta = this.beta;
  5588. this._cache.radius = this.radius;
  5589. };
  5590. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5591. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5592. return false;
  5593. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5594. };
  5595. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5596. var _this = this;
  5597. var previousPosition;
  5598. var pointerId;
  5599. if (this._attachedElement) {
  5600. return;
  5601. }
  5602. this._attachedElement = element;
  5603. var engine = this.getEngine();
  5604. if (this._onPointerDown === undefined) {
  5605. this._onPointerDown = function (evt) {
  5606. if (pointerId) {
  5607. return;
  5608. }
  5609. pointerId = evt.pointerId;
  5610. previousPosition = {
  5611. x: evt.clientX,
  5612. y: evt.clientY
  5613. };
  5614. if (!noPreventDefault) {
  5615. evt.preventDefault();
  5616. }
  5617. };
  5618. this._onPointerUp = function (evt) {
  5619. previousPosition = null;
  5620. pointerId = null;
  5621. if (!noPreventDefault) {
  5622. evt.preventDefault();
  5623. }
  5624. };
  5625. this._onPointerMove = function (evt) {
  5626. if (!previousPosition) {
  5627. return;
  5628. }
  5629. if (pointerId !== evt.pointerId) {
  5630. return;
  5631. }
  5632. var offsetX = evt.clientX - previousPosition.x;
  5633. var offsetY = evt.clientY - previousPosition.y;
  5634. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5635. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5636. previousPosition = {
  5637. x: evt.clientX,
  5638. y: evt.clientY
  5639. };
  5640. if (!noPreventDefault) {
  5641. evt.preventDefault();
  5642. }
  5643. };
  5644. this._onMouseMove = function (evt) {
  5645. if (!engine.isPointerLock) {
  5646. return;
  5647. }
  5648. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5649. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5650. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5651. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5652. if (!noPreventDefault) {
  5653. evt.preventDefault();
  5654. }
  5655. };
  5656. this._wheel = function (event) {
  5657. var delta = 0;
  5658. if (event.wheelDelta) {
  5659. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5660. } else if (event.detail) {
  5661. delta = -event.detail / _this.wheelPrecision;
  5662. }
  5663. if (delta)
  5664. _this.inertialRadiusOffset += delta;
  5665. if (event.preventDefault) {
  5666. if (!noPreventDefault) {
  5667. event.preventDefault();
  5668. }
  5669. }
  5670. };
  5671. this._onKeyDown = function (evt) {
  5672. 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) {
  5673. var index = _this._keys.indexOf(evt.keyCode);
  5674. if (index === -1) {
  5675. _this._keys.push(evt.keyCode);
  5676. }
  5677. if (evt.preventDefault) {
  5678. if (!noPreventDefault) {
  5679. evt.preventDefault();
  5680. }
  5681. }
  5682. }
  5683. };
  5684. this._onKeyUp = function (evt) {
  5685. 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) {
  5686. var index = _this._keys.indexOf(evt.keyCode);
  5687. if (index >= 0) {
  5688. _this._keys.splice(index, 1);
  5689. }
  5690. if (evt.preventDefault) {
  5691. if (!noPreventDefault) {
  5692. evt.preventDefault();
  5693. }
  5694. }
  5695. }
  5696. };
  5697. this._onLostFocus = function () {
  5698. _this._keys = [];
  5699. pointerId = null;
  5700. };
  5701. this._onGestureStart = function (e) {
  5702. if (window.MSGesture === undefined) {
  5703. return;
  5704. }
  5705. if (!_this._MSGestureHandler) {
  5706. _this._MSGestureHandler = new MSGesture();
  5707. _this._MSGestureHandler.target = element;
  5708. }
  5709. _this._MSGestureHandler.addPointer(e.pointerId);
  5710. };
  5711. this._onGesture = function (e) {
  5712. _this.radius *= e.scale;
  5713. if (e.preventDefault) {
  5714. if (!noPreventDefault) {
  5715. e.stopPropagation();
  5716. e.preventDefault();
  5717. }
  5718. }
  5719. };
  5720. this._reset = function () {
  5721. _this._keys = [];
  5722. _this.inertialAlphaOffset = 0;
  5723. _this.inertialBetaOffset = 0;
  5724. _this.inertialRadiusOffset = 0;
  5725. previousPosition = null;
  5726. pointerId = null;
  5727. };
  5728. }
  5729. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5730. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5731. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5732. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5733. element.addEventListener("mousemove", this._onMouseMove, false);
  5734. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5735. element.addEventListener("MSGestureChange", this._onGesture, false);
  5736. element.addEventListener('mousewheel', this._wheel, false);
  5737. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5738. BABYLON.Tools.RegisterTopRootEvents([
  5739. { name: "keydown", handler: this._onKeyDown },
  5740. { name: "keyup", handler: this._onKeyUp },
  5741. { name: "blur", handler: this._onLostFocus }
  5742. ]);
  5743. };
  5744. ArcRotateCamera.prototype.detachControl = function (element) {
  5745. if (this._attachedElement != element) {
  5746. return;
  5747. }
  5748. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5749. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5750. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5751. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5752. element.removeEventListener("mousemove", this._onMouseMove);
  5753. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5754. element.removeEventListener("MSGestureChange", this._onGesture);
  5755. element.removeEventListener('mousewheel', this._wheel);
  5756. element.removeEventListener('DOMMouseScroll', this._wheel);
  5757. BABYLON.Tools.UnregisterTopRootEvents([
  5758. { name: "keydown", handler: this._onKeyDown },
  5759. { name: "keyup", handler: this._onKeyUp },
  5760. { name: "blur", handler: this._onLostFocus }
  5761. ]);
  5762. this._MSGestureHandler = null;
  5763. this._attachedElement = null;
  5764. if (this._reset) {
  5765. this._reset();
  5766. }
  5767. };
  5768. ArcRotateCamera.prototype._update = function () {
  5769. for (var index = 0; index < this._keys.length; index++) {
  5770. var keyCode = this._keys[index];
  5771. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5772. this.inertialAlphaOffset -= 0.01;
  5773. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5774. this.inertialBetaOffset -= 0.01;
  5775. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5776. this.inertialAlphaOffset += 0.01;
  5777. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5778. this.inertialBetaOffset += 0.01;
  5779. }
  5780. }
  5781. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5782. this.alpha += this.inertialAlphaOffset;
  5783. this.beta += this.inertialBetaOffset;
  5784. this.radius -= this.inertialRadiusOffset;
  5785. this.inertialAlphaOffset *= this.inertia;
  5786. this.inertialBetaOffset *= this.inertia;
  5787. this.inertialRadiusOffset *= this.inertia;
  5788. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5789. this.inertialAlphaOffset = 0;
  5790. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5791. this.inertialBetaOffset = 0;
  5792. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5793. this.inertialRadiusOffset = 0;
  5794. }
  5795. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5796. this.alpha = this.lowerAlphaLimit;
  5797. }
  5798. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5799. this.alpha = this.upperAlphaLimit;
  5800. }
  5801. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5802. this.beta = this.lowerBetaLimit;
  5803. }
  5804. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5805. this.beta = this.upperBetaLimit;
  5806. }
  5807. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5808. this.radius = this.lowerRadiusLimit;
  5809. }
  5810. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5811. this.radius = this.upperRadiusLimit;
  5812. }
  5813. };
  5814. ArcRotateCamera.prototype.setPosition = function (position) {
  5815. var radiusv3 = position.subtract(this._getTargetPosition());
  5816. this.radius = radiusv3.length();
  5817. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5818. if (radiusv3.z < 0) {
  5819. this.alpha = 2 * Math.PI - this.alpha;
  5820. }
  5821. this.beta = Math.acos(radiusv3.y / this.radius);
  5822. };
  5823. ArcRotateCamera.prototype._getViewMatrix = function () {
  5824. var cosa = Math.cos(this.alpha);
  5825. var sina = Math.sin(this.alpha);
  5826. var cosb = Math.cos(this.beta);
  5827. var sinb = Math.sin(this.beta);
  5828. var target = this._getTargetPosition();
  5829. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5830. if (this.checkCollisions) {
  5831. this._collider.radius = this.collisionRadius;
  5832. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5833. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5834. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5835. this.position.copyFrom(this._previousPosition);
  5836. this.alpha = this._previousAlpha;
  5837. this.beta = this._previousBeta;
  5838. this.radius = this._previousRadius;
  5839. if (this.onCollide) {
  5840. this.onCollide(this._collider.collidedMesh);
  5841. }
  5842. }
  5843. }
  5844. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5845. this._previousAlpha = this.alpha;
  5846. this._previousBeta = this.beta;
  5847. this._previousRadius = this.radius;
  5848. this._previousPosition.copyFrom(this.position);
  5849. return this._viewMatrix;
  5850. };
  5851. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5852. meshes = meshes || this.getScene().meshes;
  5853. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5854. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5855. this.radius = distance * this.zoomOnFactor;
  5856. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5857. };
  5858. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5859. var meshesOrMinMaxVector;
  5860. var distance;
  5861. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5862. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5863. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5864. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5865. } else {
  5866. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5867. distance = meshesOrMinMaxVectorAndDistance.distance;
  5868. }
  5869. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5870. this.maxZ = distance * 2;
  5871. };
  5872. return ArcRotateCamera;
  5873. })(BABYLON.Camera);
  5874. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5875. })(BABYLON || (BABYLON = {}));
  5876. var BABYLON;
  5877. (function (BABYLON) {
  5878. var Scene = (function () {
  5879. function Scene(engine) {
  5880. this.autoClear = true;
  5881. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5882. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5883. this.forceWireframe = false;
  5884. this.cameraToUseForPointers = null;
  5885. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5886. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5887. this.fogDensity = 0.1;
  5888. this.fogStart = 0;
  5889. this.fogEnd = 1000.0;
  5890. this.lightsEnabled = true;
  5891. this.lights = new Array();
  5892. this.cameras = new Array();
  5893. this.activeCameras = new Array();
  5894. this.meshes = new Array();
  5895. this._geometries = new Array();
  5896. this.materials = new Array();
  5897. this.multiMaterials = new Array();
  5898. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5899. this.texturesEnabled = true;
  5900. this.textures = new Array();
  5901. this.particlesEnabled = true;
  5902. this.particleSystems = new Array();
  5903. this.spriteManagers = new Array();
  5904. this.layers = new Array();
  5905. this.skeletons = new Array();
  5906. this.lensFlareSystems = new Array();
  5907. this.collisionsEnabled = true;
  5908. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5909. this.postProcessesEnabled = true;
  5910. this.renderTargetsEnabled = true;
  5911. this.customRenderTargets = new Array();
  5912. this.importedMeshesFiles = new Array();
  5913. this._actionManagers = new Array();
  5914. this._meshesForIntersections = new BABYLON.SmartArray(256);
  5915. this._totalVertices = 0;
  5916. this._activeVertices = 0;
  5917. this._activeParticles = 0;
  5918. this._lastFrameDuration = 0;
  5919. this._evaluateActiveMeshesDuration = 0;
  5920. this._renderTargetsDuration = 0;
  5921. this._particlesDuration = 0;
  5922. this._renderDuration = 0;
  5923. this._spritesDuration = 0;
  5924. this._animationRatio = 0;
  5925. this._renderId = 0;
  5926. this._executeWhenReadyTimeoutId = -1;
  5927. this._toBeDisposed = new BABYLON.SmartArray(256);
  5928. this._onReadyCallbacks = new Array();
  5929. this._pendingData = [];
  5930. this._onBeforeRenderCallbacks = new Array();
  5931. this._activeMeshes = new BABYLON.SmartArray(256);
  5932. this._processedMaterials = new BABYLON.SmartArray(256);
  5933. this._renderTargets = new BABYLON.SmartArray(256);
  5934. this._activeParticleSystems = new BABYLON.SmartArray(256);
  5935. this._activeSkeletons = new BABYLON.SmartArray(32);
  5936. this._activeAnimatables = new Array();
  5937. this._transformMatrix = BABYLON.Matrix.Zero();
  5938. this._scaledPosition = BABYLON.Vector3.Zero();
  5939. this._scaledVelocity = BABYLON.Vector3.Zero();
  5940. this._engine = engine;
  5941. engine.scenes.push(this);
  5942. this._renderingManager = new BABYLON.RenderingManager(this);
  5943. this.postProcessManager = new BABYLON.PostProcessManager(this);
  5944. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  5945. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  5946. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  5947. this.attachControl();
  5948. }
  5949. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  5950. get: function () {
  5951. return this._meshUnderPointer;
  5952. },
  5953. enumerable: true,
  5954. configurable: true
  5955. });
  5956. Object.defineProperty(Scene.prototype, "pointerX", {
  5957. get: function () {
  5958. return this._pointerX;
  5959. },
  5960. enumerable: true,
  5961. configurable: true
  5962. });
  5963. Object.defineProperty(Scene.prototype, "pointerY", {
  5964. get: function () {
  5965. return this._pointerY;
  5966. },
  5967. enumerable: true,
  5968. configurable: true
  5969. });
  5970. Scene.prototype.getBoundingBoxRenderer = function () {
  5971. return this._boundingBoxRenderer;
  5972. };
  5973. Scene.prototype.getOutlineRenderer = function () {
  5974. return this._outlineRenderer;
  5975. };
  5976. Scene.prototype.getEngine = function () {
  5977. return this._engine;
  5978. };
  5979. Scene.prototype.getTotalVertices = function () {
  5980. return this._totalVertices;
  5981. };
  5982. Scene.prototype.getActiveVertices = function () {
  5983. return this._activeVertices;
  5984. };
  5985. Scene.prototype.getActiveParticles = function () {
  5986. return this._activeParticles;
  5987. };
  5988. Scene.prototype.getLastFrameDuration = function () {
  5989. return this._lastFrameDuration;
  5990. };
  5991. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  5992. return this._evaluateActiveMeshesDuration;
  5993. };
  5994. Scene.prototype.getActiveMeshes = function () {
  5995. return this._activeMeshes;
  5996. };
  5997. Scene.prototype.getRenderTargetsDuration = function () {
  5998. return this._renderTargetsDuration;
  5999. };
  6000. Scene.prototype.getRenderDuration = function () {
  6001. return this._renderDuration;
  6002. };
  6003. Scene.prototype.getParticlesDuration = function () {
  6004. return this._particlesDuration;
  6005. };
  6006. Scene.prototype.getSpritesDuration = function () {
  6007. return this._spritesDuration;
  6008. };
  6009. Scene.prototype.getAnimationRatio = function () {
  6010. return this._animationRatio;
  6011. };
  6012. Scene.prototype.getRenderId = function () {
  6013. return this._renderId;
  6014. };
  6015. Scene.prototype._updatePointerPosition = function (evt) {
  6016. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6017. this._pointerX = evt.clientX - canvasRect.left;
  6018. this._pointerY = evt.clientY - canvasRect.top;
  6019. if (this.cameraToUseForPointers) {
  6020. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6021. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6022. }
  6023. };
  6024. Scene.prototype.attachControl = function () {
  6025. var _this = this;
  6026. this._onPointerMove = function (evt) {
  6027. var canvas = _this._engine.getRenderingCanvas();
  6028. _this._updatePointerPosition(evt);
  6029. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6030. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6031. }, false, _this.cameraToUseForPointers);
  6032. if (pickResult.hit) {
  6033. _this._meshUnderPointer = pickResult.pickedMesh;
  6034. _this.setPointerOverMesh(pickResult.pickedMesh);
  6035. canvas.style.cursor = "pointer";
  6036. } else {
  6037. _this.setPointerOverMesh(null);
  6038. canvas.style.cursor = "";
  6039. _this._meshUnderPointer = null;
  6040. }
  6041. };
  6042. this._onPointerDown = function (evt) {
  6043. var predicate = null;
  6044. if (!_this.onPointerDown) {
  6045. predicate = function (mesh) {
  6046. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6047. };
  6048. }
  6049. _this._updatePointerPosition(evt);
  6050. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6051. if (pickResult.hit) {
  6052. if (pickResult.pickedMesh.actionManager) {
  6053. switch (evt.button) {
  6054. case 0:
  6055. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6056. break;
  6057. case 1:
  6058. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6059. break;
  6060. case 2:
  6061. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6062. break;
  6063. }
  6064. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6065. }
  6066. }
  6067. if (_this.onPointerDown) {
  6068. _this.onPointerDown(evt, pickResult);
  6069. }
  6070. };
  6071. this._onKeyDown = function (evt) {
  6072. if (_this.actionManager) {
  6073. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6074. }
  6075. };
  6076. this._onKeyUp = function (evt) {
  6077. if (_this.actionManager) {
  6078. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6079. }
  6080. };
  6081. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6082. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6083. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6084. window.addEventListener("keydown", this._onKeyDown, false);
  6085. window.addEventListener("keyup", this._onKeyUp, false);
  6086. };
  6087. Scene.prototype.detachControl = function () {
  6088. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6089. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6090. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6091. window.removeEventListener("keydown", this._onKeyDown);
  6092. window.removeEventListener("keyup", this._onKeyUp);
  6093. };
  6094. Scene.prototype.isReady = function () {
  6095. if (this._pendingData.length > 0) {
  6096. return false;
  6097. }
  6098. for (var index = 0; index < this._geometries.length; index++) {
  6099. var geometry = this._geometries[index];
  6100. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6101. return false;
  6102. }
  6103. }
  6104. for (index = 0; index < this.meshes.length; index++) {
  6105. var mesh = this.meshes[index];
  6106. if (!mesh.isReady()) {
  6107. return false;
  6108. }
  6109. var mat = mesh.material;
  6110. if (mat) {
  6111. if (!mat.isReady(mesh)) {
  6112. return false;
  6113. }
  6114. }
  6115. }
  6116. return true;
  6117. };
  6118. Scene.prototype.registerBeforeRender = function (func) {
  6119. this._onBeforeRenderCallbacks.push(func);
  6120. };
  6121. Scene.prototype.unregisterBeforeRender = function (func) {
  6122. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6123. if (index > -1) {
  6124. this._onBeforeRenderCallbacks.splice(index, 1);
  6125. }
  6126. };
  6127. Scene.prototype._addPendingData = function (data) {
  6128. this._pendingData.push(data);
  6129. };
  6130. Scene.prototype._removePendingData = function (data) {
  6131. var index = this._pendingData.indexOf(data);
  6132. if (index !== -1) {
  6133. this._pendingData.splice(index, 1);
  6134. }
  6135. };
  6136. Scene.prototype.getWaitingItemsCount = function () {
  6137. return this._pendingData.length;
  6138. };
  6139. Scene.prototype.executeWhenReady = function (func) {
  6140. var _this = this;
  6141. this._onReadyCallbacks.push(func);
  6142. if (this._executeWhenReadyTimeoutId !== -1) {
  6143. return;
  6144. }
  6145. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6146. _this._checkIsReady();
  6147. }, 150);
  6148. };
  6149. Scene.prototype._checkIsReady = function () {
  6150. var _this = this;
  6151. if (this.isReady()) {
  6152. this._onReadyCallbacks.forEach(function (func) {
  6153. func();
  6154. });
  6155. this._onReadyCallbacks = [];
  6156. this._executeWhenReadyTimeoutId = -1;
  6157. return;
  6158. }
  6159. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6160. _this._checkIsReady();
  6161. }, 150);
  6162. };
  6163. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6164. if (speedRatio === undefined) {
  6165. speedRatio = 1.0;
  6166. }
  6167. this.stopAnimation(target);
  6168. if (!animatable) {
  6169. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6170. }
  6171. if (target.animations) {
  6172. animatable.appendAnimations(target, target.animations);
  6173. }
  6174. if (target.getAnimatables) {
  6175. var animatables = target.getAnimatables();
  6176. for (var index = 0; index < animatables.length; index++) {
  6177. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6178. }
  6179. }
  6180. return animatable;
  6181. };
  6182. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6183. if (speedRatio === undefined) {
  6184. speedRatio = 1.0;
  6185. }
  6186. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6187. return animatable;
  6188. };
  6189. Scene.prototype.getAnimatableByTarget = function (target) {
  6190. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6191. if (this._activeAnimatables[index].target === target) {
  6192. return this._activeAnimatables[index];
  6193. }
  6194. }
  6195. return null;
  6196. };
  6197. Scene.prototype.stopAnimation = function (target) {
  6198. var animatable = this.getAnimatableByTarget(target);
  6199. if (animatable) {
  6200. animatable.stop();
  6201. }
  6202. };
  6203. Scene.prototype._animate = function () {
  6204. if (!this._animationStartDate) {
  6205. this._animationStartDate = new Date().getTime();
  6206. }
  6207. var now = new Date().getTime();
  6208. var delay = now - this._animationStartDate;
  6209. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6210. if (!this._activeAnimatables[index]._animate(delay)) {
  6211. this._activeAnimatables.splice(index, 1);
  6212. index--;
  6213. }
  6214. }
  6215. };
  6216. Scene.prototype.getViewMatrix = function () {
  6217. return this._viewMatrix;
  6218. };
  6219. Scene.prototype.getProjectionMatrix = function () {
  6220. return this._projectionMatrix;
  6221. };
  6222. Scene.prototype.getTransformMatrix = function () {
  6223. return this._transformMatrix;
  6224. };
  6225. Scene.prototype.setTransformMatrix = function (view, projection) {
  6226. this._viewMatrix = view;
  6227. this._projectionMatrix = projection;
  6228. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6229. };
  6230. Scene.prototype.setActiveCameraByID = function (id) {
  6231. var camera = this.getCameraByID(id);
  6232. if (camera) {
  6233. this.activeCamera = camera;
  6234. return camera;
  6235. }
  6236. return null;
  6237. };
  6238. Scene.prototype.setActiveCameraByName = function (name) {
  6239. var camera = this.getCameraByName(name);
  6240. if (camera) {
  6241. this.activeCamera = camera;
  6242. return camera;
  6243. }
  6244. return null;
  6245. };
  6246. Scene.prototype.getMaterialByID = function (id) {
  6247. for (var index = 0; index < this.materials.length; index++) {
  6248. if (this.materials[index].id === id) {
  6249. return this.materials[index];
  6250. }
  6251. }
  6252. return null;
  6253. };
  6254. Scene.prototype.getMaterialByName = function (name) {
  6255. for (var index = 0; index < this.materials.length; index++) {
  6256. if (this.materials[index].name === name) {
  6257. return this.materials[index];
  6258. }
  6259. }
  6260. return null;
  6261. };
  6262. Scene.prototype.getCameraByID = function (id) {
  6263. for (var index = 0; index < this.cameras.length; index++) {
  6264. if (this.cameras[index].id === id) {
  6265. return this.cameras[index];
  6266. }
  6267. }
  6268. return null;
  6269. };
  6270. Scene.prototype.getCameraByName = function (name) {
  6271. for (var index = 0; index < this.cameras.length; index++) {
  6272. if (this.cameras[index].name === name) {
  6273. return this.cameras[index];
  6274. }
  6275. }
  6276. return null;
  6277. };
  6278. Scene.prototype.getLightByName = function (name) {
  6279. for (var index = 0; index < this.lights.length; index++) {
  6280. if (this.lights[index].name === name) {
  6281. return this.lights[index];
  6282. }
  6283. }
  6284. return null;
  6285. };
  6286. Scene.prototype.getLightByID = function (id) {
  6287. for (var index = 0; index < this.lights.length; index++) {
  6288. if (this.lights[index].id === id) {
  6289. return this.lights[index];
  6290. }
  6291. }
  6292. return null;
  6293. };
  6294. Scene.prototype.getGeometryByID = function (id) {
  6295. for (var index = 0; index < this._geometries.length; index++) {
  6296. if (this._geometries[index].id === id) {
  6297. return this._geometries[index];
  6298. }
  6299. }
  6300. return null;
  6301. };
  6302. Scene.prototype.pushGeometry = function (geometry, force) {
  6303. if (!force && this.getGeometryByID(geometry.id)) {
  6304. return false;
  6305. }
  6306. this._geometries.push(geometry);
  6307. return true;
  6308. };
  6309. Scene.prototype.getGeometries = function () {
  6310. return this._geometries;
  6311. };
  6312. Scene.prototype.getMeshByID = function (id) {
  6313. for (var index = 0; index < this.meshes.length; index++) {
  6314. if (this.meshes[index].id === id) {
  6315. return this.meshes[index];
  6316. }
  6317. }
  6318. return null;
  6319. };
  6320. Scene.prototype.getLastMeshByID = function (id) {
  6321. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6322. if (this.meshes[index].id === id) {
  6323. return this.meshes[index];
  6324. }
  6325. }
  6326. return null;
  6327. };
  6328. Scene.prototype.getLastEntryByID = function (id) {
  6329. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6330. if (this.meshes[index].id === id) {
  6331. return this.meshes[index];
  6332. }
  6333. }
  6334. for (index = this.cameras.length - 1; index >= 0; index--) {
  6335. if (this.cameras[index].id === id) {
  6336. return this.cameras[index];
  6337. }
  6338. }
  6339. for (index = this.lights.length - 1; index >= 0; index--) {
  6340. if (this.lights[index].id === id) {
  6341. return this.lights[index];
  6342. }
  6343. }
  6344. return null;
  6345. };
  6346. Scene.prototype.getMeshByName = function (name) {
  6347. for (var index = 0; index < this.meshes.length; index++) {
  6348. if (this.meshes[index].name === name) {
  6349. return this.meshes[index];
  6350. }
  6351. }
  6352. return null;
  6353. };
  6354. Scene.prototype.getLastSkeletonByID = function (id) {
  6355. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6356. if (this.skeletons[index].id === id) {
  6357. return this.skeletons[index];
  6358. }
  6359. }
  6360. return null;
  6361. };
  6362. Scene.prototype.getSkeletonById = function (id) {
  6363. for (var index = 0; index < this.skeletons.length; index++) {
  6364. if (this.skeletons[index].id === id) {
  6365. return this.skeletons[index];
  6366. }
  6367. }
  6368. return null;
  6369. };
  6370. Scene.prototype.getSkeletonByName = function (name) {
  6371. for (var index = 0; index < this.skeletons.length; index++) {
  6372. if (this.skeletons[index].name === name) {
  6373. return this.skeletons[index];
  6374. }
  6375. }
  6376. return null;
  6377. };
  6378. Scene.prototype.isActiveMesh = function (mesh) {
  6379. return (this._activeMeshes.indexOf(mesh) !== -1);
  6380. };
  6381. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6382. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6383. var material = subMesh.getMaterial();
  6384. if (mesh.showSubMeshesBoundingBox) {
  6385. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6386. }
  6387. if (material) {
  6388. if (material.getRenderTargetTextures) {
  6389. if (this._processedMaterials.indexOf(material) === -1) {
  6390. this._processedMaterials.push(material);
  6391. this._renderTargets.concat(material.getRenderTargetTextures());
  6392. }
  6393. }
  6394. this._activeVertices += subMesh.verticesCount;
  6395. this._renderingManager.dispatch(subMesh);
  6396. }
  6397. }
  6398. };
  6399. Scene.prototype._evaluateActiveMeshes = function () {
  6400. this._activeMeshes.reset();
  6401. this._renderingManager.reset();
  6402. this._processedMaterials.reset();
  6403. this._activeParticleSystems.reset();
  6404. this._activeSkeletons.reset();
  6405. this._boundingBoxRenderer.reset();
  6406. if (!this._frustumPlanes) {
  6407. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6408. } else {
  6409. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6410. }
  6411. var meshes;
  6412. var len;
  6413. if (this._selectionOctree) {
  6414. var selection = this._selectionOctree.select(this._frustumPlanes);
  6415. meshes = selection.data;
  6416. len = selection.length;
  6417. } else {
  6418. len = this.meshes.length;
  6419. meshes = this.meshes;
  6420. }
  6421. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6422. var mesh = meshes[meshIndex];
  6423. this._totalVertices += mesh.getTotalVertices();
  6424. if (!mesh.isReady()) {
  6425. continue;
  6426. }
  6427. mesh.computeWorldMatrix();
  6428. mesh._preActivate();
  6429. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6430. this._meshesForIntersections.pushNoDuplicate(mesh);
  6431. }
  6432. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6433. this._activeMeshes.push(mesh);
  6434. mesh._activate(this._renderId);
  6435. this._activeMesh(mesh);
  6436. }
  6437. }
  6438. var beforeParticlesDate = new Date().getTime();
  6439. if (this.particlesEnabled) {
  6440. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6441. var particleSystem = this.particleSystems[particleIndex];
  6442. if (!particleSystem.isStarted()) {
  6443. continue;
  6444. }
  6445. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6446. this._activeParticleSystems.push(particleSystem);
  6447. particleSystem.animate();
  6448. }
  6449. }
  6450. }
  6451. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6452. };
  6453. Scene.prototype._activeMesh = function (mesh) {
  6454. if (mesh.skeleton) {
  6455. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6456. }
  6457. if (mesh.showBoundingBox) {
  6458. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6459. }
  6460. if (mesh.subMeshes) {
  6461. var len;
  6462. var subMeshes;
  6463. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6464. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6465. len = intersections.length;
  6466. subMeshes = intersections.data;
  6467. } else {
  6468. subMeshes = mesh.subMeshes;
  6469. len = subMeshes.length;
  6470. }
  6471. for (var subIndex = 0; subIndex < len; subIndex++) {
  6472. var subMesh = subMeshes[subIndex];
  6473. this._evaluateSubMesh(subMesh, mesh);
  6474. }
  6475. }
  6476. };
  6477. Scene.prototype.updateTransformMatrix = function (force) {
  6478. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6479. };
  6480. Scene.prototype._renderForCamera = function (camera) {
  6481. var engine = this._engine;
  6482. this.activeCamera = camera;
  6483. if (!this.activeCamera)
  6484. throw new Error("Active camera not set");
  6485. engine.setViewport(this.activeCamera.viewport);
  6486. this._renderId++;
  6487. this.updateTransformMatrix();
  6488. if (this.beforeCameraRender) {
  6489. this.beforeCameraRender(this.activeCamera);
  6490. }
  6491. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6492. this._evaluateActiveMeshes();
  6493. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6494. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6495. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6496. skeleton.prepare();
  6497. }
  6498. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6499. var renderTarget = this.customRenderTargets[customIndex];
  6500. this._renderTargets.push(renderTarget);
  6501. }
  6502. var beforeRenderTargetDate = new Date().getTime();
  6503. if (this.renderTargetsEnabled) {
  6504. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6505. renderTarget = this._renderTargets.data[renderIndex];
  6506. if (renderTarget._shouldRender()) {
  6507. this._renderId++;
  6508. renderTarget.render();
  6509. }
  6510. }
  6511. this._renderId++;
  6512. }
  6513. if (this._renderTargets.length > 0) {
  6514. engine.restoreDefaultFramebuffer();
  6515. }
  6516. this._renderTargetsDuration = new Date().getTime() - beforeRenderTargetDate;
  6517. this.postProcessManager._prepareFrame();
  6518. var beforeRenderDate = new Date().getTime();
  6519. if (this.layers.length) {
  6520. engine.setDepthBuffer(false);
  6521. var layerIndex;
  6522. var layer;
  6523. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6524. layer = this.layers[layerIndex];
  6525. if (layer.isBackground) {
  6526. layer.render();
  6527. }
  6528. }
  6529. engine.setDepthBuffer(true);
  6530. }
  6531. this._renderingManager.render(null, null, true, true);
  6532. this._boundingBoxRenderer.render();
  6533. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6534. this.lensFlareSystems[lensFlareSystemIndex].render();
  6535. }
  6536. if (this.layers.length) {
  6537. engine.setDepthBuffer(false);
  6538. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6539. layer = this.layers[layerIndex];
  6540. if (!layer.isBackground) {
  6541. layer.render();
  6542. }
  6543. }
  6544. engine.setDepthBuffer(true);
  6545. }
  6546. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6547. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6548. this.activeCamera._updateFromScene();
  6549. this._renderTargets.reset();
  6550. if (this.afterCameraRender) {
  6551. this.afterCameraRender(this.activeCamera);
  6552. }
  6553. };
  6554. Scene.prototype._processSubCameras = function (camera) {
  6555. if (camera.subCameras.length == 0) {
  6556. this._renderForCamera(camera);
  6557. return;
  6558. }
  6559. for (var index = 0; index < camera.subCameras.length; index++) {
  6560. this._renderForCamera(camera.subCameras[index]);
  6561. }
  6562. this.activeCamera = camera;
  6563. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6564. this.activeCamera._updateFromScene();
  6565. };
  6566. Scene.prototype._checkIntersections = function () {
  6567. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6568. var sourceMesh = this._meshesForIntersections.data[index];
  6569. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6570. var action = sourceMesh.actionManager.actions[actionIndex];
  6571. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6572. var otherMesh = action.getTriggerParameter();
  6573. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6574. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6575. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6576. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6577. sourceMesh._intersectionsInProgress.push(otherMesh);
  6578. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6579. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6580. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6581. if (indexOfOther > -1) {
  6582. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6583. }
  6584. }
  6585. }
  6586. }
  6587. }
  6588. };
  6589. Scene.prototype.render = function () {
  6590. var startDate = new Date().getTime();
  6591. this._particlesDuration = 0;
  6592. this._spritesDuration = 0;
  6593. this._activeParticles = 0;
  6594. this._renderDuration = 0;
  6595. this._evaluateActiveMeshesDuration = 0;
  6596. this._totalVertices = 0;
  6597. this._activeVertices = 0;
  6598. this._meshesForIntersections.reset();
  6599. if (this.actionManager) {
  6600. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6601. }
  6602. if (this.beforeRender) {
  6603. this.beforeRender();
  6604. }
  6605. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6606. this._onBeforeRenderCallbacks[callbackIndex]();
  6607. }
  6608. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6609. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6610. this._animate();
  6611. if (this._physicsEngine) {
  6612. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6613. }
  6614. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6615. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6616. var light = this.lights[lightIndex];
  6617. var shadowGenerator = light.getShadowGenerator();
  6618. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6619. this._renderTargets.push(shadowGenerator.getShadowMap());
  6620. }
  6621. }
  6622. this.postProcessRenderPipelineManager.update();
  6623. if (this.activeCameras.length > 0) {
  6624. var currentRenderId = this._renderId;
  6625. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6626. this._renderId = currentRenderId;
  6627. this._processSubCameras(this.activeCameras[cameraIndex]);
  6628. }
  6629. } else {
  6630. if (!this.activeCamera) {
  6631. throw new Error("No camera defined");
  6632. }
  6633. this._processSubCameras(this.activeCamera);
  6634. }
  6635. this._checkIntersections();
  6636. if (this.afterRender) {
  6637. this.afterRender();
  6638. }
  6639. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6640. this._toBeDisposed.data[index].dispose();
  6641. this._toBeDisposed[index] = null;
  6642. }
  6643. this._toBeDisposed.reset();
  6644. this._lastFrameDuration = new Date().getTime() - startDate;
  6645. };
  6646. Scene.prototype.dispose = function () {
  6647. this.beforeRender = null;
  6648. this.afterRender = null;
  6649. this.skeletons = [];
  6650. this._boundingBoxRenderer.dispose();
  6651. if (this.onDispose) {
  6652. this.onDispose();
  6653. }
  6654. this.detachControl();
  6655. var canvas = this._engine.getRenderingCanvas();
  6656. var index;
  6657. for (index = 0; index < this.cameras.length; index++) {
  6658. this.cameras[index].detachControl(canvas);
  6659. }
  6660. while (this.lights.length) {
  6661. this.lights[0].dispose();
  6662. }
  6663. while (this.meshes.length) {
  6664. this.meshes[0].dispose(true);
  6665. }
  6666. while (this.cameras.length) {
  6667. this.cameras[0].dispose();
  6668. }
  6669. while (this.materials.length) {
  6670. this.materials[0].dispose();
  6671. }
  6672. while (this.particleSystems.length) {
  6673. this.particleSystems[0].dispose();
  6674. }
  6675. while (this.spriteManagers.length) {
  6676. this.spriteManagers[0].dispose();
  6677. }
  6678. while (this.layers.length) {
  6679. this.layers[0].dispose();
  6680. }
  6681. while (this.textures.length) {
  6682. this.textures[0].dispose();
  6683. }
  6684. this.postProcessManager.dispose();
  6685. if (this._physicsEngine) {
  6686. this.disablePhysicsEngine();
  6687. }
  6688. index = this._engine.scenes.indexOf(this);
  6689. if (index > -1) {
  6690. this._engine.scenes.splice(index, 1);
  6691. }
  6692. this._engine.wipeCaches();
  6693. };
  6694. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6695. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6696. position.divideToRef(collider.radius, this._scaledPosition);
  6697. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6698. collider.retry = 0;
  6699. collider.initialVelocity = this._scaledVelocity;
  6700. collider.initialPosition = this._scaledPosition;
  6701. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6702. finalPosition.multiplyInPlace(collider.radius);
  6703. };
  6704. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6705. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6706. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6707. if (collider.retry >= maximumRetry) {
  6708. finalPosition.copyFrom(position);
  6709. return;
  6710. }
  6711. collider._initialize(position, velocity, closeDistance);
  6712. for (var index = 0; index < this.meshes.length; index++) {
  6713. var mesh = this.meshes[index];
  6714. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6715. mesh._checkCollision(collider);
  6716. }
  6717. }
  6718. if (!collider.collisionFound) {
  6719. position.addToRef(velocity, finalPosition);
  6720. return;
  6721. }
  6722. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6723. collider._getResponse(position, velocity);
  6724. }
  6725. if (velocity.length() <= closeDistance) {
  6726. finalPosition.copyFrom(position);
  6727. return;
  6728. }
  6729. collider.retry++;
  6730. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6731. };
  6732. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6733. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6734. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6735. if (!this._selectionOctree) {
  6736. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6737. }
  6738. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6739. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6740. for (var index = 0; index < this.meshes.length; index++) {
  6741. var mesh = this.meshes[index];
  6742. mesh.computeWorldMatrix(true);
  6743. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6744. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6745. BABYLON.Tools.CheckExtends(minBox, min, max);
  6746. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6747. }
  6748. this._selectionOctree.update(min, max, this.meshes);
  6749. return this._selectionOctree;
  6750. };
  6751. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6752. var engine = this._engine;
  6753. if (!camera) {
  6754. if (!this.activeCamera)
  6755. throw new Error("Active camera not set");
  6756. camera = this.activeCamera;
  6757. }
  6758. var cameraViewport = camera.viewport;
  6759. var viewport = cameraViewport.toGlobal(engine);
  6760. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6761. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6762. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6763. };
  6764. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6765. var pickingInfo = null;
  6766. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6767. var mesh = this.meshes[meshIndex];
  6768. if (predicate) {
  6769. if (!predicate(mesh)) {
  6770. continue;
  6771. }
  6772. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6773. continue;
  6774. }
  6775. var world = mesh.getWorldMatrix();
  6776. var ray = rayFunction(world);
  6777. var result = mesh.intersects(ray, fastCheck);
  6778. if (!result || !result.hit)
  6779. continue;
  6780. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6781. continue;
  6782. pickingInfo = result;
  6783. if (fastCheck) {
  6784. break;
  6785. }
  6786. }
  6787. return pickingInfo || new BABYLON.PickingInfo();
  6788. };
  6789. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6790. var _this = this;
  6791. return this._internalPick(function (world) {
  6792. return _this.createPickingRay(x, y, world, camera);
  6793. }, predicate, fastCheck);
  6794. };
  6795. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6796. var _this = this;
  6797. return this._internalPick(function (world) {
  6798. if (!_this._pickWithRayInverseMatrix) {
  6799. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6800. }
  6801. world.invertToRef(_this._pickWithRayInverseMatrix);
  6802. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6803. }, predicate, fastCheck);
  6804. };
  6805. Scene.prototype.setPointerOverMesh = function (mesh) {
  6806. if (this._pointerOverMesh === mesh) {
  6807. return;
  6808. }
  6809. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6810. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6811. }
  6812. this._pointerOverMesh = mesh;
  6813. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6814. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6815. }
  6816. };
  6817. Scene.prototype.getPointerOverMesh = function () {
  6818. return this._pointerOverMesh;
  6819. };
  6820. Scene.prototype.getPhysicsEngine = function () {
  6821. return this._physicsEngine;
  6822. };
  6823. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6824. if (this._physicsEngine) {
  6825. return true;
  6826. }
  6827. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6828. if (!this._physicsEngine.isSupported()) {
  6829. this._physicsEngine = null;
  6830. return false;
  6831. }
  6832. this._physicsEngine._initialize(gravity);
  6833. return true;
  6834. };
  6835. Scene.prototype.disablePhysicsEngine = function () {
  6836. if (!this._physicsEngine) {
  6837. return;
  6838. }
  6839. this._physicsEngine.dispose();
  6840. this._physicsEngine = undefined;
  6841. };
  6842. Scene.prototype.isPhysicsEnabled = function () {
  6843. return this._physicsEngine !== undefined;
  6844. };
  6845. Scene.prototype.setGravity = function (gravity) {
  6846. if (!this._physicsEngine) {
  6847. return;
  6848. }
  6849. this._physicsEngine._setGravity(gravity);
  6850. };
  6851. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6852. if (parts.parts) {
  6853. options = parts;
  6854. parts = parts.parts;
  6855. }
  6856. if (!this._physicsEngine) {
  6857. return null;
  6858. }
  6859. for (var index = 0; index < parts.length; index++) {
  6860. var mesh = parts[index].mesh;
  6861. mesh._physicImpostor = parts[index].impostor;
  6862. mesh._physicsMass = options.mass / parts.length;
  6863. mesh._physicsFriction = options.friction;
  6864. mesh._physicRestitution = options.restitution;
  6865. }
  6866. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6867. };
  6868. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6869. for (var index = 0; index < compound.parts.length; index++) {
  6870. var mesh = compound.parts[index].mesh;
  6871. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6872. this._physicsEngine._unregisterMesh(mesh);
  6873. }
  6874. };
  6875. Scene.prototype._getByTags = function (list, tagsQuery) {
  6876. if (tagsQuery === undefined) {
  6877. return list;
  6878. }
  6879. var listByTags = [];
  6880. for (var i in list) {
  6881. var item = list[i];
  6882. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6883. listByTags.push(item);
  6884. }
  6885. }
  6886. return listByTags;
  6887. };
  6888. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6889. return this._getByTags(this.meshes, tagsQuery);
  6890. };
  6891. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6892. return this._getByTags(this.cameras, tagsQuery);
  6893. };
  6894. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6895. return this._getByTags(this.lights, tagsQuery);
  6896. };
  6897. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  6898. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  6899. };
  6900. Scene.FOGMODE_NONE = 0;
  6901. Scene.FOGMODE_EXP = 1;
  6902. Scene.FOGMODE_EXP2 = 2;
  6903. Scene.FOGMODE_LINEAR = 3;
  6904. Scene.MinDeltaTime = 1.0;
  6905. Scene.MaxDeltaTime = 1000.0;
  6906. return Scene;
  6907. })();
  6908. BABYLON.Scene = Scene;
  6909. })(BABYLON || (BABYLON = {}));
  6910. var BABYLON;
  6911. (function (BABYLON) {
  6912. var VertexBuffer = (function () {
  6913. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  6914. if (engine instanceof BABYLON.Mesh) {
  6915. this._engine = engine.getScene().getEngine();
  6916. } else {
  6917. this._engine = engine;
  6918. }
  6919. this._updatable = updatable;
  6920. this._data = data;
  6921. if (!postponeInternalCreation) {
  6922. this.create();
  6923. }
  6924. this._kind = kind;
  6925. switch (kind) {
  6926. case VertexBuffer.PositionKind:
  6927. this._strideSize = 3;
  6928. break;
  6929. case VertexBuffer.NormalKind:
  6930. this._strideSize = 3;
  6931. break;
  6932. case VertexBuffer.UVKind:
  6933. this._strideSize = 2;
  6934. break;
  6935. case VertexBuffer.UV2Kind:
  6936. this._strideSize = 2;
  6937. break;
  6938. case VertexBuffer.ColorKind:
  6939. this._strideSize = 3;
  6940. break;
  6941. case VertexBuffer.MatricesIndicesKind:
  6942. this._strideSize = 4;
  6943. break;
  6944. case VertexBuffer.MatricesWeightsKind:
  6945. this._strideSize = 4;
  6946. break;
  6947. }
  6948. }
  6949. VertexBuffer.prototype.isUpdatable = function () {
  6950. return this._updatable;
  6951. };
  6952. VertexBuffer.prototype.getData = function () {
  6953. return this._data;
  6954. };
  6955. VertexBuffer.prototype.getBuffer = function () {
  6956. return this._buffer;
  6957. };
  6958. VertexBuffer.prototype.getStrideSize = function () {
  6959. return this._strideSize;
  6960. };
  6961. VertexBuffer.prototype.create = function (data) {
  6962. if (!data && this._buffer) {
  6963. return;
  6964. }
  6965. data = data || this._data;
  6966. if (!this._buffer) {
  6967. if (this._updatable) {
  6968. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  6969. } else {
  6970. this._buffer = this._engine.createVertexBuffer(data);
  6971. }
  6972. }
  6973. if (this._updatable) {
  6974. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  6975. this._data = data;
  6976. }
  6977. };
  6978. VertexBuffer.prototype.update = function (data) {
  6979. this.create(data);
  6980. };
  6981. VertexBuffer.prototype.dispose = function () {
  6982. if (!this._buffer) {
  6983. return;
  6984. }
  6985. if (this._engine._releaseBuffer(this._buffer)) {
  6986. this._buffer = null;
  6987. }
  6988. };
  6989. Object.defineProperty(VertexBuffer, "PositionKind", {
  6990. get: function () {
  6991. return VertexBuffer._PositionKind;
  6992. },
  6993. enumerable: true,
  6994. configurable: true
  6995. });
  6996. Object.defineProperty(VertexBuffer, "NormalKind", {
  6997. get: function () {
  6998. return VertexBuffer._NormalKind;
  6999. },
  7000. enumerable: true,
  7001. configurable: true
  7002. });
  7003. Object.defineProperty(VertexBuffer, "UVKind", {
  7004. get: function () {
  7005. return VertexBuffer._UVKind;
  7006. },
  7007. enumerable: true,
  7008. configurable: true
  7009. });
  7010. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7011. get: function () {
  7012. return VertexBuffer._UV2Kind;
  7013. },
  7014. enumerable: true,
  7015. configurable: true
  7016. });
  7017. Object.defineProperty(VertexBuffer, "ColorKind", {
  7018. get: function () {
  7019. return VertexBuffer._ColorKind;
  7020. },
  7021. enumerable: true,
  7022. configurable: true
  7023. });
  7024. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7025. get: function () {
  7026. return VertexBuffer._MatricesIndicesKind;
  7027. },
  7028. enumerable: true,
  7029. configurable: true
  7030. });
  7031. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7032. get: function () {
  7033. return VertexBuffer._MatricesWeightsKind;
  7034. },
  7035. enumerable: true,
  7036. configurable: true
  7037. });
  7038. VertexBuffer._PositionKind = "position";
  7039. VertexBuffer._NormalKind = "normal";
  7040. VertexBuffer._UVKind = "uv";
  7041. VertexBuffer._UV2Kind = "uv2";
  7042. VertexBuffer._ColorKind = "color";
  7043. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7044. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7045. return VertexBuffer;
  7046. })();
  7047. BABYLON.VertexBuffer = VertexBuffer;
  7048. })(BABYLON || (BABYLON = {}));
  7049. var __extends = this.__extends || function (d, b) {
  7050. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7051. function __() { this.constructor = d; }
  7052. __.prototype = b.prototype;
  7053. d.prototype = new __();
  7054. };
  7055. var BABYLON;
  7056. (function (BABYLON) {
  7057. var AbstractMesh = (function (_super) {
  7058. __extends(AbstractMesh, _super);
  7059. function AbstractMesh(name, scene) {
  7060. _super.call(this, name, scene);
  7061. this.position = new BABYLON.Vector3(0, 0, 0);
  7062. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7063. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7064. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7065. this.visibility = 1.0;
  7066. this.infiniteDistance = false;
  7067. this.isVisible = true;
  7068. this.isPickable = true;
  7069. this.showBoundingBox = false;
  7070. this.showSubMeshesBoundingBox = false;
  7071. this.onDispose = null;
  7072. this.checkCollisions = false;
  7073. this.isBlocker = false;
  7074. this.renderingGroupId = 0;
  7075. this.receiveShadows = false;
  7076. this.renderOutline = false;
  7077. this.outlineColor = BABYLON.Color3.Red();
  7078. this.outlineWidth = 0.02;
  7079. this.useOctreeForRenderingSelection = true;
  7080. this.useOctreeForPicking = true;
  7081. this.useOctreeForCollisions = true;
  7082. this.layerMask = 0xFFFFFFFF;
  7083. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7084. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7085. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7086. this._collider = new BABYLON.Collider();
  7087. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7088. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7089. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7090. this._localScaling = BABYLON.Matrix.Zero();
  7091. this._localRotation = BABYLON.Matrix.Zero();
  7092. this._localTranslation = BABYLON.Matrix.Zero();
  7093. this._localBillboard = BABYLON.Matrix.Zero();
  7094. this._localPivotScaling = BABYLON.Matrix.Zero();
  7095. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7096. this._localWorld = BABYLON.Matrix.Zero();
  7097. this._worldMatrix = BABYLON.Matrix.Zero();
  7098. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7099. this._absolutePosition = BABYLON.Vector3.Zero();
  7100. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7101. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7102. this._isDirty = false;
  7103. this._pivotMatrix = BABYLON.Matrix.Identity();
  7104. this._isDisposed = false;
  7105. this._renderId = 0;
  7106. this._intersectionsInProgress = new Array();
  7107. scene.meshes.push(this);
  7108. }
  7109. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7110. get: function () {
  7111. return AbstractMesh._BILLBOARDMODE_NONE;
  7112. },
  7113. enumerable: true,
  7114. configurable: true
  7115. });
  7116. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7117. get: function () {
  7118. return AbstractMesh._BILLBOARDMODE_X;
  7119. },
  7120. enumerable: true,
  7121. configurable: true
  7122. });
  7123. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7124. get: function () {
  7125. return AbstractMesh._BILLBOARDMODE_Y;
  7126. },
  7127. enumerable: true,
  7128. configurable: true
  7129. });
  7130. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7131. get: function () {
  7132. return AbstractMesh._BILLBOARDMODE_Z;
  7133. },
  7134. enumerable: true,
  7135. configurable: true
  7136. });
  7137. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7138. get: function () {
  7139. return AbstractMesh._BILLBOARDMODE_ALL;
  7140. },
  7141. enumerable: true,
  7142. configurable: true
  7143. });
  7144. AbstractMesh.prototype.getTotalVertices = function () {
  7145. return 0;
  7146. };
  7147. AbstractMesh.prototype.getIndices = function () {
  7148. return null;
  7149. };
  7150. AbstractMesh.prototype.getVerticesData = function (kind) {
  7151. return null;
  7152. };
  7153. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7154. return false;
  7155. };
  7156. AbstractMesh.prototype.getBoundingInfo = function () {
  7157. if (!this._boundingInfo) {
  7158. this._updateBoundingInfo();
  7159. }
  7160. return this._boundingInfo;
  7161. };
  7162. AbstractMesh.prototype._preActivate = function () {
  7163. };
  7164. AbstractMesh.prototype._activate = function (renderId) {
  7165. this._renderId = renderId;
  7166. };
  7167. AbstractMesh.prototype.getWorldMatrix = function () {
  7168. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7169. this.computeWorldMatrix();
  7170. }
  7171. return this._worldMatrix;
  7172. };
  7173. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7174. get: function () {
  7175. return this._worldMatrix;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7181. get: function () {
  7182. return this._absolutePosition;
  7183. },
  7184. enumerable: true,
  7185. configurable: true
  7186. });
  7187. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7188. if (!this.rotationQuaternion) {
  7189. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7190. this.rotation = BABYLON.Vector3.Zero();
  7191. }
  7192. if (!space || space == 0 /* LOCAL */) {
  7193. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7194. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7195. } else {
  7196. if (this.parent) {
  7197. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7198. invertParentWorldMatrix.invert();
  7199. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7200. }
  7201. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7202. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7203. }
  7204. };
  7205. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7206. var displacementVector = axis.scale(distance);
  7207. if (!space || space == 0 /* LOCAL */) {
  7208. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7209. this.setPositionWithLocalVector(tempV3);
  7210. } else {
  7211. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7212. }
  7213. };
  7214. AbstractMesh.prototype.getAbsolutePosition = function () {
  7215. this.computeWorldMatrix();
  7216. return this._absolutePosition;
  7217. };
  7218. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7219. if (!absolutePosition) {
  7220. return;
  7221. }
  7222. var absolutePositionX;
  7223. var absolutePositionY;
  7224. var absolutePositionZ;
  7225. if (absolutePosition.x === undefined) {
  7226. if (arguments.length < 3) {
  7227. return;
  7228. }
  7229. absolutePositionX = arguments[0];
  7230. absolutePositionY = arguments[1];
  7231. absolutePositionZ = arguments[2];
  7232. } else {
  7233. absolutePositionX = absolutePosition.x;
  7234. absolutePositionY = absolutePosition.y;
  7235. absolutePositionZ = absolutePosition.z;
  7236. }
  7237. if (this.parent) {
  7238. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7239. invertParentWorldMatrix.invert();
  7240. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7241. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7242. } else {
  7243. this.position.x = absolutePositionX;
  7244. this.position.y = absolutePositionY;
  7245. this.position.z = absolutePositionZ;
  7246. }
  7247. };
  7248. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7249. this._pivotMatrix = matrix;
  7250. this._cache.pivotMatrixUpdated = true;
  7251. };
  7252. AbstractMesh.prototype.getPivotMatrix = function () {
  7253. return this._pivotMatrix;
  7254. };
  7255. AbstractMesh.prototype._isSynchronized = function () {
  7256. if (this._isDirty) {
  7257. return false;
  7258. }
  7259. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7260. return false;
  7261. if (this._cache.pivotMatrixUpdated) {
  7262. return false;
  7263. }
  7264. if (this.infiniteDistance) {
  7265. return false;
  7266. }
  7267. if (!this._cache.position.equals(this.position))
  7268. return false;
  7269. if (this.rotationQuaternion) {
  7270. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7271. return false;
  7272. } else {
  7273. if (!this._cache.rotation.equals(this.rotation))
  7274. return false;
  7275. }
  7276. if (!this._cache.scaling.equals(this.scaling))
  7277. return false;
  7278. return true;
  7279. };
  7280. AbstractMesh.prototype._initCache = function () {
  7281. _super.prototype._initCache.call(this);
  7282. this._cache.localMatrixUpdated = false;
  7283. this._cache.position = BABYLON.Vector3.Zero();
  7284. this._cache.scaling = BABYLON.Vector3.Zero();
  7285. this._cache.rotation = BABYLON.Vector3.Zero();
  7286. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7287. };
  7288. AbstractMesh.prototype.markAsDirty = function (property) {
  7289. if (property === "rotation") {
  7290. this.rotationQuaternion = null;
  7291. }
  7292. this._currentRenderId = Number.MAX_VALUE;
  7293. this._isDirty = true;
  7294. };
  7295. AbstractMesh.prototype._updateBoundingInfo = function () {
  7296. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7297. this._boundingInfo._update(this.worldMatrixFromCache);
  7298. if (!this.subMeshes) {
  7299. return;
  7300. }
  7301. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7302. var subMesh = this.subMeshes[subIndex];
  7303. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7304. }
  7305. };
  7306. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7307. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7308. return this._worldMatrix;
  7309. }
  7310. this._cache.position.copyFrom(this.position);
  7311. this._cache.scaling.copyFrom(this.scaling);
  7312. this._cache.pivotMatrixUpdated = false;
  7313. this._currentRenderId = this.getScene().getRenderId();
  7314. this._isDirty = false;
  7315. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7316. if (this.rotationQuaternion) {
  7317. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7318. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7319. } else {
  7320. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7321. this._cache.rotation.copyFrom(this.rotation);
  7322. }
  7323. if (this.infiniteDistance && !this.parent) {
  7324. var camera = this.getScene().activeCamera;
  7325. var cameraWorldMatrix = camera.getWorldMatrix();
  7326. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7327. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7328. } else {
  7329. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7330. }
  7331. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7332. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7333. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7334. var localPosition = this.position.clone();
  7335. var zero = this.getScene().activeCamera.position.clone();
  7336. if (this.parent && this.parent.position) {
  7337. localPosition.addInPlace(this.parent.position);
  7338. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7339. }
  7340. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7341. zero = this.getScene().activeCamera.position;
  7342. } else {
  7343. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7344. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7345. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7346. zero.y = localPosition.y + 0.001;
  7347. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7348. zero.z = localPosition.z + 0.001;
  7349. }
  7350. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7351. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7352. this._localBillboard.invert();
  7353. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7354. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7355. }
  7356. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7357. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7358. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7359. } else {
  7360. this._worldMatrix.copyFrom(this._localWorld);
  7361. }
  7362. this._updateBoundingInfo();
  7363. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7364. return this._worldMatrix;
  7365. };
  7366. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7367. this.computeWorldMatrix();
  7368. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7369. };
  7370. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7371. this.computeWorldMatrix();
  7372. var invLocalWorldMatrix = this._localWorld.clone();
  7373. invLocalWorldMatrix.invert();
  7374. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7375. };
  7376. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7377. this.computeWorldMatrix();
  7378. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7379. };
  7380. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7381. yawCor = yawCor || 0;
  7382. pitchCor = pitchCor || 0;
  7383. rollCor = rollCor || 0;
  7384. var dv = targetPoint.subtract(this.position);
  7385. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7386. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7387. var pitch = Math.atan2(dv.y, len);
  7388. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7389. };
  7390. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7391. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7392. return false;
  7393. }
  7394. return true;
  7395. };
  7396. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7397. if (!this._boundingInfo || !mesh._boundingInfo) {
  7398. return false;
  7399. }
  7400. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7401. };
  7402. AbstractMesh.prototype.intersectsPoint = function (point) {
  7403. if (!this._boundingInfo) {
  7404. return false;
  7405. }
  7406. return this._boundingInfo.intersectsPoint(point);
  7407. };
  7408. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7409. var physicsEngine = this.getScene().getPhysicsEngine();
  7410. if (!physicsEngine) {
  7411. return;
  7412. }
  7413. if (impostor.impostor) {
  7414. options = impostor;
  7415. impostor = impostor.impostor;
  7416. }
  7417. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7418. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7419. physicsEngine._unregisterMesh(this);
  7420. return;
  7421. }
  7422. options.mass = options.mass || 0;
  7423. options.friction = options.friction || 0.2;
  7424. options.restitution = options.restitution || 0.9;
  7425. this._physicImpostor = impostor;
  7426. this._physicsMass = options.mass;
  7427. this._physicsFriction = options.friction;
  7428. this._physicRestitution = options.restitution;
  7429. physicsEngine._registerMesh(this, impostor, options);
  7430. };
  7431. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7432. if (!this._physicImpostor) {
  7433. return BABYLON.PhysicsEngine.NoImpostor;
  7434. }
  7435. return this._physicImpostor;
  7436. };
  7437. AbstractMesh.prototype.getPhysicsMass = function () {
  7438. if (!this._physicsMass) {
  7439. return 0;
  7440. }
  7441. return this._physicsMass;
  7442. };
  7443. AbstractMesh.prototype.getPhysicsFriction = function () {
  7444. if (!this._physicsFriction) {
  7445. return 0;
  7446. }
  7447. return this._physicsFriction;
  7448. };
  7449. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7450. if (!this._physicRestitution) {
  7451. return 0;
  7452. }
  7453. return this._physicRestitution;
  7454. };
  7455. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7456. if (!this._physicImpostor) {
  7457. return;
  7458. }
  7459. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7460. };
  7461. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7462. if (!this._physicImpostor) {
  7463. return;
  7464. }
  7465. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7466. };
  7467. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7468. if (!this._physicImpostor) {
  7469. return;
  7470. }
  7471. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7472. };
  7473. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7474. var globalPosition = this.getAbsolutePosition();
  7475. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7476. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7477. this._collider.radius = this.ellipsoid;
  7478. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7479. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7480. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7481. this.position.addInPlace(this._diffPositionForCollisions);
  7482. }
  7483. };
  7484. /**
  7485. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7486. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7487. */
  7488. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7489. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7490. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7491. if (!this._submeshesOctree) {
  7492. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7493. }
  7494. this.computeWorldMatrix(true);
  7495. var bbox = this.getBoundingInfo().boundingBox;
  7496. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7497. return this._submeshesOctree;
  7498. };
  7499. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7500. this._generatePointsArray();
  7501. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7502. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7503. subMesh._lastColliderWorldVertices = [];
  7504. subMesh._trianglePlanes = [];
  7505. var start = subMesh.verticesStart;
  7506. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7507. for (var i = start; i < end; i++) {
  7508. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7509. }
  7510. }
  7511. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7512. };
  7513. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7514. var subMeshes;
  7515. var len;
  7516. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7517. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7518. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7519. len = intersections.length;
  7520. subMeshes = intersections.data;
  7521. } else {
  7522. subMeshes = this.subMeshes;
  7523. len = subMeshes.length;
  7524. }
  7525. for (var index = 0; index < len; index++) {
  7526. var subMesh = subMeshes[index];
  7527. if (len > 1 && !subMesh._checkCollision(collider))
  7528. continue;
  7529. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7530. }
  7531. };
  7532. AbstractMesh.prototype._checkCollision = function (collider) {
  7533. if (!this._boundingInfo._checkCollision(collider))
  7534. return;
  7535. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7536. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7537. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7538. };
  7539. AbstractMesh.prototype._generatePointsArray = function () {
  7540. return false;
  7541. };
  7542. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7543. var pickingInfo = new BABYLON.PickingInfo();
  7544. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7545. return pickingInfo;
  7546. }
  7547. if (!this._generatePointsArray()) {
  7548. return pickingInfo;
  7549. }
  7550. var intersectInfo = null;
  7551. var subMeshes;
  7552. var len;
  7553. if (this._submeshesOctree && this.useOctreeForPicking) {
  7554. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7555. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7556. len = intersections.length;
  7557. subMeshes = intersections.data;
  7558. } else {
  7559. subMeshes = this.subMeshes;
  7560. len = subMeshes.length;
  7561. }
  7562. for (var index = 0; index < len; index++) {
  7563. var subMesh = subMeshes[index];
  7564. if (len > 1 && !subMesh.canIntersects(ray))
  7565. continue;
  7566. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7567. if (currentIntersectInfo) {
  7568. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7569. intersectInfo = currentIntersectInfo;
  7570. if (fastCheck) {
  7571. break;
  7572. }
  7573. }
  7574. }
  7575. }
  7576. if (intersectInfo) {
  7577. var world = this.getWorldMatrix();
  7578. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7579. var direction = ray.direction.clone();
  7580. direction.normalize();
  7581. direction = direction.scale(intersectInfo.distance);
  7582. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7583. var pickedPoint = worldOrigin.add(worldDirection);
  7584. pickingInfo.hit = true;
  7585. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7586. pickingInfo.pickedPoint = pickedPoint;
  7587. pickingInfo.pickedMesh = this;
  7588. pickingInfo.bu = intersectInfo.bu;
  7589. pickingInfo.bv = intersectInfo.bv;
  7590. pickingInfo.faceId = intersectInfo.faceId;
  7591. return pickingInfo;
  7592. }
  7593. return pickingInfo;
  7594. };
  7595. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7596. return null;
  7597. };
  7598. AbstractMesh.prototype.releaseSubMeshes = function () {
  7599. if (this.subMeshes) {
  7600. while (this.subMeshes.length) {
  7601. this.subMeshes[0].dispose();
  7602. }
  7603. } else {
  7604. this.subMeshes = new Array();
  7605. }
  7606. };
  7607. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7608. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7609. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7610. }
  7611. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7612. var other = this._intersectionsInProgress[index];
  7613. var pos = other._intersectionsInProgress.indexOf(this);
  7614. other._intersectionsInProgress.splice(pos, 1);
  7615. }
  7616. this._intersectionsInProgress = [];
  7617. this.releaseSubMeshes();
  7618. var index = this.getScene().meshes.indexOf(this);
  7619. if (index != -1) {
  7620. this.getScene().meshes.splice(index, 1);
  7621. }
  7622. if (!doNotRecurse) {
  7623. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7624. if (this.getScene().particleSystems[index].emitter == this) {
  7625. this.getScene().particleSystems[index].dispose();
  7626. index--;
  7627. }
  7628. }
  7629. var objects = this.getScene().meshes.slice(0);
  7630. for (index = 0; index < objects.length; index++) {
  7631. if (objects[index].parent == this) {
  7632. objects[index].dispose();
  7633. }
  7634. }
  7635. } else {
  7636. for (index = 0; index < this.getScene().meshes.length; index++) {
  7637. var obj = this.getScene().meshes[index];
  7638. if (obj.parent === this) {
  7639. obj.parent = null;
  7640. obj.computeWorldMatrix(true);
  7641. }
  7642. }
  7643. }
  7644. this._isDisposed = true;
  7645. if (this.onDispose) {
  7646. this.onDispose();
  7647. }
  7648. };
  7649. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7650. AbstractMesh._BILLBOARDMODE_X = 1;
  7651. AbstractMesh._BILLBOARDMODE_Y = 2;
  7652. AbstractMesh._BILLBOARDMODE_Z = 4;
  7653. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7654. return AbstractMesh;
  7655. })(BABYLON.Node);
  7656. BABYLON.AbstractMesh = AbstractMesh;
  7657. })(BABYLON || (BABYLON = {}));
  7658. var __extends = this.__extends || function (d, b) {
  7659. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7660. function __() { this.constructor = d; }
  7661. __.prototype = b.prototype;
  7662. d.prototype = new __();
  7663. };
  7664. var BABYLON;
  7665. (function (BABYLON) {
  7666. var _InstancesBatch = (function () {
  7667. function _InstancesBatch() {
  7668. this.mustReturn = false;
  7669. this.visibleInstances = new Array();
  7670. this.renderSelf = new Array();
  7671. }
  7672. return _InstancesBatch;
  7673. })();
  7674. BABYLON._InstancesBatch = _InstancesBatch;
  7675. var Mesh = (function (_super) {
  7676. __extends(Mesh, _super);
  7677. function Mesh(name, scene) {
  7678. _super.call(this, name, scene);
  7679. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7680. this.instances = new Array();
  7681. this._onBeforeRenderCallbacks = new Array();
  7682. this._onAfterRenderCallbacks = new Array();
  7683. this._visibleInstances = {};
  7684. this._renderIdForInstances = new Array();
  7685. this._batchCache = new _InstancesBatch();
  7686. this._instancesBufferSize = 32 * 16 * 4;
  7687. }
  7688. Mesh.prototype.getTotalVertices = function () {
  7689. if (!this._geometry) {
  7690. return 0;
  7691. }
  7692. return this._geometry.getTotalVertices();
  7693. };
  7694. Mesh.prototype.getVerticesData = function (kind) {
  7695. if (!this._geometry) {
  7696. return null;
  7697. }
  7698. return this._geometry.getVerticesData(kind);
  7699. };
  7700. Mesh.prototype.getVertexBuffer = function (kind) {
  7701. if (!this._geometry) {
  7702. return undefined;
  7703. }
  7704. return this._geometry.getVertexBuffer(kind);
  7705. };
  7706. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7707. if (!this._geometry) {
  7708. if (this._delayInfo) {
  7709. return this._delayInfo.indexOf(kind) !== -1;
  7710. }
  7711. return false;
  7712. }
  7713. return this._geometry.isVerticesDataPresent(kind);
  7714. };
  7715. Mesh.prototype.getVerticesDataKinds = function () {
  7716. if (!this._geometry) {
  7717. var result = [];
  7718. if (this._delayInfo) {
  7719. for (var kind in this._delayInfo) {
  7720. result.push(kind);
  7721. }
  7722. }
  7723. return result;
  7724. }
  7725. return this._geometry.getVerticesDataKinds();
  7726. };
  7727. Mesh.prototype.getTotalIndices = function () {
  7728. if (!this._geometry) {
  7729. return 0;
  7730. }
  7731. return this._geometry.getTotalIndices();
  7732. };
  7733. Mesh.prototype.getIndices = function () {
  7734. if (!this._geometry) {
  7735. return [];
  7736. }
  7737. return this._geometry.getIndices();
  7738. };
  7739. Mesh.prototype.isReady = function () {
  7740. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7741. return false;
  7742. }
  7743. return _super.prototype.isReady.call(this);
  7744. };
  7745. Mesh.prototype.isDisposed = function () {
  7746. return this._isDisposed;
  7747. };
  7748. Mesh.prototype._preActivate = function () {
  7749. var sceneRenderId = this.getScene().getRenderId();
  7750. if (this._preActivateId == sceneRenderId) {
  7751. return;
  7752. }
  7753. this._preActivateId = sceneRenderId;
  7754. this._visibleInstances = null;
  7755. };
  7756. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7757. if (!this._visibleInstances) {
  7758. this._visibleInstances = {};
  7759. this._visibleInstances.defaultRenderId = renderId;
  7760. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7761. }
  7762. if (!this._visibleInstances[renderId]) {
  7763. this._visibleInstances[renderId] = new Array();
  7764. }
  7765. this._visibleInstances[renderId].push(instance);
  7766. };
  7767. Mesh.prototype.refreshBoundingInfo = function () {
  7768. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7769. if (data) {
  7770. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7771. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7772. }
  7773. if (this.subMeshes) {
  7774. for (var index = 0; index < this.subMeshes.length; index++) {
  7775. this.subMeshes[index].refreshBoundingInfo();
  7776. }
  7777. }
  7778. this._updateBoundingInfo();
  7779. };
  7780. Mesh.prototype._createGlobalSubMesh = function () {
  7781. var totalVertices = this.getTotalVertices();
  7782. if (!totalVertices || !this.getIndices()) {
  7783. return null;
  7784. }
  7785. this.releaseSubMeshes();
  7786. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7787. };
  7788. Mesh.prototype.subdivide = function (count) {
  7789. if (count < 1) {
  7790. return;
  7791. }
  7792. var totalIndices = this.getTotalIndices();
  7793. var subdivisionSize = (totalIndices / count) | 0;
  7794. var offset = 0;
  7795. while (subdivisionSize % 3 != 0) {
  7796. subdivisionSize++;
  7797. }
  7798. this.releaseSubMeshes();
  7799. for (var index = 0; index < count; index++) {
  7800. if (offset >= totalIndices) {
  7801. break;
  7802. }
  7803. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7804. offset += subdivisionSize;
  7805. }
  7806. this.synchronizeInstances();
  7807. };
  7808. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7809. if (kind instanceof Array) {
  7810. var temp = data;
  7811. data = kind;
  7812. kind = temp;
  7813. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7814. }
  7815. if (!this._geometry) {
  7816. var vertexData = new BABYLON.VertexData();
  7817. vertexData.set(data, kind);
  7818. var scene = this.getScene();
  7819. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7820. } else {
  7821. this._geometry.setVerticesData(kind, data, updatable);
  7822. }
  7823. };
  7824. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7825. if (!this._geometry) {
  7826. return;
  7827. }
  7828. if (!makeItUnique) {
  7829. this._geometry.updateVerticesData(kind, data, updateExtends);
  7830. } else {
  7831. this.makeGeometryUnique();
  7832. this.updateVerticesData(kind, data, updateExtends, false);
  7833. }
  7834. };
  7835. Mesh.prototype.makeGeometryUnique = function () {
  7836. if (!this._geometry) {
  7837. return;
  7838. }
  7839. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7840. geometry.applyToMesh(this);
  7841. };
  7842. Mesh.prototype.setIndices = function (indices) {
  7843. if (!this._geometry) {
  7844. var vertexData = new BABYLON.VertexData();
  7845. vertexData.indices = indices;
  7846. var scene = this.getScene();
  7847. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7848. } else {
  7849. this._geometry.setIndices(indices);
  7850. }
  7851. };
  7852. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7853. var engine = this.getScene().getEngine();
  7854. var indexToBind = this._geometry.getIndexBuffer();
  7855. if (wireframe) {
  7856. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7857. }
  7858. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7859. };
  7860. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7861. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7862. return;
  7863. }
  7864. var engine = this.getScene().getEngine();
  7865. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7866. };
  7867. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7868. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7869. return;
  7870. }
  7871. var engine = this.getScene().getEngine();
  7872. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7873. };
  7874. Mesh.prototype.registerBeforeRender = function (func) {
  7875. this._onBeforeRenderCallbacks.push(func);
  7876. };
  7877. Mesh.prototype.unregisterBeforeRender = function (func) {
  7878. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7879. if (index > -1) {
  7880. this._onBeforeRenderCallbacks.splice(index, 1);
  7881. }
  7882. };
  7883. Mesh.prototype.registerAfterRender = function (func) {
  7884. this._onAfterRenderCallbacks.push(func);
  7885. };
  7886. Mesh.prototype.unregisterAfterRender = function (func) {
  7887. var index = this._onAfterRenderCallbacks.indexOf(func);
  7888. if (index > -1) {
  7889. this._onAfterRenderCallbacks.splice(index, 1);
  7890. }
  7891. };
  7892. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7893. var scene = this.getScene();
  7894. this._batchCache.mustReturn = false;
  7895. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7896. this._batchCache.visibleInstances[subMeshId] = null;
  7897. if (this._visibleInstances) {
  7898. var currentRenderId = scene.getRenderId();
  7899. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  7900. var selfRenderId = this._renderId;
  7901. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  7902. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  7903. currentRenderId = this._visibleInstances.defaultRenderId;
  7904. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  7905. }
  7906. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  7907. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  7908. this._batchCache.mustReturn = true;
  7909. return this._batchCache;
  7910. }
  7911. if (currentRenderId !== selfRenderId) {
  7912. this._batchCache.renderSelf[subMeshId] = false;
  7913. }
  7914. }
  7915. this._renderIdForInstances[subMeshId] = currentRenderId;
  7916. }
  7917. return this._batchCache;
  7918. };
  7919. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  7920. var matricesCount = this.instances.length + 1;
  7921. var bufferSize = matricesCount * 16 * 4;
  7922. while (this._instancesBufferSize < bufferSize) {
  7923. this._instancesBufferSize *= 2;
  7924. }
  7925. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  7926. if (this._worldMatricesInstancesBuffer) {
  7927. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  7928. }
  7929. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  7930. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  7931. }
  7932. var offset = 0;
  7933. var instancesCount = 0;
  7934. var world = this.getWorldMatrix();
  7935. if (batch.renderSelf[subMesh._id]) {
  7936. world.copyToArray(this._worldMatricesInstancesArray, offset);
  7937. offset += 16;
  7938. instancesCount++;
  7939. }
  7940. var visibleInstances = batch.visibleInstances[subMesh._id];
  7941. if (visibleInstances) {
  7942. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  7943. var instance = visibleInstances[instanceIndex];
  7944. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  7945. offset += 16;
  7946. instancesCount++;
  7947. }
  7948. }
  7949. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  7950. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  7951. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  7952. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  7953. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  7954. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  7955. this._draw(subMesh, !wireFrame, instancesCount);
  7956. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  7957. };
  7958. Mesh.prototype.render = function (subMesh) {
  7959. var scene = this.getScene();
  7960. var batch = this._getInstancesRenderList(subMesh._id);
  7961. if (batch.mustReturn) {
  7962. return;
  7963. }
  7964. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7965. return;
  7966. }
  7967. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7968. this._onBeforeRenderCallbacks[callbackIndex]();
  7969. }
  7970. var engine = scene.getEngine();
  7971. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  7972. var effectiveMaterial = subMesh.getMaterial();
  7973. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  7974. return;
  7975. }
  7976. var savedDepthWrite = engine.getDepthWrite();
  7977. if (this.renderOutline) {
  7978. engine.setDepthWrite(false);
  7979. scene.getOutlineRenderer().render(subMesh, batch);
  7980. }
  7981. effectiveMaterial._preBind();
  7982. var effect = effectiveMaterial.getEffect();
  7983. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  7984. this._bind(subMesh, effect, wireFrame);
  7985. var world = this.getWorldMatrix();
  7986. effectiveMaterial.bind(world, this);
  7987. if (hardwareInstancedRendering) {
  7988. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  7989. } else {
  7990. if (batch.renderSelf[subMesh._id]) {
  7991. this._draw(subMesh, !wireFrame);
  7992. }
  7993. if (batch.visibleInstances[subMesh._id]) {
  7994. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  7995. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  7996. world = instance.getWorldMatrix();
  7997. effectiveMaterial.bindOnlyWorldMatrix(world);
  7998. this._draw(subMesh, !wireFrame);
  7999. }
  8000. }
  8001. }
  8002. effectiveMaterial.unbind();
  8003. if (this.renderOutline && savedDepthWrite) {
  8004. engine.setDepthWrite(true);
  8005. engine.setColorWrite(false);
  8006. scene.getOutlineRenderer().render(subMesh, batch);
  8007. engine.setColorWrite(true);
  8008. }
  8009. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8010. this._onAfterRenderCallbacks[callbackIndex]();
  8011. }
  8012. };
  8013. Mesh.prototype.getEmittedParticleSystems = function () {
  8014. var results = new Array();
  8015. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8016. var particleSystem = this.getScene().particleSystems[index];
  8017. if (particleSystem.emitter === this) {
  8018. results.push(particleSystem);
  8019. }
  8020. }
  8021. return results;
  8022. };
  8023. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8024. var results = new Array();
  8025. var descendants = this.getDescendants();
  8026. descendants.push(this);
  8027. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8028. var particleSystem = this.getScene().particleSystems[index];
  8029. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8030. results.push(particleSystem);
  8031. }
  8032. }
  8033. return results;
  8034. };
  8035. Mesh.prototype.getChildren = function () {
  8036. var results = [];
  8037. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8038. var mesh = this.getScene().meshes[index];
  8039. if (mesh.parent == this) {
  8040. results.push(mesh);
  8041. }
  8042. }
  8043. return results;
  8044. };
  8045. Mesh.prototype._checkDelayState = function () {
  8046. var _this = this;
  8047. var that = this;
  8048. var scene = this.getScene();
  8049. if (this._geometry) {
  8050. this._geometry.load(scene);
  8051. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8052. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8053. scene._addPendingData(that);
  8054. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8055. _this._delayLoadingFunction(JSON.parse(data), _this);
  8056. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8057. scene._removePendingData(_this);
  8058. }, function () {
  8059. }, scene.database);
  8060. }
  8061. };
  8062. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8063. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8064. return false;
  8065. }
  8066. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8067. return false;
  8068. }
  8069. this._checkDelayState();
  8070. return true;
  8071. };
  8072. Mesh.prototype.setMaterialByID = function (id) {
  8073. var materials = this.getScene().materials;
  8074. for (var index = 0; index < materials.length; index++) {
  8075. if (materials[index].id == id) {
  8076. this.material = materials[index];
  8077. return;
  8078. }
  8079. }
  8080. var multiMaterials = this.getScene().multiMaterials;
  8081. for (index = 0; index < multiMaterials.length; index++) {
  8082. if (multiMaterials[index].id == id) {
  8083. this.material = multiMaterials[index];
  8084. return;
  8085. }
  8086. }
  8087. };
  8088. Mesh.prototype.getAnimatables = function () {
  8089. var results = [];
  8090. if (this.material) {
  8091. results.push(this.material);
  8092. }
  8093. return results;
  8094. };
  8095. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8096. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8097. return;
  8098. }
  8099. this._resetPointsArrayCache();
  8100. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8101. var temp = [];
  8102. for (var index = 0; index < data.length; index += 3) {
  8103. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8104. }
  8105. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8106. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8107. return;
  8108. }
  8109. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8110. for (index = 0; index < data.length; index += 3) {
  8111. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8112. }
  8113. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8114. };
  8115. Mesh.prototype._resetPointsArrayCache = function () {
  8116. this._positions = null;
  8117. };
  8118. Mesh.prototype._generatePointsArray = function () {
  8119. if (this._positions)
  8120. return true;
  8121. this._positions = [];
  8122. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8123. if (!data) {
  8124. return false;
  8125. }
  8126. for (var index = 0; index < data.length; index += 3) {
  8127. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8128. }
  8129. return true;
  8130. };
  8131. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8132. var result = new BABYLON.Mesh(name, this.getScene());
  8133. this._geometry.applyToMesh(result);
  8134. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8135. result.material = this.material;
  8136. if (newParent) {
  8137. result.parent = newParent;
  8138. }
  8139. if (!doNotCloneChildren) {
  8140. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8141. var mesh = this.getScene().meshes[index];
  8142. if (mesh.parent == this) {
  8143. mesh.clone(mesh.name, result);
  8144. }
  8145. }
  8146. }
  8147. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8148. var system = this.getScene().particleSystems[index];
  8149. if (system.emitter == this) {
  8150. system.clone(system.name, result);
  8151. }
  8152. }
  8153. result.computeWorldMatrix(true);
  8154. return result;
  8155. };
  8156. Mesh.prototype.dispose = function (doNotRecurse) {
  8157. if (this._geometry) {
  8158. this._geometry.releaseForMesh(this, true);
  8159. }
  8160. if (this._worldMatricesInstancesBuffer) {
  8161. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8162. this._worldMatricesInstancesBuffer = null;
  8163. }
  8164. while (this.instances.length) {
  8165. this.instances[0].dispose();
  8166. }
  8167. _super.prototype.dispose.call(this, doNotRecurse);
  8168. };
  8169. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8170. var _this = this;
  8171. var scene = this.getScene();
  8172. var onload = function (img) {
  8173. var canvas = document.createElement("canvas");
  8174. var context = canvas.getContext("2d");
  8175. var heightMapWidth = img.width;
  8176. var heightMapHeight = img.height;
  8177. canvas.width = heightMapWidth;
  8178. canvas.height = heightMapHeight;
  8179. context.drawImage(img, 0, 0);
  8180. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8181. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8182. };
  8183. BABYLON.Tools.LoadImage(url, onload, function () {
  8184. }, scene.database);
  8185. };
  8186. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8187. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8188. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8189. return;
  8190. }
  8191. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8192. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8193. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8194. var position = BABYLON.Vector3.Zero();
  8195. var normal = BABYLON.Vector3.Zero();
  8196. var uv = BABYLON.Vector2.Zero();
  8197. for (var index = 0; index < positions.length; index += 3) {
  8198. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8199. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8200. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8201. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8202. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8203. var pos = (u + v * heightMapWidth) * 4;
  8204. var r = buffer[pos] / 255.0;
  8205. var g = buffer[pos + 1] / 255.0;
  8206. var b = buffer[pos + 2] / 255.0;
  8207. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8208. normal.normalize();
  8209. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8210. position = position.add(normal);
  8211. position.toArray(positions, index);
  8212. }
  8213. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8214. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8215. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8216. };
  8217. Mesh.prototype.convertToFlatShadedMesh = function () {
  8218. var kinds = this.getVerticesDataKinds();
  8219. var vbs = [];
  8220. var data = [];
  8221. var newdata = [];
  8222. var updatableNormals = false;
  8223. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8224. var kind = kinds[kindIndex];
  8225. var vertexBuffer = this.getVertexBuffer(kind);
  8226. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8227. updatableNormals = vertexBuffer.isUpdatable();
  8228. kinds.splice(kindIndex, 1);
  8229. kindIndex--;
  8230. continue;
  8231. }
  8232. vbs[kind] = vertexBuffer;
  8233. data[kind] = vbs[kind].getData();
  8234. newdata[kind] = [];
  8235. }
  8236. var previousSubmeshes = this.subMeshes.slice(0);
  8237. var indices = this.getIndices();
  8238. var totalIndices = this.getTotalIndices();
  8239. for (index = 0; index < totalIndices; index++) {
  8240. var vertexIndex = indices[index];
  8241. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8242. kind = kinds[kindIndex];
  8243. var stride = vbs[kind].getStrideSize();
  8244. for (var offset = 0; offset < stride; offset++) {
  8245. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8246. }
  8247. }
  8248. }
  8249. var normals = [];
  8250. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8251. for (var index = 0; index < totalIndices; index += 3) {
  8252. indices[index] = index;
  8253. indices[index + 1] = index + 1;
  8254. indices[index + 2] = index + 2;
  8255. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8256. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8257. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8258. var p1p2 = p1.subtract(p2);
  8259. var p3p2 = p3.subtract(p2);
  8260. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8261. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8262. normals.push(normal.x);
  8263. normals.push(normal.y);
  8264. normals.push(normal.z);
  8265. }
  8266. }
  8267. this.setIndices(indices);
  8268. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8269. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8270. kind = kinds[kindIndex];
  8271. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8272. }
  8273. this.releaseSubMeshes();
  8274. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8275. var previousOne = previousSubmeshes[submeshIndex];
  8276. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8277. }
  8278. this.synchronizeInstances();
  8279. };
  8280. Mesh.prototype.createInstance = function (name) {
  8281. return new BABYLON.InstancedMesh(name, this);
  8282. };
  8283. Mesh.prototype.synchronizeInstances = function () {
  8284. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8285. var instance = this.instances[instanceIndex];
  8286. instance._syncSubMeshes();
  8287. }
  8288. };
  8289. Mesh.CreateBox = function (name, size, scene, updatable) {
  8290. var box = new BABYLON.Mesh(name, scene);
  8291. var vertexData = BABYLON.VertexData.CreateBox(size);
  8292. vertexData.applyToMesh(box, updatable);
  8293. return box;
  8294. };
  8295. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8296. var sphere = new BABYLON.Mesh(name, scene);
  8297. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8298. vertexData.applyToMesh(sphere, updatable);
  8299. return sphere;
  8300. };
  8301. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8302. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8303. if (scene !== undefined) {
  8304. updatable = scene;
  8305. }
  8306. scene = subdivisions;
  8307. subdivisions = 1;
  8308. }
  8309. var cylinder = new BABYLON.Mesh(name, scene);
  8310. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8311. vertexData.applyToMesh(cylinder, updatable);
  8312. return cylinder;
  8313. };
  8314. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8315. var torus = new BABYLON.Mesh(name, scene);
  8316. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8317. vertexData.applyToMesh(torus, updatable);
  8318. return torus;
  8319. };
  8320. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8321. var torusKnot = new BABYLON.Mesh(name, scene);
  8322. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8323. vertexData.applyToMesh(torusKnot, updatable);
  8324. return torusKnot;
  8325. };
  8326. Mesh.CreateLines = function (name, points, scene, updatable) {
  8327. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8328. var vertexData = BABYLON.VertexData.CreateLines(points);
  8329. vertexData.applyToMesh(lines, updatable);
  8330. return lines;
  8331. };
  8332. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8333. var plane = new BABYLON.Mesh(name, scene);
  8334. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8335. vertexData.applyToMesh(plane, updatable);
  8336. return plane;
  8337. };
  8338. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8339. var ground = new BABYLON.GroundMesh(name, scene);
  8340. ground._setReady(false);
  8341. ground._subdivisions = subdivisions;
  8342. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8343. vertexData.applyToMesh(ground, updatable);
  8344. ground._setReady(true);
  8345. return ground;
  8346. };
  8347. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8348. var tiledGround = new BABYLON.Mesh(name, scene);
  8349. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8350. vertexData.applyToMesh(tiledGround, updatable);
  8351. return tiledGround;
  8352. };
  8353. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8354. var ground = new BABYLON.GroundMesh(name, scene);
  8355. ground._subdivisions = subdivisions;
  8356. ground._setReady(false);
  8357. var onload = function (img) {
  8358. var canvas = document.createElement("canvas");
  8359. var context = canvas.getContext("2d");
  8360. var heightMapWidth = img.width;
  8361. var heightMapHeight = img.height;
  8362. canvas.width = heightMapWidth;
  8363. canvas.height = heightMapHeight;
  8364. context.drawImage(img, 0, 0);
  8365. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8366. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8367. vertexData.applyToMesh(ground, updatable);
  8368. ground._setReady(true);
  8369. };
  8370. BABYLON.Tools.LoadImage(url, onload, function () {
  8371. }, scene.database);
  8372. return ground;
  8373. };
  8374. Mesh.MinMax = function (meshes) {
  8375. var minVector = null;
  8376. var maxVector = null;
  8377. for (var i in meshes) {
  8378. var mesh = meshes[i];
  8379. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8380. if (!minVector) {
  8381. minVector = boundingBox.minimumWorld;
  8382. maxVector = boundingBox.maximumWorld;
  8383. continue;
  8384. }
  8385. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8386. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8387. }
  8388. return {
  8389. min: minVector,
  8390. max: maxVector
  8391. };
  8392. };
  8393. Mesh.Center = function (meshesOrMinMaxVector) {
  8394. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8395. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8396. };
  8397. return Mesh;
  8398. })(BABYLON.AbstractMesh);
  8399. BABYLON.Mesh = Mesh;
  8400. })(BABYLON || (BABYLON = {}));
  8401. var __extends = this.__extends || function (d, b) {
  8402. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8403. function __() { this.constructor = d; }
  8404. __.prototype = b.prototype;
  8405. d.prototype = new __();
  8406. };
  8407. var BABYLON;
  8408. (function (BABYLON) {
  8409. var GroundMesh = (function (_super) {
  8410. __extends(GroundMesh, _super);
  8411. function GroundMesh(name, scene) {
  8412. _super.call(this, name, scene);
  8413. this.generateOctree = false;
  8414. this._worldInverse = new BABYLON.Matrix();
  8415. }
  8416. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8417. get: function () {
  8418. return this._subdivisions;
  8419. },
  8420. enumerable: true,
  8421. configurable: true
  8422. });
  8423. GroundMesh.prototype.optimize = function (chunksCount) {
  8424. this.subdivide(this._subdivisions);
  8425. this.createOrUpdateSubmeshesOctree(32);
  8426. };
  8427. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8428. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8429. this.getWorldMatrix().invertToRef(this._worldInverse);
  8430. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8431. var pickInfo = this.intersects(ray);
  8432. if (pickInfo.hit) {
  8433. return pickInfo.pickedPoint.y;
  8434. }
  8435. return 0;
  8436. };
  8437. return GroundMesh;
  8438. })(BABYLON.Mesh);
  8439. BABYLON.GroundMesh = GroundMesh;
  8440. })(BABYLON || (BABYLON = {}));
  8441. var __extends = this.__extends || function (d, b) {
  8442. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8443. function __() { this.constructor = d; }
  8444. __.prototype = b.prototype;
  8445. d.prototype = new __();
  8446. };
  8447. var BABYLON;
  8448. (function (BABYLON) {
  8449. var InstancedMesh = (function (_super) {
  8450. __extends(InstancedMesh, _super);
  8451. function InstancedMesh(name, source) {
  8452. _super.call(this, name, source.getScene());
  8453. source.instances.push(this);
  8454. this._sourceMesh = source;
  8455. this.position.copyFrom(source.position);
  8456. this.rotation.copyFrom(source.rotation);
  8457. this.scaling.copyFrom(source.scaling);
  8458. if (source.rotationQuaternion) {
  8459. this.rotationQuaternion = source.rotationQuaternion.clone();
  8460. }
  8461. this.infiniteDistance = source.infiniteDistance;
  8462. this.setPivotMatrix(source.getPivotMatrix());
  8463. this.refreshBoundingInfo();
  8464. this._syncSubMeshes();
  8465. }
  8466. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8467. get: function () {
  8468. return this._sourceMesh.receiveShadows;
  8469. },
  8470. enumerable: true,
  8471. configurable: true
  8472. });
  8473. Object.defineProperty(InstancedMesh.prototype, "material", {
  8474. get: function () {
  8475. return this._sourceMesh.material;
  8476. },
  8477. enumerable: true,
  8478. configurable: true
  8479. });
  8480. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8481. get: function () {
  8482. return this._sourceMesh.visibility;
  8483. },
  8484. enumerable: true,
  8485. configurable: true
  8486. });
  8487. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8488. get: function () {
  8489. return this._sourceMesh.skeleton;
  8490. },
  8491. enumerable: true,
  8492. configurable: true
  8493. });
  8494. InstancedMesh.prototype.getTotalVertices = function () {
  8495. return this._sourceMesh.getTotalVertices();
  8496. };
  8497. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8498. get: function () {
  8499. return this._sourceMesh;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. InstancedMesh.prototype.getVerticesData = function (kind) {
  8505. return this._sourceMesh.getVerticesData(kind);
  8506. };
  8507. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8508. return this._sourceMesh.isVerticesDataPresent(kind);
  8509. };
  8510. InstancedMesh.prototype.getIndices = function () {
  8511. return this._sourceMesh.getIndices();
  8512. };
  8513. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8514. get: function () {
  8515. return this._sourceMesh._positions;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8521. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8522. if (data) {
  8523. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8524. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8525. }
  8526. this._updateBoundingInfo();
  8527. };
  8528. InstancedMesh.prototype._preActivate = function () {
  8529. this.sourceMesh._preActivate();
  8530. };
  8531. InstancedMesh.prototype._activate = function (renderId) {
  8532. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8533. };
  8534. InstancedMesh.prototype._syncSubMeshes = function () {
  8535. this.releaseSubMeshes();
  8536. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8537. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8538. }
  8539. };
  8540. InstancedMesh.prototype._generatePointsArray = function () {
  8541. return this._sourceMesh._generatePointsArray();
  8542. };
  8543. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8544. var result = this._sourceMesh.createInstance(name);
  8545. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8546. this.refreshBoundingInfo();
  8547. if (newParent) {
  8548. result.parent = newParent;
  8549. }
  8550. if (!doNotCloneChildren) {
  8551. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8552. var mesh = this.getScene().meshes[index];
  8553. if (mesh.parent == this) {
  8554. mesh.clone(mesh.name, result);
  8555. }
  8556. }
  8557. }
  8558. result.computeWorldMatrix(true);
  8559. return result;
  8560. };
  8561. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8562. var index = this._sourceMesh.instances.indexOf(this);
  8563. this._sourceMesh.instances.splice(index, 1);
  8564. _super.prototype.dispose.call(this, doNotRecurse);
  8565. };
  8566. return InstancedMesh;
  8567. })(BABYLON.AbstractMesh);
  8568. BABYLON.InstancedMesh = InstancedMesh;
  8569. })(BABYLON || (BABYLON = {}));
  8570. var BABYLON;
  8571. (function (BABYLON) {
  8572. var SubMesh = (function () {
  8573. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8574. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8575. this.materialIndex = materialIndex;
  8576. this.verticesStart = verticesStart;
  8577. this.verticesCount = verticesCount;
  8578. this.indexStart = indexStart;
  8579. this.indexCount = indexCount;
  8580. this._renderId = 0;
  8581. this._mesh = mesh;
  8582. this._renderingMesh = renderingMesh || mesh;
  8583. mesh.subMeshes.push(this);
  8584. this._id = mesh.subMeshes.length - 1;
  8585. if (createBoundingBox) {
  8586. this.refreshBoundingInfo();
  8587. }
  8588. }
  8589. SubMesh.prototype.getBoundingInfo = function () {
  8590. return this._boundingInfo;
  8591. };
  8592. SubMesh.prototype.getMesh = function () {
  8593. return this._mesh;
  8594. };
  8595. SubMesh.prototype.getRenderingMesh = function () {
  8596. return this._renderingMesh;
  8597. };
  8598. SubMesh.prototype.getMaterial = function () {
  8599. var rootMaterial = this._renderingMesh.material;
  8600. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8601. var multiMaterial = rootMaterial;
  8602. return multiMaterial.getSubMaterial(this.materialIndex);
  8603. }
  8604. if (!rootMaterial) {
  8605. return this._mesh.getScene().defaultMaterial;
  8606. }
  8607. return rootMaterial;
  8608. };
  8609. SubMesh.prototype.refreshBoundingInfo = function () {
  8610. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8611. if (!data) {
  8612. this._boundingInfo = this._mesh._boundingInfo;
  8613. return;
  8614. }
  8615. var indices = this._renderingMesh.getIndices();
  8616. var extend;
  8617. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8618. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8619. } else {
  8620. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8621. }
  8622. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8623. };
  8624. SubMesh.prototype._checkCollision = function (collider) {
  8625. return this._boundingInfo._checkCollision(collider);
  8626. };
  8627. SubMesh.prototype.updateBoundingInfo = function (world) {
  8628. if (!this._boundingInfo) {
  8629. this.refreshBoundingInfo();
  8630. }
  8631. this._boundingInfo._update(world);
  8632. };
  8633. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8634. return this._boundingInfo.isInFrustum(frustumPlanes);
  8635. };
  8636. SubMesh.prototype.render = function () {
  8637. this._renderingMesh.render(this);
  8638. };
  8639. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8640. if (!this._linesIndexBuffer) {
  8641. var linesIndices = [];
  8642. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8643. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8644. }
  8645. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8646. this.linesIndexCount = linesIndices.length;
  8647. }
  8648. return this._linesIndexBuffer;
  8649. };
  8650. SubMesh.prototype.canIntersects = function (ray) {
  8651. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8652. };
  8653. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8654. var intersectInfo = null;
  8655. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8656. var p0 = positions[indices[index]];
  8657. var p1 = positions[indices[index + 1]];
  8658. var p2 = positions[indices[index + 2]];
  8659. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8660. if (currentIntersectInfo) {
  8661. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8662. intersectInfo = currentIntersectInfo;
  8663. intersectInfo.faceId = index / 3;
  8664. if (fastCheck) {
  8665. break;
  8666. }
  8667. }
  8668. }
  8669. }
  8670. return intersectInfo;
  8671. };
  8672. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8673. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8674. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8675. return result;
  8676. };
  8677. SubMesh.prototype.dispose = function () {
  8678. if (this._linesIndexBuffer) {
  8679. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8680. this._linesIndexBuffer = null;
  8681. }
  8682. var index = this._mesh.subMeshes.indexOf(this);
  8683. this._mesh.subMeshes.splice(index, 1);
  8684. };
  8685. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8686. var minVertexIndex = Number.MAX_VALUE;
  8687. var maxVertexIndex = -Number.MAX_VALUE;
  8688. renderingMesh = renderingMesh || mesh;
  8689. var indices = renderingMesh.getIndices();
  8690. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8691. var vertexIndex = indices[index];
  8692. if (vertexIndex < minVertexIndex)
  8693. minVertexIndex = vertexIndex;
  8694. if (vertexIndex > maxVertexIndex)
  8695. maxVertexIndex = vertexIndex;
  8696. }
  8697. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8698. };
  8699. return SubMesh;
  8700. })();
  8701. BABYLON.SubMesh = SubMesh;
  8702. })(BABYLON || (BABYLON = {}));
  8703. var BABYLON;
  8704. (function (BABYLON) {
  8705. var BaseTexture = (function () {
  8706. function BaseTexture(scene) {
  8707. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8708. this.hasAlpha = false;
  8709. this.getAlphaFromRGB = false;
  8710. this.level = 1;
  8711. this.isCube = false;
  8712. this.isRenderTarget = false;
  8713. this.animations = new Array();
  8714. this.coordinatesIndex = 0;
  8715. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8716. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8717. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8718. this.anisotropicFilteringLevel = 4;
  8719. this._scene = scene;
  8720. this._scene.textures.push(this);
  8721. }
  8722. BaseTexture.prototype.getScene = function () {
  8723. return this._scene;
  8724. };
  8725. BaseTexture.prototype.getTextureMatrix = function () {
  8726. return null;
  8727. };
  8728. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8729. return null;
  8730. };
  8731. BaseTexture.prototype.getInternalTexture = function () {
  8732. return this._texture;
  8733. };
  8734. BaseTexture.prototype.isReady = function () {
  8735. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8736. return true;
  8737. }
  8738. if (this._texture) {
  8739. return this._texture.isReady;
  8740. }
  8741. return false;
  8742. };
  8743. BaseTexture.prototype.getSize = function () {
  8744. if (this._texture._width) {
  8745. return { width: this._texture._width, height: this._texture._height };
  8746. }
  8747. if (this._texture._size) {
  8748. return { width: this._texture._size, height: this._texture._size };
  8749. }
  8750. return { width: 0, height: 0 };
  8751. };
  8752. BaseTexture.prototype.getBaseSize = function () {
  8753. if (!this.isReady())
  8754. return { width: 0, height: 0 };
  8755. if (this._texture._size) {
  8756. return { width: this._texture._size, height: this._texture._size };
  8757. }
  8758. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8759. };
  8760. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8761. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8762. for (var index = 0; index < texturesCache.length; index++) {
  8763. var texturesCacheEntry = texturesCache[index];
  8764. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8765. texturesCacheEntry.references++;
  8766. return texturesCacheEntry;
  8767. }
  8768. }
  8769. return null;
  8770. };
  8771. BaseTexture.prototype.delayLoad = function () {
  8772. };
  8773. BaseTexture.prototype.releaseInternalTexture = function () {
  8774. if (!this._texture) {
  8775. return;
  8776. }
  8777. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8778. this._texture.references--;
  8779. if (this._texture.references == 0) {
  8780. var index = texturesCache.indexOf(this._texture);
  8781. texturesCache.splice(index, 1);
  8782. this._scene.getEngine()._releaseTexture(this._texture);
  8783. delete this._texture;
  8784. }
  8785. };
  8786. BaseTexture.prototype.clone = function () {
  8787. return null;
  8788. };
  8789. BaseTexture.prototype.dispose = function () {
  8790. var index = this._scene.textures.indexOf(this);
  8791. if (index >= 0) {
  8792. this._scene.textures.splice(index, 1);
  8793. }
  8794. if (this._texture === undefined) {
  8795. return;
  8796. }
  8797. this.releaseInternalTexture();
  8798. if (this.onDispose) {
  8799. this.onDispose();
  8800. }
  8801. };
  8802. return BaseTexture;
  8803. })();
  8804. BABYLON.BaseTexture = BaseTexture;
  8805. })(BABYLON || (BABYLON = {}));
  8806. var BABYLON;
  8807. (function (BABYLON) {
  8808. var RenderingGroup = (function () {
  8809. function RenderingGroup(index, scene) {
  8810. this.index = index;
  8811. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8812. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8813. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8814. this._scene = scene;
  8815. }
  8816. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8817. if (customRenderFunction) {
  8818. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8819. return true;
  8820. }
  8821. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8822. return false;
  8823. }
  8824. var engine = this._scene.getEngine();
  8825. var subIndex;
  8826. var submesh;
  8827. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8828. submesh = this._opaqueSubMeshes.data[subIndex];
  8829. this._activeVertices += submesh.verticesCount;
  8830. submesh.render();
  8831. }
  8832. engine.setAlphaTesting(true);
  8833. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8834. submesh = this._alphaTestSubMeshes.data[subIndex];
  8835. this._activeVertices += submesh.verticesCount;
  8836. submesh.render();
  8837. }
  8838. engine.setAlphaTesting(false);
  8839. if (beforeTransparents) {
  8840. beforeTransparents();
  8841. }
  8842. if (this._transparentSubMeshes.length) {
  8843. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8844. submesh = this._transparentSubMeshes.data[subIndex];
  8845. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8846. }
  8847. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8848. sortedArray.sort(function (a, b) {
  8849. if (a._distanceToCamera < b._distanceToCamera) {
  8850. return 1;
  8851. }
  8852. if (a._distanceToCamera > b._distanceToCamera) {
  8853. return -1;
  8854. }
  8855. return 0;
  8856. });
  8857. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8858. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8859. submesh = sortedArray[subIndex];
  8860. this._activeVertices += submesh.verticesCount;
  8861. submesh.render();
  8862. }
  8863. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8864. }
  8865. return true;
  8866. };
  8867. RenderingGroup.prototype.prepare = function () {
  8868. this._opaqueSubMeshes.reset();
  8869. this._transparentSubMeshes.reset();
  8870. this._alphaTestSubMeshes.reset();
  8871. };
  8872. RenderingGroup.prototype.dispatch = function (subMesh) {
  8873. var material = subMesh.getMaterial();
  8874. var mesh = subMesh.getMesh();
  8875. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8876. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8877. this._transparentSubMeshes.push(subMesh);
  8878. }
  8879. } else if (material.needAlphaTesting()) {
  8880. this._alphaTestSubMeshes.push(subMesh);
  8881. } else {
  8882. this._opaqueSubMeshes.push(subMesh);
  8883. }
  8884. };
  8885. return RenderingGroup;
  8886. })();
  8887. BABYLON.RenderingGroup = RenderingGroup;
  8888. })(BABYLON || (BABYLON = {}));
  8889. var BABYLON;
  8890. (function (BABYLON) {
  8891. var RenderingManager = (function () {
  8892. function RenderingManager(scene) {
  8893. this._renderingGroups = new Array();
  8894. this._scene = scene;
  8895. }
  8896. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  8897. if (this._scene._activeParticleSystems.length === 0) {
  8898. return;
  8899. }
  8900. var beforeParticlesDate = new Date().getTime();
  8901. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  8902. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  8903. if (particleSystem.renderingGroupId !== index) {
  8904. continue;
  8905. }
  8906. this._clearDepthBuffer();
  8907. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  8908. this._scene._activeParticles += particleSystem.render();
  8909. }
  8910. }
  8911. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8912. };
  8913. RenderingManager.prototype._renderSprites = function (index) {
  8914. if (this._scene.spriteManagers.length === 0) {
  8915. return;
  8916. }
  8917. var beforeSpritessDate = new Date().getTime();
  8918. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  8919. var spriteManager = this._scene.spriteManagers[id];
  8920. if (spriteManager.renderingGroupId === index) {
  8921. this._clearDepthBuffer();
  8922. spriteManager.render();
  8923. }
  8924. }
  8925. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  8926. };
  8927. RenderingManager.prototype._clearDepthBuffer = function () {
  8928. if (this._depthBufferAlreadyCleaned) {
  8929. return;
  8930. }
  8931. this._scene.getEngine().clear(0, false, true);
  8932. this._depthBufferAlreadyCleaned = true;
  8933. };
  8934. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  8935. var _this = this;
  8936. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  8937. this._depthBufferAlreadyCleaned = false;
  8938. var renderingGroup = this._renderingGroups[index];
  8939. if (renderingGroup) {
  8940. this._clearDepthBuffer();
  8941. if (!renderingGroup.render(customRenderFunction, function () {
  8942. if (renderSprites) {
  8943. _this._renderSprites(index);
  8944. }
  8945. })) {
  8946. this._renderingGroups.splice(index, 1);
  8947. }
  8948. } else if (renderSprites) {
  8949. this._renderSprites(index);
  8950. }
  8951. if (renderParticles) {
  8952. this._renderParticles(index, activeMeshes);
  8953. }
  8954. }
  8955. };
  8956. RenderingManager.prototype.reset = function () {
  8957. for (var index in this._renderingGroups) {
  8958. var renderingGroup = this._renderingGroups[index];
  8959. renderingGroup.prepare();
  8960. }
  8961. };
  8962. RenderingManager.prototype.dispatch = function (subMesh) {
  8963. var mesh = subMesh.getMesh();
  8964. var renderingGroupId = mesh.renderingGroupId || 0;
  8965. if (!this._renderingGroups[renderingGroupId]) {
  8966. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  8967. }
  8968. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  8969. };
  8970. RenderingManager.MAX_RENDERINGGROUPS = 4;
  8971. return RenderingManager;
  8972. })();
  8973. BABYLON.RenderingManager = RenderingManager;
  8974. })(BABYLON || (BABYLON = {}));
  8975. var __extends = this.__extends || function (d, b) {
  8976. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8977. function __() { this.constructor = d; }
  8978. __.prototype = b.prototype;
  8979. d.prototype = new __();
  8980. };
  8981. var BABYLON;
  8982. (function (BABYLON) {
  8983. var Texture = (function (_super) {
  8984. __extends(Texture, _super);
  8985. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  8986. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  8987. _super.call(this, scene);
  8988. this.uOffset = 0;
  8989. this.vOffset = 0;
  8990. this.uScale = 1.0;
  8991. this.vScale = 1.0;
  8992. this.uAng = 0;
  8993. this.vAng = 0;
  8994. this.wAng = 0;
  8995. this.name = url;
  8996. this.url = url;
  8997. this._noMipmap = noMipmap;
  8998. this._invertY = invertY;
  8999. this._samplingMode = samplingMode;
  9000. if (!url) {
  9001. return;
  9002. }
  9003. this._texture = this._getFromCache(url, noMipmap);
  9004. if (!this._texture) {
  9005. if (!scene.useDelayedTextureLoading) {
  9006. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  9007. } else {
  9008. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9009. }
  9010. }
  9011. }
  9012. Texture.prototype.delayLoad = function () {
  9013. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9014. return;
  9015. }
  9016. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9017. this._texture = this._getFromCache(this.url, this._noMipmap);
  9018. if (!this._texture) {
  9019. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9020. }
  9021. };
  9022. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9023. x -= this.uOffset + 0.5;
  9024. y -= this.vOffset + 0.5;
  9025. z -= 0.5;
  9026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9027. t.x *= this.uScale;
  9028. t.y *= this.vScale;
  9029. t.x += 0.5;
  9030. t.y += 0.5;
  9031. t.z += 0.5;
  9032. };
  9033. Texture.prototype.getTextureMatrix = function () {
  9034. 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) {
  9035. return this._cachedTextureMatrix;
  9036. }
  9037. this._cachedUOffset = this.uOffset;
  9038. this._cachedVOffset = this.vOffset;
  9039. this._cachedUScale = this.uScale;
  9040. this._cachedVScale = this.vScale;
  9041. this._cachedUAng = this.uAng;
  9042. this._cachedVAng = this.vAng;
  9043. this._cachedWAng = this.wAng;
  9044. if (!this._cachedTextureMatrix) {
  9045. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9046. this._rowGenerationMatrix = new BABYLON.Matrix();
  9047. this._t0 = BABYLON.Vector3.Zero();
  9048. this._t1 = BABYLON.Vector3.Zero();
  9049. this._t2 = BABYLON.Vector3.Zero();
  9050. }
  9051. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9052. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9053. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9054. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9055. this._t1.subtractInPlace(this._t0);
  9056. this._t2.subtractInPlace(this._t0);
  9057. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9058. this._cachedTextureMatrix.m[0] = this._t1.x;
  9059. this._cachedTextureMatrix.m[1] = this._t1.y;
  9060. this._cachedTextureMatrix.m[2] = this._t1.z;
  9061. this._cachedTextureMatrix.m[4] = this._t2.x;
  9062. this._cachedTextureMatrix.m[5] = this._t2.y;
  9063. this._cachedTextureMatrix.m[6] = this._t2.z;
  9064. this._cachedTextureMatrix.m[8] = this._t0.x;
  9065. this._cachedTextureMatrix.m[9] = this._t0.y;
  9066. this._cachedTextureMatrix.m[10] = this._t0.z;
  9067. return this._cachedTextureMatrix;
  9068. };
  9069. Texture.prototype.getReflectionTextureMatrix = function () {
  9070. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9071. return this._cachedTextureMatrix;
  9072. }
  9073. if (!this._cachedTextureMatrix) {
  9074. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9075. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9076. }
  9077. switch (this.coordinatesMode) {
  9078. case BABYLON.Texture.SPHERICAL_MODE:
  9079. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9080. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9081. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9082. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9083. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9084. break;
  9085. case BABYLON.Texture.PLANAR_MODE:
  9086. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9087. this._cachedTextureMatrix[0] = this.uScale;
  9088. this._cachedTextureMatrix[5] = this.vScale;
  9089. this._cachedTextureMatrix[12] = this.uOffset;
  9090. this._cachedTextureMatrix[13] = this.vOffset;
  9091. break;
  9092. case BABYLON.Texture.PROJECTION_MODE:
  9093. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9094. this._projectionModeMatrix.m[0] = 0.5;
  9095. this._projectionModeMatrix.m[5] = -0.5;
  9096. this._projectionModeMatrix.m[10] = 0.0;
  9097. this._projectionModeMatrix.m[12] = 0.5;
  9098. this._projectionModeMatrix.m[13] = 0.5;
  9099. this._projectionModeMatrix.m[14] = 1.0;
  9100. this._projectionModeMatrix.m[15] = 1.0;
  9101. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9102. break;
  9103. default:
  9104. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9105. break;
  9106. }
  9107. return this._cachedTextureMatrix;
  9108. };
  9109. Texture.prototype.clone = function () {
  9110. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9111. newTexture.hasAlpha = this.hasAlpha;
  9112. newTexture.level = this.level;
  9113. newTexture.wrapU = this.wrapU;
  9114. newTexture.wrapV = this.wrapV;
  9115. newTexture.coordinatesIndex = this.coordinatesIndex;
  9116. newTexture.coordinatesMode = this.coordinatesMode;
  9117. newTexture.uOffset = this.uOffset;
  9118. newTexture.vOffset = this.vOffset;
  9119. newTexture.uScale = this.uScale;
  9120. newTexture.vScale = this.vScale;
  9121. newTexture.uAng = this.uAng;
  9122. newTexture.vAng = this.vAng;
  9123. newTexture.wAng = this.wAng;
  9124. return newTexture;
  9125. };
  9126. Texture.NEAREST_SAMPLINGMODE = 1;
  9127. Texture.BILINEAR_SAMPLINGMODE = 2;
  9128. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9129. Texture.EXPLICIT_MODE = 0;
  9130. Texture.SPHERICAL_MODE = 1;
  9131. Texture.PLANAR_MODE = 2;
  9132. Texture.CUBIC_MODE = 3;
  9133. Texture.PROJECTION_MODE = 4;
  9134. Texture.SKYBOX_MODE = 5;
  9135. Texture.CLAMP_ADDRESSMODE = 0;
  9136. Texture.WRAP_ADDRESSMODE = 1;
  9137. Texture.MIRROR_ADDRESSMODE = 2;
  9138. return Texture;
  9139. })(BABYLON.BaseTexture);
  9140. BABYLON.Texture = Texture;
  9141. })(BABYLON || (BABYLON = {}));
  9142. var __extends = this.__extends || function (d, b) {
  9143. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9144. function __() { this.constructor = d; }
  9145. __.prototype = b.prototype;
  9146. d.prototype = new __();
  9147. };
  9148. var BABYLON;
  9149. (function (BABYLON) {
  9150. var CubeTexture = (function (_super) {
  9151. __extends(CubeTexture, _super);
  9152. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9153. _super.call(this, scene);
  9154. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9155. this.name = rootUrl;
  9156. this.url = rootUrl;
  9157. this._noMipmap = noMipmap;
  9158. this.hasAlpha = false;
  9159. this._texture = this._getFromCache(rootUrl, noMipmap);
  9160. if (!extensions) {
  9161. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9162. }
  9163. this._extensions = extensions;
  9164. if (!this._texture) {
  9165. if (!scene.useDelayedTextureLoading) {
  9166. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9167. } else {
  9168. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9169. }
  9170. }
  9171. this.isCube = true;
  9172. this._textureMatrix = BABYLON.Matrix.Identity();
  9173. }
  9174. CubeTexture.prototype.clone = function () {
  9175. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9176. newTexture.level = this.level;
  9177. newTexture.wrapU = this.wrapU;
  9178. newTexture.wrapV = this.wrapV;
  9179. newTexture.coordinatesIndex = this.coordinatesIndex;
  9180. newTexture.coordinatesMode = this.coordinatesMode;
  9181. return newTexture;
  9182. };
  9183. CubeTexture.prototype.delayLoad = function () {
  9184. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9185. return;
  9186. }
  9187. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9188. this._texture = this._getFromCache(this.url, this._noMipmap);
  9189. if (!this._texture) {
  9190. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9191. }
  9192. };
  9193. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9194. return this._textureMatrix;
  9195. };
  9196. return CubeTexture;
  9197. })(BABYLON.BaseTexture);
  9198. BABYLON.CubeTexture = CubeTexture;
  9199. })(BABYLON || (BABYLON = {}));
  9200. var __extends = this.__extends || function (d, b) {
  9201. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9202. function __() { this.constructor = d; }
  9203. __.prototype = b.prototype;
  9204. d.prototype = new __();
  9205. };
  9206. var BABYLON;
  9207. (function (BABYLON) {
  9208. var RenderTargetTexture = (function (_super) {
  9209. __extends(RenderTargetTexture, _super);
  9210. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9211. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9212. _super.call(this, null, scene, !generateMipMaps);
  9213. this.renderList = new Array();
  9214. this.renderParticles = true;
  9215. this.renderSprites = false;
  9216. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9217. this._currentRefreshId = -1;
  9218. this._refreshRate = 1;
  9219. this.name = name;
  9220. this.isRenderTarget = true;
  9221. this._size = size;
  9222. this._generateMipMaps = generateMipMaps;
  9223. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9224. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9225. this._renderingManager = new BABYLON.RenderingManager(scene);
  9226. }
  9227. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9228. this._currentRefreshId = -1;
  9229. };
  9230. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9231. get: function () {
  9232. return this._refreshRate;
  9233. },
  9234. set: function (value) {
  9235. this._refreshRate = value;
  9236. this.resetRefreshCounter();
  9237. },
  9238. enumerable: true,
  9239. configurable: true
  9240. });
  9241. RenderTargetTexture.prototype._shouldRender = function () {
  9242. if (this._currentRefreshId === -1) {
  9243. this._currentRefreshId = 1;
  9244. return true;
  9245. }
  9246. if (this.refreshRate == this._currentRefreshId) {
  9247. this._currentRefreshId = 1;
  9248. return true;
  9249. }
  9250. this._currentRefreshId++;
  9251. return false;
  9252. };
  9253. RenderTargetTexture.prototype.getRenderSize = function () {
  9254. return this._size;
  9255. };
  9256. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9257. this.releaseInternalTexture();
  9258. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9259. };
  9260. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9261. var scene = this.getScene();
  9262. var engine = scene.getEngine();
  9263. if (this._waitingRenderList) {
  9264. this.renderList = [];
  9265. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9266. var id = this._waitingRenderList[index];
  9267. this.renderList.push(scene.getMeshByID(id));
  9268. }
  9269. delete this._waitingRenderList;
  9270. }
  9271. if (!this.renderList) {
  9272. return;
  9273. }
  9274. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9275. engine.bindFramebuffer(this._texture);
  9276. }
  9277. engine.clear(scene.clearColor, true, true);
  9278. this._renderingManager.reset();
  9279. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9280. var mesh = this.renderList[meshIndex];
  9281. if (mesh) {
  9282. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9283. this.resetRefreshCounter();
  9284. continue;
  9285. }
  9286. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9287. mesh._activate(scene.getRenderId());
  9288. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9289. var subMesh = mesh.subMeshes[subIndex];
  9290. scene._activeVertices += subMesh.verticesCount;
  9291. this._renderingManager.dispatch(subMesh);
  9292. }
  9293. }
  9294. }
  9295. }
  9296. if (!this._doNotChangeAspectRatio) {
  9297. scene.updateTransformMatrix(true);
  9298. }
  9299. if (this.onBeforeRender) {
  9300. this.onBeforeRender();
  9301. }
  9302. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9303. if (useCameraPostProcess) {
  9304. scene.postProcessManager._finalizeFrame(false, this._texture);
  9305. }
  9306. if (this.onAfterRender) {
  9307. this.onAfterRender();
  9308. }
  9309. engine.unBindFramebuffer(this._texture);
  9310. if (!this._doNotChangeAspectRatio) {
  9311. scene.updateTransformMatrix(true);
  9312. }
  9313. };
  9314. RenderTargetTexture.prototype.clone = function () {
  9315. var textureSize = this.getSize();
  9316. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9317. newTexture.hasAlpha = this.hasAlpha;
  9318. newTexture.level = this.level;
  9319. newTexture.coordinatesMode = this.coordinatesMode;
  9320. newTexture.renderList = this.renderList.slice(0);
  9321. return newTexture;
  9322. };
  9323. return RenderTargetTexture;
  9324. })(BABYLON.Texture);
  9325. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9326. })(BABYLON || (BABYLON = {}));
  9327. var __extends = this.__extends || function (d, b) {
  9328. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9329. function __() { this.constructor = d; }
  9330. __.prototype = b.prototype;
  9331. d.prototype = new __();
  9332. };
  9333. var BABYLON;
  9334. (function (BABYLON) {
  9335. var MirrorTexture = (function (_super) {
  9336. __extends(MirrorTexture, _super);
  9337. function MirrorTexture(name, size, scene, generateMipMaps) {
  9338. var _this = this;
  9339. _super.call(this, name, size, scene, generateMipMaps, true);
  9340. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9341. this._transformMatrix = BABYLON.Matrix.Zero();
  9342. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9343. this.onBeforeRender = function () {
  9344. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9345. _this._savedViewMatrix = scene.getViewMatrix();
  9346. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9347. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9348. scene.clipPlane = _this.mirrorPlane;
  9349. scene.getEngine().cullBackFaces = false;
  9350. };
  9351. this.onAfterRender = function () {
  9352. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9353. scene.getEngine().cullBackFaces = true;
  9354. delete scene.clipPlane;
  9355. };
  9356. }
  9357. MirrorTexture.prototype.clone = function () {
  9358. var textureSize = this.getSize();
  9359. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9360. newTexture.hasAlpha = this.hasAlpha;
  9361. newTexture.level = this.level;
  9362. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9363. newTexture.renderList = this.renderList.slice(0);
  9364. return newTexture;
  9365. };
  9366. return MirrorTexture;
  9367. })(BABYLON.RenderTargetTexture);
  9368. BABYLON.MirrorTexture = MirrorTexture;
  9369. })(BABYLON || (BABYLON = {}));
  9370. var __extends = this.__extends || function (d, b) {
  9371. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9372. function __() { this.constructor = d; }
  9373. __.prototype = b.prototype;
  9374. d.prototype = new __();
  9375. };
  9376. var BABYLON;
  9377. (function (BABYLON) {
  9378. var DynamicTexture = (function (_super) {
  9379. __extends(DynamicTexture, _super);
  9380. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9381. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9382. _super.call(this, null, scene, !generateMipMaps);
  9383. this.name = name;
  9384. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9385. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9386. this._generateMipMaps = generateMipMaps;
  9387. if (options.getContext) {
  9388. this._canvas = options;
  9389. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9390. } else {
  9391. this._canvas = document.createElement("canvas");
  9392. if (options.width) {
  9393. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9394. } else {
  9395. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9396. }
  9397. }
  9398. var textureSize = this.getSize();
  9399. this._canvas.width = textureSize.width;
  9400. this._canvas.height = textureSize.height;
  9401. this._context = this._canvas.getContext("2d");
  9402. }
  9403. DynamicTexture.prototype.getContext = function () {
  9404. return this._context;
  9405. };
  9406. DynamicTexture.prototype.update = function (invertY) {
  9407. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9408. };
  9409. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9410. var size = this.getSize();
  9411. if (clearColor) {
  9412. this._context.fillStyle = clearColor;
  9413. this._context.fillRect(0, 0, size.width, size.height);
  9414. }
  9415. this._context.font = font;
  9416. if (x === null) {
  9417. var textSize = this._context.measureText(text);
  9418. x = (size.width - textSize.width) / 2;
  9419. }
  9420. this._context.fillStyle = color;
  9421. this._context.fillText(text, x, y);
  9422. this.update(invertY);
  9423. };
  9424. DynamicTexture.prototype.clone = function () {
  9425. var textureSize = this.getSize();
  9426. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9427. newTexture.hasAlpha = this.hasAlpha;
  9428. newTexture.level = this.level;
  9429. newTexture.wrapU = this.wrapU;
  9430. newTexture.wrapV = this.wrapV;
  9431. return newTexture;
  9432. };
  9433. return DynamicTexture;
  9434. })(BABYLON.Texture);
  9435. BABYLON.DynamicTexture = DynamicTexture;
  9436. })(BABYLON || (BABYLON = {}));
  9437. var __extends = this.__extends || function (d, b) {
  9438. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9439. function __() { this.constructor = d; }
  9440. __.prototype = b.prototype;
  9441. d.prototype = new __();
  9442. };
  9443. var BABYLON;
  9444. (function (BABYLON) {
  9445. var VideoTexture = (function (_super) {
  9446. __extends(VideoTexture, _super);
  9447. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9448. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9449. var _this = this;
  9450. _super.call(this, null, scene, !generateMipMaps, invertY);
  9451. this._autoLaunch = true;
  9452. this.name = name;
  9453. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9454. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9455. var requiredWidth = size.width || size;
  9456. var requiredHeight = size.height || size;
  9457. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9458. var textureSize = this.getSize();
  9459. this.video = document.createElement("video");
  9460. this.video.width = textureSize.width;
  9461. this.video.height = textureSize.height;
  9462. this.video.autoplay = false;
  9463. this.video.loop = true;
  9464. this.video.addEventListener("canplaythrough", function () {
  9465. if (_this._texture) {
  9466. _this._texture.isReady = true;
  9467. }
  9468. });
  9469. urls.forEach(function (url) {
  9470. var source = document.createElement("source");
  9471. source.src = url;
  9472. _this.video.appendChild(source);
  9473. });
  9474. this._lastUpdate = new Date().getTime();
  9475. }
  9476. VideoTexture.prototype.update = function () {
  9477. if (this._autoLaunch) {
  9478. this._autoLaunch = false;
  9479. this.video.play();
  9480. }
  9481. var now = new Date().getTime();
  9482. if (now - this._lastUpdate < 15) {
  9483. return false;
  9484. }
  9485. this._lastUpdate = now;
  9486. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9487. return true;
  9488. };
  9489. return VideoTexture;
  9490. })(BABYLON.Texture);
  9491. BABYLON.VideoTexture = VideoTexture;
  9492. })(BABYLON || (BABYLON = {}));
  9493. var BABYLON;
  9494. (function (BABYLON) {
  9495. var EffectFallbacks = (function () {
  9496. function EffectFallbacks() {
  9497. this._defines = {};
  9498. this._currentRank = 32;
  9499. this._maxRank = -1;
  9500. }
  9501. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9502. if (!this._defines[rank]) {
  9503. if (rank < this._currentRank) {
  9504. this._currentRank = rank;
  9505. }
  9506. if (rank > this._maxRank) {
  9507. this._maxRank = rank;
  9508. }
  9509. this._defines[rank] = new Array();
  9510. }
  9511. this._defines[rank].push(define);
  9512. };
  9513. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9514. get: function () {
  9515. return this._currentRank <= this._maxRank;
  9516. },
  9517. enumerable: true,
  9518. configurable: true
  9519. });
  9520. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9521. var currentFallbacks = this._defines[this._currentRank];
  9522. for (var index = 0; index < currentFallbacks.length; index++) {
  9523. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9524. }
  9525. this._currentRank++;
  9526. return currentDefines;
  9527. };
  9528. return EffectFallbacks;
  9529. })();
  9530. BABYLON.EffectFallbacks = EffectFallbacks;
  9531. var Effect = (function () {
  9532. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9533. var _this = this;
  9534. this._isReady = false;
  9535. this._compilationError = "";
  9536. this._valueCache = [];
  9537. this._engine = engine;
  9538. this.name = baseName;
  9539. this.defines = defines;
  9540. this._uniformsNames = uniformsNames.concat(samplers);
  9541. this._samplers = samplers;
  9542. this._attributesNames = attributesNames;
  9543. this.onError = onError;
  9544. this.onCompiled = onCompiled;
  9545. var vertexSource;
  9546. var fragmentSource;
  9547. if (baseName.vertexElement) {
  9548. vertexSource = document.getElementById(baseName.vertexElement);
  9549. } else {
  9550. vertexSource = baseName.vertex || baseName;
  9551. }
  9552. if (baseName.fragmentElement) {
  9553. fragmentSource = document.getElementById(baseName.fragmentElement);
  9554. } else {
  9555. fragmentSource = baseName.fragment || baseName;
  9556. }
  9557. this._loadVertexShader(vertexSource, function (vertexCode) {
  9558. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9559. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9560. });
  9561. });
  9562. }
  9563. Effect.prototype.isReady = function () {
  9564. return this._isReady;
  9565. };
  9566. Effect.prototype.getProgram = function () {
  9567. return this._program;
  9568. };
  9569. Effect.prototype.getAttributesNames = function () {
  9570. return this._attributesNames;
  9571. };
  9572. Effect.prototype.getAttributeLocation = function (index) {
  9573. return this._attributes[index];
  9574. };
  9575. Effect.prototype.getAttributeLocationByName = function (name) {
  9576. var index = this._attributesNames.indexOf(name);
  9577. return this._attributes[index];
  9578. };
  9579. Effect.prototype.getAttributesCount = function () {
  9580. return this._attributes.length;
  9581. };
  9582. Effect.prototype.getUniformIndex = function (uniformName) {
  9583. return this._uniformsNames.indexOf(uniformName);
  9584. };
  9585. Effect.prototype.getUniform = function (uniformName) {
  9586. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9587. };
  9588. Effect.prototype.getSamplers = function () {
  9589. return this._samplers;
  9590. };
  9591. Effect.prototype.getCompilationError = function () {
  9592. return this._compilationError;
  9593. };
  9594. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9595. if (vertex instanceof HTMLElement) {
  9596. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9597. callback(vertexCode);
  9598. return;
  9599. }
  9600. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9601. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9602. return;
  9603. }
  9604. var vertexShaderUrl;
  9605. if (vertex[0] === ".") {
  9606. vertexShaderUrl = vertex;
  9607. } else {
  9608. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9609. }
  9610. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9611. };
  9612. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9613. if (fragment instanceof HTMLElement) {
  9614. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9615. callback(fragmentCode);
  9616. return;
  9617. }
  9618. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9619. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9620. return;
  9621. }
  9622. var fragmentShaderUrl;
  9623. if (fragment[0] === ".") {
  9624. fragmentShaderUrl = fragment;
  9625. } else {
  9626. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9627. }
  9628. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9629. };
  9630. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9631. try {
  9632. var engine = this._engine;
  9633. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9634. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9635. this._attributes = engine.getAttributes(this._program, attributesNames);
  9636. for (var index = 0; index < this._samplers.length; index++) {
  9637. var sampler = this.getUniform(this._samplers[index]);
  9638. if (sampler == null) {
  9639. this._samplers.splice(index, 1);
  9640. index--;
  9641. }
  9642. }
  9643. engine.bindSamplers(this);
  9644. this._isReady = true;
  9645. if (this.onCompiled) {
  9646. this.onCompiled(this);
  9647. }
  9648. } catch (e) {
  9649. if (fallbacks && fallbacks.isMoreFallbacks) {
  9650. defines = fallbacks.reduce(defines);
  9651. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9652. } else {
  9653. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9654. BABYLON.Tools.Error("Defines: " + defines);
  9655. BABYLON.Tools.Error("Error: " + e.message);
  9656. this._compilationError = e.message;
  9657. if (this.onError) {
  9658. this.onError(this, this._compilationError);
  9659. }
  9660. }
  9661. }
  9662. };
  9663. Effect.prototype._bindTexture = function (channel, texture) {
  9664. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9665. };
  9666. Effect.prototype.setTexture = function (channel, texture) {
  9667. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9668. };
  9669. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9670. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9671. };
  9672. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9673. if (!this._valueCache[uniformName]) {
  9674. this._valueCache[uniformName] = [x, y];
  9675. return;
  9676. }
  9677. this._valueCache[uniformName][0] = x;
  9678. this._valueCache[uniformName][1] = y;
  9679. };
  9680. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9681. if (!this._valueCache[uniformName]) {
  9682. this._valueCache[uniformName] = [x, y, z];
  9683. return;
  9684. }
  9685. this._valueCache[uniformName][0] = x;
  9686. this._valueCache[uniformName][1] = y;
  9687. this._valueCache[uniformName][2] = z;
  9688. };
  9689. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9690. if (!this._valueCache[uniformName]) {
  9691. this._valueCache[uniformName] = [x, y, z, w];
  9692. return;
  9693. }
  9694. this._valueCache[uniformName][0] = x;
  9695. this._valueCache[uniformName][1] = y;
  9696. this._valueCache[uniformName][2] = z;
  9697. this._valueCache[uniformName][3] = w;
  9698. };
  9699. Effect.prototype.setArray = function (uniformName, array) {
  9700. this._engine.setArray(this.getUniform(uniformName), array);
  9701. return this;
  9702. };
  9703. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9704. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9705. return this;
  9706. };
  9707. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9708. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9709. return this;
  9710. };
  9711. Effect.prototype.setFloat = function (uniformName, value) {
  9712. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9713. return this;
  9714. this._valueCache[uniformName] = value;
  9715. this._engine.setFloat(this.getUniform(uniformName), value);
  9716. return this;
  9717. };
  9718. Effect.prototype.setBool = function (uniformName, bool) {
  9719. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9720. return this;
  9721. this._valueCache[uniformName] = bool;
  9722. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9723. return this;
  9724. };
  9725. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9726. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9727. return this;
  9728. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9729. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9730. return this;
  9731. };
  9732. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9733. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9734. return this;
  9735. this._cacheFloat2(uniformName, x, y);
  9736. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9737. return this;
  9738. };
  9739. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9740. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9741. return this;
  9742. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9743. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9744. return this;
  9745. };
  9746. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9747. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9748. return this;
  9749. this._cacheFloat3(uniformName, x, y, z);
  9750. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9751. return this;
  9752. };
  9753. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9754. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9755. return this;
  9756. this._cacheFloat4(uniformName, x, y, z, w);
  9757. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9758. return this;
  9759. };
  9760. Effect.prototype.setColor3 = function (uniformName, color3) {
  9761. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9762. return this;
  9763. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9764. this._engine.setColor3(this.getUniform(uniformName), color3);
  9765. return this;
  9766. };
  9767. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9768. 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)
  9769. return this;
  9770. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9771. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9772. return this;
  9773. };
  9774. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9775. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9776. blurPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9777. colorPixelShader:"precision mediump float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9778. colorVertexShader:"precision mediump 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}",
  9779. convolutionPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9780. defaultPixelShader:"#ifdef GL_ES\nprecision mediump 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 + 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 alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\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}",
  9781. defaultVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9782. displayPassPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9783. filterPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9784. fxaaPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9785. layerPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9786. layerVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9787. legacydefaultPixelShader:"#ifdef GL_ES\nprecision mediump 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 + 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}",
  9788. legacydefaultVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9789. lensFlarePixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9790. lensFlareVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9791. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\n\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  9792. outlinePixelShader:"precision mediump 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}",
  9793. outlineVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9794. particlesPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9795. particlesVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9796. passPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  9797. postprocessVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9798. refractionPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9799. shadowMapPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9800. shadowMapVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9801. spritesPixelShader:"#ifdef GL_ES\nprecision mediump 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}",
  9802. spritesVertexShader:"#ifdef GL_ES\nprecision mediump 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}",
  9803. };
  9804. return Effect;
  9805. })();
  9806. BABYLON.Effect = Effect;
  9807. })(BABYLON || (BABYLON = {}));
  9808. var BABYLON;
  9809. (function (BABYLON) {
  9810. var Material = (function () {
  9811. function Material(name, scene, doNotAdd) {
  9812. this.name = name;
  9813. this.checkReadyOnEveryCall = true;
  9814. this.checkReadyOnlyOnce = false;
  9815. this.state = "";
  9816. this.alpha = 1.0;
  9817. this.wireframe = false;
  9818. this.backFaceCulling = true;
  9819. this._wasPreviouslyReady = false;
  9820. this.id = name;
  9821. this._scene = scene;
  9822. if (!doNotAdd) {
  9823. scene.materials.push(this);
  9824. }
  9825. }
  9826. Material.prototype.isReady = function (mesh, useInstances) {
  9827. return true;
  9828. };
  9829. Material.prototype.getEffect = function () {
  9830. return this._effect;
  9831. };
  9832. Material.prototype.getScene = function () {
  9833. return this._scene;
  9834. };
  9835. Material.prototype.needAlphaBlending = function () {
  9836. return (this.alpha < 1.0);
  9837. };
  9838. Material.prototype.needAlphaTesting = function () {
  9839. return false;
  9840. };
  9841. Material.prototype.getAlphaTestTexture = function () {
  9842. return null;
  9843. };
  9844. Material.prototype.trackCreation = function (onCompiled, onError) {
  9845. };
  9846. Material.prototype._preBind = function () {
  9847. var engine = this._scene.getEngine();
  9848. engine.enableEffect(this._effect);
  9849. engine.setState(this.backFaceCulling);
  9850. };
  9851. Material.prototype.bind = function (world, mesh) {
  9852. };
  9853. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9854. };
  9855. Material.prototype.unbind = function () {
  9856. };
  9857. Material.prototype.dispose = function (forceDisposeEffect) {
  9858. var index = this._scene.materials.indexOf(this);
  9859. this._scene.materials.splice(index, 1);
  9860. if (forceDisposeEffect && this._effect) {
  9861. this._scene.getEngine()._releaseEffect(this._effect);
  9862. this._effect = null;
  9863. }
  9864. if (this.onDispose) {
  9865. this.onDispose();
  9866. }
  9867. };
  9868. return Material;
  9869. })();
  9870. BABYLON.Material = Material;
  9871. })(BABYLON || (BABYLON = {}));
  9872. var __extends = this.__extends || function (d, b) {
  9873. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9874. function __() { this.constructor = d; }
  9875. __.prototype = b.prototype;
  9876. d.prototype = new __();
  9877. };
  9878. var BABYLON;
  9879. (function (BABYLON) {
  9880. var maxSimultaneousLights = 4;
  9881. var FresnelParameters = (function () {
  9882. function FresnelParameters() {
  9883. this.isEnabled = true;
  9884. this.leftColor = BABYLON.Color3.White();
  9885. this.rightColor = BABYLON.Color3.Black();
  9886. this.bias = 0;
  9887. this.power = 1;
  9888. }
  9889. return FresnelParameters;
  9890. })();
  9891. BABYLON.FresnelParameters = FresnelParameters;
  9892. var StandardMaterial = (function (_super) {
  9893. __extends(StandardMaterial, _super);
  9894. function StandardMaterial(name, scene) {
  9895. var _this = this;
  9896. _super.call(this, name, scene);
  9897. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9898. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  9899. this.specularColor = new BABYLON.Color3(1, 1, 1);
  9900. this.specularPower = 64;
  9901. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  9902. this.useAlphaFromDiffuseTexture = false;
  9903. this._cachedDefines = null;
  9904. this._renderTargets = new BABYLON.SmartArray(16);
  9905. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  9906. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  9907. this._scaledDiffuse = new BABYLON.Color3();
  9908. this._scaledSpecular = new BABYLON.Color3();
  9909. this.getRenderTargetTextures = function () {
  9910. _this._renderTargets.reset();
  9911. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  9912. _this._renderTargets.push(_this.reflectionTexture);
  9913. }
  9914. return _this._renderTargets;
  9915. };
  9916. }
  9917. StandardMaterial.prototype.needAlphaBlending = function () {
  9918. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  9919. };
  9920. StandardMaterial.prototype.needAlphaTesting = function () {
  9921. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  9922. };
  9923. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  9924. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  9925. };
  9926. StandardMaterial.prototype.getAlphaTestTexture = function () {
  9927. return this.diffuseTexture;
  9928. };
  9929. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  9930. if (this.checkReadyOnlyOnce) {
  9931. if (this._wasPreviouslyReady) {
  9932. return true;
  9933. }
  9934. }
  9935. var scene = this.getScene();
  9936. if (!this.checkReadyOnEveryCall) {
  9937. if (this._renderId === scene.getRenderId()) {
  9938. return true;
  9939. }
  9940. }
  9941. var engine = scene.getEngine();
  9942. var defines = [];
  9943. var fallbacks = new BABYLON.EffectFallbacks();
  9944. if (scene.texturesEnabled) {
  9945. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  9946. if (!this.diffuseTexture.isReady()) {
  9947. return false;
  9948. } else {
  9949. defines.push("#define DIFFUSE");
  9950. }
  9951. }
  9952. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  9953. if (!this.ambientTexture.isReady()) {
  9954. return false;
  9955. } else {
  9956. defines.push("#define AMBIENT");
  9957. }
  9958. }
  9959. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  9960. if (!this.opacityTexture.isReady()) {
  9961. return false;
  9962. } else {
  9963. defines.push("#define OPACITY");
  9964. if (this.opacityTexture.getAlphaFromRGB) {
  9965. defines.push("#define OPACITYRGB");
  9966. }
  9967. }
  9968. }
  9969. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  9970. if (!this.reflectionTexture.isReady()) {
  9971. return false;
  9972. } else {
  9973. defines.push("#define REFLECTION");
  9974. fallbacks.addFallback(0, "REFLECTION");
  9975. }
  9976. }
  9977. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  9978. if (!this.emissiveTexture.isReady()) {
  9979. return false;
  9980. } else {
  9981. defines.push("#define EMISSIVE");
  9982. }
  9983. }
  9984. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  9985. if (!this.specularTexture.isReady()) {
  9986. return false;
  9987. } else {
  9988. defines.push("#define SPECULAR");
  9989. fallbacks.addFallback(0, "SPECULAR");
  9990. }
  9991. }
  9992. }
  9993. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  9994. if (!this.bumpTexture.isReady()) {
  9995. return false;
  9996. } else {
  9997. defines.push("#define BUMP");
  9998. fallbacks.addFallback(0, "BUMP");
  9999. }
  10000. }
  10001. if (scene.clipPlane) {
  10002. defines.push("#define CLIPPLANE");
  10003. }
  10004. if (engine.getAlphaTesting()) {
  10005. defines.push("#define ALPHATEST");
  10006. }
  10007. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10008. defines.push("#define ALPHAFROMDIFFUSE");
  10009. }
  10010. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10011. defines.push("#define FOG");
  10012. fallbacks.addFallback(1, "FOG");
  10013. }
  10014. var shadowsActivated = false;
  10015. var lightIndex = 0;
  10016. if (scene.lightsEnabled) {
  10017. for (var index = 0; index < scene.lights.length; index++) {
  10018. var light = scene.lights[index];
  10019. if (!light.isEnabled()) {
  10020. continue;
  10021. }
  10022. if (light._excludedMeshesIds.length > 0) {
  10023. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10024. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10025. if (excludedMesh) {
  10026. light.excludedMeshes.push(excludedMesh);
  10027. }
  10028. }
  10029. light._excludedMeshesIds = [];
  10030. }
  10031. if (light._includedOnlyMeshesIds.length > 0) {
  10032. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10033. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10034. if (includedOnlyMesh) {
  10035. light.includedOnlyMeshes.push(includedOnlyMesh);
  10036. }
  10037. }
  10038. light._includedOnlyMeshesIds = [];
  10039. }
  10040. if (!light.canAffectMesh(mesh)) {
  10041. continue;
  10042. }
  10043. defines.push("#define LIGHT" + lightIndex);
  10044. if (lightIndex > 0) {
  10045. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10046. }
  10047. var type;
  10048. if (light instanceof BABYLON.SpotLight) {
  10049. type = "#define SPOTLIGHT" + lightIndex;
  10050. } else if (light instanceof BABYLON.HemisphericLight) {
  10051. type = "#define HEMILIGHT" + lightIndex;
  10052. } else {
  10053. type = "#define POINTDIRLIGHT" + lightIndex;
  10054. }
  10055. defines.push(type);
  10056. if (lightIndex > 0) {
  10057. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10058. }
  10059. var shadowGenerator = light.getShadowGenerator();
  10060. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10061. defines.push("#define SHADOW" + lightIndex);
  10062. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10063. if (!shadowsActivated) {
  10064. defines.push("#define SHADOWS");
  10065. shadowsActivated = true;
  10066. }
  10067. if (shadowGenerator.useVarianceShadowMap) {
  10068. defines.push("#define SHADOWVSM" + lightIndex);
  10069. if (lightIndex > 0) {
  10070. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10071. }
  10072. }
  10073. if (shadowGenerator.usePoissonSampling) {
  10074. defines.push("#define SHADOWPCF" + lightIndex);
  10075. if (lightIndex > 0) {
  10076. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10077. }
  10078. }
  10079. }
  10080. lightIndex++;
  10081. if (lightIndex == maxSimultaneousLights)
  10082. break;
  10083. }
  10084. }
  10085. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10086. var fresnelRank = 1;
  10087. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10088. defines.push("#define DIFFUSEFRESNEL");
  10089. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10090. fresnelRank++;
  10091. }
  10092. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10093. defines.push("#define OPACITYFRESNEL");
  10094. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10095. fresnelRank++;
  10096. }
  10097. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10098. defines.push("#define REFLECTIONFRESNEL");
  10099. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10100. fresnelRank++;
  10101. }
  10102. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10103. defines.push("#define EMISSIVEFRESNEL");
  10104. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10105. fresnelRank++;
  10106. }
  10107. defines.push("#define FRESNEL");
  10108. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10109. }
  10110. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10111. if (mesh) {
  10112. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10113. attribs.push(BABYLON.VertexBuffer.UVKind);
  10114. defines.push("#define UV1");
  10115. }
  10116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10117. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10118. defines.push("#define UV2");
  10119. }
  10120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10121. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10122. defines.push("#define VERTEXCOLOR");
  10123. }
  10124. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10127. defines.push("#define BONES");
  10128. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10129. defines.push("#define BONES4");
  10130. fallbacks.addFallback(0, "BONES4");
  10131. }
  10132. if (useInstances) {
  10133. defines.push("#define INSTANCES");
  10134. attribs.push("world0");
  10135. attribs.push("world1");
  10136. attribs.push("world2");
  10137. attribs.push("world3");
  10138. }
  10139. }
  10140. var join = defines.join("\n");
  10141. if (this._cachedDefines != join) {
  10142. this._cachedDefines = join;
  10143. var shaderName = "default";
  10144. if (!scene.getEngine().getCaps().standardDerivatives) {
  10145. shaderName = "legacydefault";
  10146. }
  10147. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10148. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10149. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10150. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10151. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10152. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10153. "vFogInfos", "vFogColor",
  10154. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10155. "mBones",
  10156. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10157. "darkness0", "darkness1", "darkness2", "darkness3",
  10158. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10159. ], [
  10160. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10161. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10162. ], join, fallbacks, this.onCompiled, this.onError);
  10163. }
  10164. if (!this._effect.isReady()) {
  10165. return false;
  10166. }
  10167. this._renderId = scene.getRenderId();
  10168. this._wasPreviouslyReady = true;
  10169. return true;
  10170. };
  10171. StandardMaterial.prototype.unbind = function () {
  10172. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10173. this._effect.setTexture("reflection2DSampler", null);
  10174. }
  10175. };
  10176. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10177. this._effect.setMatrix("world", world);
  10178. };
  10179. StandardMaterial.prototype.bind = function (world, mesh) {
  10180. var scene = this.getScene();
  10181. this.bindOnlyWorldMatrix(world);
  10182. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10183. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10184. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10185. }
  10186. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10187. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10188. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10189. }
  10190. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10191. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10192. }
  10193. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10194. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10195. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10196. }
  10197. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10198. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10199. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10200. }
  10201. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10202. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10203. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10204. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10205. }
  10206. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10207. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10208. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10209. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10210. }
  10211. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10212. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10213. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10214. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10215. }
  10216. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10217. if (this.reflectionTexture.isCube) {
  10218. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10219. } else {
  10220. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10221. }
  10222. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10223. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10224. }
  10225. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10226. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10227. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10228. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10229. }
  10230. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10231. this._effect.setTexture("specularSampler", this.specularTexture);
  10232. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10233. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10234. }
  10235. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10236. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10237. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10238. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10239. }
  10240. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10241. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10242. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10243. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10244. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10245. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10246. if (scene.lightsEnabled) {
  10247. var lightIndex = 0;
  10248. for (var index = 0; index < scene.lights.length; index++) {
  10249. var light = scene.lights[index];
  10250. if (!light.isEnabled()) {
  10251. continue;
  10252. }
  10253. if (!light.canAffectMesh(mesh)) {
  10254. continue;
  10255. }
  10256. if (light instanceof BABYLON.PointLight) {
  10257. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10258. } else if (light instanceof BABYLON.DirectionalLight) {
  10259. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10260. } else if (light instanceof BABYLON.SpotLight) {
  10261. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10262. } else if (light instanceof BABYLON.HemisphericLight) {
  10263. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10264. }
  10265. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10266. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10267. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10268. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10269. var shadowGenerator = light.getShadowGenerator();
  10270. if (mesh.receiveShadows && shadowGenerator) {
  10271. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10272. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10273. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10274. }
  10275. lightIndex++;
  10276. if (lightIndex == maxSimultaneousLights)
  10277. break;
  10278. }
  10279. }
  10280. if (scene.clipPlane) {
  10281. var clipPlane = scene.clipPlane;
  10282. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10283. }
  10284. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10285. this._effect.setMatrix("view", scene.getViewMatrix());
  10286. }
  10287. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10288. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10289. this._effect.setColor3("vFogColor", scene.fogColor);
  10290. }
  10291. };
  10292. StandardMaterial.prototype.getAnimatables = function () {
  10293. var results = [];
  10294. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10295. results.push(this.diffuseTexture);
  10296. }
  10297. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10298. results.push(this.ambientTexture);
  10299. }
  10300. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10301. results.push(this.opacityTexture);
  10302. }
  10303. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10304. results.push(this.reflectionTexture);
  10305. }
  10306. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10307. results.push(this.emissiveTexture);
  10308. }
  10309. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10310. results.push(this.specularTexture);
  10311. }
  10312. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10313. results.push(this.bumpTexture);
  10314. }
  10315. return results;
  10316. };
  10317. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10318. if (this.diffuseTexture) {
  10319. this.diffuseTexture.dispose();
  10320. }
  10321. if (this.ambientTexture) {
  10322. this.ambientTexture.dispose();
  10323. }
  10324. if (this.opacityTexture) {
  10325. this.opacityTexture.dispose();
  10326. }
  10327. if (this.reflectionTexture) {
  10328. this.reflectionTexture.dispose();
  10329. }
  10330. if (this.emissiveTexture) {
  10331. this.emissiveTexture.dispose();
  10332. }
  10333. if (this.specularTexture) {
  10334. this.specularTexture.dispose();
  10335. }
  10336. if (this.bumpTexture) {
  10337. this.bumpTexture.dispose();
  10338. }
  10339. _super.prototype.dispose.call(this, forceDisposeEffect);
  10340. };
  10341. StandardMaterial.prototype.clone = function (name) {
  10342. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10343. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10344. newStandardMaterial.alpha = this.alpha;
  10345. newStandardMaterial.wireframe = this.wireframe;
  10346. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10347. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10348. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10349. }
  10350. if (this.ambientTexture && this.ambientTexture.clone) {
  10351. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10352. }
  10353. if (this.opacityTexture && this.opacityTexture.clone) {
  10354. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10355. }
  10356. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10357. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10358. }
  10359. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10360. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10361. }
  10362. if (this.specularTexture && this.specularTexture.clone) {
  10363. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10364. }
  10365. if (this.bumpTexture && this.bumpTexture.clone) {
  10366. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10367. }
  10368. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10369. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10370. newStandardMaterial.specularColor = this.specularColor.clone();
  10371. newStandardMaterial.specularPower = this.specularPower;
  10372. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10373. return newStandardMaterial;
  10374. };
  10375. StandardMaterial.DiffuseTextureEnabled = true;
  10376. StandardMaterial.AmbientTextureEnabled = true;
  10377. StandardMaterial.OpacityTextureEnabled = true;
  10378. StandardMaterial.ReflectionTextureEnabled = true;
  10379. StandardMaterial.EmissiveTextureEnabled = true;
  10380. StandardMaterial.SpecularTextureEnabled = true;
  10381. StandardMaterial.BumpTextureEnabled = true;
  10382. return StandardMaterial;
  10383. })(BABYLON.Material);
  10384. BABYLON.StandardMaterial = StandardMaterial;
  10385. })(BABYLON || (BABYLON = {}));
  10386. var __extends = this.__extends || function (d, b) {
  10387. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10388. function __() { this.constructor = d; }
  10389. __.prototype = b.prototype;
  10390. d.prototype = new __();
  10391. };
  10392. var BABYLON;
  10393. (function (BABYLON) {
  10394. var MultiMaterial = (function (_super) {
  10395. __extends(MultiMaterial, _super);
  10396. function MultiMaterial(name, scene) {
  10397. _super.call(this, name, scene, true);
  10398. this.subMaterials = new Array();
  10399. scene.multiMaterials.push(this);
  10400. }
  10401. MultiMaterial.prototype.getSubMaterial = function (index) {
  10402. if (index < 0 || index >= this.subMaterials.length) {
  10403. return this.getScene().defaultMaterial;
  10404. }
  10405. return this.subMaterials[index];
  10406. };
  10407. MultiMaterial.prototype.isReady = function (mesh) {
  10408. for (var index = 0; index < this.subMaterials.length; index++) {
  10409. var subMaterial = this.subMaterials[index];
  10410. if (subMaterial) {
  10411. if (!this.subMaterials[index].isReady(mesh)) {
  10412. return false;
  10413. }
  10414. }
  10415. }
  10416. return true;
  10417. };
  10418. return MultiMaterial;
  10419. })(BABYLON.Material);
  10420. BABYLON.MultiMaterial = MultiMaterial;
  10421. })(BABYLON || (BABYLON = {}));
  10422. var BABYLON;
  10423. (function (BABYLON) {
  10424. var Database = (function () {
  10425. function Database(urlToScene, callbackManifestChecked) {
  10426. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10427. this.callbackManifestChecked = callbackManifestChecked;
  10428. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10429. this.db = null;
  10430. this.enableSceneOffline = false;
  10431. this.enableTexturesOffline = false;
  10432. this.manifestVersionFound = 0;
  10433. this.mustUpdateRessources = false;
  10434. this.hasReachedQuota = false;
  10435. this.checkManifestFile();
  10436. }
  10437. Database.prototype.checkManifestFile = function () {
  10438. var _this = this;
  10439. function noManifestFile() {
  10440. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10441. that.enableSceneOffline = false;
  10442. that.enableTexturesOffline = false;
  10443. that.callbackManifestChecked(false);
  10444. }
  10445. var that = this;
  10446. var manifestURL = this.currentSceneUrl + ".manifest";
  10447. var xhr = new XMLHttpRequest();
  10448. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10449. xhr.open("GET", manifestURLTimeStamped, true);
  10450. xhr.addEventListener("load", function () {
  10451. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10452. try {
  10453. var manifestFile = JSON.parse(xhr.response);
  10454. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10455. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10456. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10457. _this.manifestVersionFound = manifestFile.version;
  10458. }
  10459. if (_this.callbackManifestChecked) {
  10460. _this.callbackManifestChecked(true);
  10461. }
  10462. } catch (ex) {
  10463. noManifestFile();
  10464. }
  10465. } else {
  10466. noManifestFile();
  10467. }
  10468. }, false);
  10469. xhr.addEventListener("error", function (event) {
  10470. noManifestFile();
  10471. }, false);
  10472. try {
  10473. xhr.send();
  10474. } catch (ex) {
  10475. BABYLON.Tools.Error("Error on XHR send request.");
  10476. that.callbackManifestChecked(false);
  10477. }
  10478. };
  10479. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10480. var _this = this;
  10481. function handleError() {
  10482. that.isSupported = false;
  10483. if (errorCallback)
  10484. errorCallback();
  10485. }
  10486. var that = this;
  10487. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10488. this.isSupported = false;
  10489. if (errorCallback)
  10490. errorCallback();
  10491. } else {
  10492. if (!this.db) {
  10493. this.hasReachedQuota = false;
  10494. this.isSupported = true;
  10495. var request = this.idbFactory.open("babylonjs", 1);
  10496. request.onerror = function (event) {
  10497. handleError();
  10498. };
  10499. request.onblocked = function (event) {
  10500. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10501. handleError();
  10502. };
  10503. request.onsuccess = function (event) {
  10504. _this.db = request.result;
  10505. successCallback();
  10506. };
  10507. request.onupgradeneeded = function (event) {
  10508. _this.db = (event.target).result;
  10509. try {
  10510. if (event.oldVersion > 0) {
  10511. _this.db.deleteObjectStore("scenes");
  10512. _this.db.deleteObjectStore("versions");
  10513. _this.db.deleteObjectStore("textures");
  10514. }
  10515. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10516. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10517. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10518. } catch (ex) {
  10519. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10520. handleError();
  10521. }
  10522. };
  10523. } else {
  10524. if (successCallback)
  10525. successCallback();
  10526. }
  10527. }
  10528. };
  10529. Database.prototype.loadImageFromDB = function (url, image) {
  10530. var _this = this;
  10531. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10532. var saveAndLoadImage = function () {
  10533. if (!_this.hasReachedQuota && _this.db !== null) {
  10534. _this._saveImageIntoDBAsync(completeURL, image);
  10535. } else {
  10536. image.src = url;
  10537. }
  10538. };
  10539. if (!this.mustUpdateRessources) {
  10540. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10541. } else {
  10542. saveAndLoadImage();
  10543. }
  10544. };
  10545. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10546. if (this.isSupported && this.db !== null) {
  10547. var texture;
  10548. var transaction = this.db.transaction(["textures"]);
  10549. transaction.onabort = function (event) {
  10550. image.src = url;
  10551. };
  10552. transaction.oncomplete = function (event) {
  10553. var blobTextureURL;
  10554. if (texture) {
  10555. var URL = window.URL || window.webkitURL;
  10556. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10557. image.onerror = function () {
  10558. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10559. image.src = url;
  10560. };
  10561. image.src = blobTextureURL;
  10562. } else {
  10563. notInDBCallback();
  10564. }
  10565. };
  10566. var getRequest = transaction.objectStore("textures").get(url);
  10567. getRequest.onsuccess = function (event) {
  10568. texture = (event.target).result;
  10569. };
  10570. getRequest.onerror = function (event) {
  10571. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10572. image.src = url;
  10573. };
  10574. } else {
  10575. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10576. image.src = url;
  10577. }
  10578. };
  10579. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10580. var _this = this;
  10581. if (this.isSupported) {
  10582. var generateBlobUrl = function () {
  10583. var blobTextureURL;
  10584. if (blob) {
  10585. var URL = window.URL || window.webkitURL;
  10586. try {
  10587. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10588. } catch (ex) {
  10589. blobTextureURL = URL.createObjectURL(blob);
  10590. }
  10591. }
  10592. image.src = blobTextureURL;
  10593. };
  10594. if (BABYLON.Database.isUASupportingBlobStorage) {
  10595. var xhr = new XMLHttpRequest(), blob;
  10596. xhr.open("GET", url, true);
  10597. xhr.responseType = "blob";
  10598. xhr.addEventListener("load", function () {
  10599. if (xhr.status === 200) {
  10600. blob = xhr.response;
  10601. var transaction = _this.db.transaction(["textures"], "readwrite");
  10602. transaction.onabort = function (event) {
  10603. try {
  10604. if (event.srcElement.error.name === "QuotaExceededError") {
  10605. this.hasReachedQuota = true;
  10606. }
  10607. } catch (ex) {
  10608. }
  10609. generateBlobUrl();
  10610. };
  10611. transaction.oncomplete = function (event) {
  10612. generateBlobUrl();
  10613. };
  10614. var newTexture = { textureUrl: url, data: blob };
  10615. try {
  10616. var addRequest = transaction.objectStore("textures").put(newTexture);
  10617. addRequest.onsuccess = function (event) {
  10618. };
  10619. addRequest.onerror = function (event) {
  10620. generateBlobUrl();
  10621. };
  10622. } catch (ex) {
  10623. if (ex.code === 25) {
  10624. BABYLON.Database.isUASupportingBlobStorage = false;
  10625. }
  10626. image.src = url;
  10627. }
  10628. } else {
  10629. image.src = url;
  10630. }
  10631. }, false);
  10632. xhr.addEventListener("error", function (event) {
  10633. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10634. image.src = url;
  10635. }, false);
  10636. xhr.send();
  10637. } else {
  10638. image.src = url;
  10639. }
  10640. } else {
  10641. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10642. image.src = url;
  10643. }
  10644. };
  10645. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10646. var _this = this;
  10647. var updateVersion = function (event) {
  10648. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10649. };
  10650. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10651. };
  10652. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10653. var _this = this;
  10654. if (this.isSupported) {
  10655. var version;
  10656. try {
  10657. var transaction = this.db.transaction(["versions"]);
  10658. transaction.oncomplete = function (event) {
  10659. if (version) {
  10660. if (_this.manifestVersionFound > version.data) {
  10661. _this.mustUpdateRessources = true;
  10662. updateInDBCallback();
  10663. } else {
  10664. callback(version.data);
  10665. }
  10666. } else {
  10667. _this.mustUpdateRessources = true;
  10668. updateInDBCallback();
  10669. }
  10670. };
  10671. transaction.onabort = function (event) {
  10672. callback(-1);
  10673. };
  10674. var getRequest = transaction.objectStore("versions").get(url);
  10675. getRequest.onsuccess = function (event) {
  10676. version = (event.target).result;
  10677. };
  10678. getRequest.onerror = function (event) {
  10679. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10680. callback(-1);
  10681. };
  10682. } catch (ex) {
  10683. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10684. callback(-1);
  10685. }
  10686. } else {
  10687. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10688. callback(-1);
  10689. }
  10690. };
  10691. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10692. var _this = this;
  10693. if (this.isSupported && !this.hasReachedQuota) {
  10694. try {
  10695. var transaction = this.db.transaction(["versions"], "readwrite");
  10696. transaction.onabort = function (event) {
  10697. try {
  10698. if (event.srcElement.error.name === "QuotaExceededError") {
  10699. _this.hasReachedQuota = true;
  10700. }
  10701. } catch (ex) {
  10702. }
  10703. callback(-1);
  10704. };
  10705. transaction.oncomplete = function (event) {
  10706. callback(_this.manifestVersionFound);
  10707. };
  10708. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10709. var addRequest = transaction.objectStore("versions").put(newVersion);
  10710. addRequest.onsuccess = function (event) {
  10711. };
  10712. addRequest.onerror = function (event) {
  10713. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10714. };
  10715. } catch (ex) {
  10716. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10717. callback(-1);
  10718. }
  10719. } else {
  10720. callback(-1);
  10721. }
  10722. };
  10723. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10724. var _this = this;
  10725. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10726. var saveAndLoadFile = function (event) {
  10727. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10728. };
  10729. this._checkVersionFromDB(completeUrl, function (version) {
  10730. if (version !== -1) {
  10731. if (!_this.mustUpdateRessources) {
  10732. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10733. } else {
  10734. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10735. }
  10736. } else {
  10737. errorCallback();
  10738. }
  10739. });
  10740. };
  10741. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10742. if (this.isSupported) {
  10743. var targetStore;
  10744. if (url.indexOf(".babylon") !== -1) {
  10745. targetStore = "scenes";
  10746. } else {
  10747. targetStore = "textures";
  10748. }
  10749. var file;
  10750. var transaction = this.db.transaction([targetStore]);
  10751. transaction.oncomplete = function (event) {
  10752. if (file) {
  10753. callback(file.data);
  10754. } else {
  10755. notInDBCallback();
  10756. }
  10757. };
  10758. transaction.onabort = function (event) {
  10759. notInDBCallback();
  10760. };
  10761. var getRequest = transaction.objectStore(targetStore).get(url);
  10762. getRequest.onsuccess = function (event) {
  10763. file = (event.target).result;
  10764. };
  10765. getRequest.onerror = function (event) {
  10766. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10767. notInDBCallback();
  10768. };
  10769. } else {
  10770. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10771. callback();
  10772. }
  10773. };
  10774. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10775. var _this = this;
  10776. if (this.isSupported) {
  10777. var targetStore;
  10778. if (url.indexOf(".babylon") !== -1) {
  10779. targetStore = "scenes";
  10780. } else {
  10781. targetStore = "textures";
  10782. }
  10783. var xhr = new XMLHttpRequest(), fileData;
  10784. xhr.open("GET", url, true);
  10785. if (useArrayBuffer) {
  10786. xhr.responseType = "arraybuffer";
  10787. }
  10788. xhr.onprogress = progressCallback;
  10789. xhr.addEventListener("load", function () {
  10790. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10791. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10792. if (!_this.hasReachedQuota) {
  10793. var transaction = _this.db.transaction([targetStore], "readwrite");
  10794. transaction.onabort = function (event) {
  10795. try {
  10796. if (event.srcElement.error.name === "QuotaExceededError") {
  10797. this.hasReachedQuota = true;
  10798. }
  10799. } catch (ex) {
  10800. }
  10801. callback(fileData);
  10802. };
  10803. transaction.oncomplete = function (event) {
  10804. callback(fileData);
  10805. };
  10806. var newFile;
  10807. if (targetStore === "scenes") {
  10808. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10809. } else {
  10810. newFile = { textureUrl: url, data: fileData };
  10811. }
  10812. try {
  10813. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10814. addRequest.onsuccess = function (event) {
  10815. };
  10816. addRequest.onerror = function (event) {
  10817. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10818. };
  10819. } catch (ex) {
  10820. callback(fileData);
  10821. }
  10822. } else {
  10823. callback(fileData);
  10824. }
  10825. } else {
  10826. callback();
  10827. }
  10828. }, false);
  10829. xhr.addEventListener("error", function (event) {
  10830. BABYLON.Tools.Error("error on XHR request.");
  10831. callback();
  10832. }, false);
  10833. xhr.send();
  10834. } else {
  10835. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10836. callback();
  10837. }
  10838. };
  10839. Database.isUASupportingBlobStorage = true;
  10840. Database.parseURL = function (url) {
  10841. var a = document.createElement('a');
  10842. a.href = url;
  10843. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10844. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10845. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10846. return absLocation;
  10847. };
  10848. Database.ReturnFullUrlLocation = function (url) {
  10849. if (url.indexOf("http:/") === -1) {
  10850. return (BABYLON.Database.parseURL(window.location.href) + url);
  10851. } else {
  10852. return url;
  10853. }
  10854. };
  10855. return Database;
  10856. })();
  10857. BABYLON.Database = Database;
  10858. })(BABYLON || (BABYLON = {}));
  10859. var BABYLON;
  10860. (function (BABYLON) {
  10861. var SpriteManager = (function () {
  10862. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10863. this.name = name;
  10864. this.cellSize = cellSize;
  10865. this.sprites = new Array();
  10866. this.renderingGroupId = 0;
  10867. this._vertexDeclaration = [3, 4, 4, 4];
  10868. this._vertexStrideSize = 15 * 4;
  10869. this._capacity = capacity;
  10870. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10871. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10872. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10873. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10874. this._scene = scene;
  10875. this._scene.spriteManagers.push(this);
  10876. this._vertexDeclaration = [3, 4, 4, 4];
  10877. this._vertexStrideSize = 15 * 4;
  10878. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10879. var indices = [];
  10880. var index = 0;
  10881. for (var count = 0; count < capacity; count++) {
  10882. indices.push(index);
  10883. indices.push(index + 1);
  10884. indices.push(index + 2);
  10885. indices.push(index);
  10886. indices.push(index + 2);
  10887. indices.push(index + 3);
  10888. index += 4;
  10889. }
  10890. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10891. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  10892. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  10893. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  10894. }
  10895. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  10896. var arrayOffset = index * 15;
  10897. if (offsetX == 0)
  10898. offsetX = this._epsilon;
  10899. else if (offsetX == 1)
  10900. offsetX = 1 - this._epsilon;
  10901. if (offsetY == 0)
  10902. offsetY = this._epsilon;
  10903. else if (offsetY == 1)
  10904. offsetY = 1 - this._epsilon;
  10905. this._vertices[arrayOffset] = sprite.position.x;
  10906. this._vertices[arrayOffset + 1] = sprite.position.y;
  10907. this._vertices[arrayOffset + 2] = sprite.position.z;
  10908. this._vertices[arrayOffset + 3] = sprite.angle;
  10909. this._vertices[arrayOffset + 4] = sprite.size;
  10910. this._vertices[arrayOffset + 5] = offsetX;
  10911. this._vertices[arrayOffset + 6] = offsetY;
  10912. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  10913. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  10914. var offset = (sprite.cellIndex / rowSize) >> 0;
  10915. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  10916. this._vertices[arrayOffset + 10] = offset;
  10917. this._vertices[arrayOffset + 11] = sprite.color.r;
  10918. this._vertices[arrayOffset + 12] = sprite.color.g;
  10919. this._vertices[arrayOffset + 13] = sprite.color.b;
  10920. this._vertices[arrayOffset + 14] = sprite.color.a;
  10921. };
  10922. SpriteManager.prototype.render = function () {
  10923. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  10924. return;
  10925. var engine = this._scene.getEngine();
  10926. var baseSize = this._spriteTexture.getBaseSize();
  10927. var deltaTime = BABYLON.Tools.GetDeltaTime();
  10928. var max = Math.min(this._capacity, this.sprites.length);
  10929. var rowSize = baseSize.width / this.cellSize;
  10930. var offset = 0;
  10931. for (var index = 0; index < max; index++) {
  10932. var sprite = this.sprites[index];
  10933. if (!sprite) {
  10934. continue;
  10935. }
  10936. sprite._animate(deltaTime);
  10937. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  10938. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  10939. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  10940. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  10941. }
  10942. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  10943. var effect = this._effectBase;
  10944. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10945. effect = this._effectFog;
  10946. }
  10947. engine.enableEffect(effect);
  10948. var viewMatrix = this._scene.getViewMatrix();
  10949. effect.setTexture("diffuseSampler", this._spriteTexture);
  10950. effect.setMatrix("view", viewMatrix);
  10951. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  10952. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  10953. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10954. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  10955. effect.setColor3("vFogColor", this._scene.fogColor);
  10956. }
  10957. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  10958. effect.setBool("alphaTest", true);
  10959. engine.setColorWrite(false);
  10960. engine.draw(true, 0, max * 6);
  10961. engine.setColorWrite(true);
  10962. effect.setBool("alphaTest", false);
  10963. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10964. engine.draw(true, 0, max * 6);
  10965. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10966. };
  10967. SpriteManager.prototype.dispose = function () {
  10968. if (this._vertexBuffer) {
  10969. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  10970. this._vertexBuffer = null;
  10971. }
  10972. if (this._indexBuffer) {
  10973. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  10974. this._indexBuffer = null;
  10975. }
  10976. if (this._spriteTexture) {
  10977. this._spriteTexture.dispose();
  10978. this._spriteTexture = null;
  10979. }
  10980. var index = this._scene.spriteManagers.indexOf(this);
  10981. this._scene.spriteManagers.splice(index, 1);
  10982. if (this.onDispose) {
  10983. this.onDispose();
  10984. }
  10985. };
  10986. return SpriteManager;
  10987. })();
  10988. BABYLON.SpriteManager = SpriteManager;
  10989. })(BABYLON || (BABYLON = {}));
  10990. var BABYLON;
  10991. (function (BABYLON) {
  10992. var Sprite = (function () {
  10993. function Sprite(name, manager) {
  10994. this.name = name;
  10995. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  10996. this.size = 1.0;
  10997. this.angle = 0;
  10998. this.cellIndex = 0;
  10999. this.invertU = 0;
  11000. this.invertV = 0;
  11001. this.animations = new Array();
  11002. this._animationStarted = false;
  11003. this._loopAnimation = false;
  11004. this._fromIndex = 0;
  11005. this._toIndex = 0;
  11006. this._delay = 0;
  11007. this._direction = 1;
  11008. this._frameCount = 0;
  11009. this._time = 0;
  11010. this._manager = manager;
  11011. this._manager.sprites.push(this);
  11012. this.position = BABYLON.Vector3.Zero();
  11013. }
  11014. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11015. this._fromIndex = from;
  11016. this._toIndex = to;
  11017. this._loopAnimation = loop;
  11018. this._delay = delay;
  11019. this._animationStarted = true;
  11020. this._direction = from < to ? 1 : -1;
  11021. this.cellIndex = from;
  11022. this._time = 0;
  11023. };
  11024. Sprite.prototype.stopAnimation = function () {
  11025. this._animationStarted = false;
  11026. };
  11027. Sprite.prototype._animate = function (deltaTime) {
  11028. if (!this._animationStarted)
  11029. return;
  11030. this._time += deltaTime;
  11031. if (this._time > this._delay) {
  11032. this._time = this._time % this._delay;
  11033. this.cellIndex += this._direction;
  11034. if (this.cellIndex == this._toIndex) {
  11035. if (this._loopAnimation) {
  11036. this.cellIndex = this._fromIndex;
  11037. } else {
  11038. this._animationStarted = false;
  11039. if (this.disposeWhenFinishedAnimating) {
  11040. this.dispose();
  11041. }
  11042. }
  11043. }
  11044. }
  11045. };
  11046. Sprite.prototype.dispose = function () {
  11047. for (var i = 0; i < this._manager.sprites.length; i++) {
  11048. if (this._manager.sprites[i] == this) {
  11049. this._manager.sprites.splice(i, 1);
  11050. }
  11051. }
  11052. };
  11053. return Sprite;
  11054. })();
  11055. BABYLON.Sprite = Sprite;
  11056. })(BABYLON || (BABYLON = {}));
  11057. var BABYLON;
  11058. (function (BABYLON) {
  11059. var Layer = (function () {
  11060. function Layer(name, imgUrl, scene, isBackground, color) {
  11061. this.name = name;
  11062. this._vertexDeclaration = [2];
  11063. this._vertexStrideSize = 2 * 4;
  11064. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11065. this.isBackground = isBackground === undefined ? true : isBackground;
  11066. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11067. this._scene = scene;
  11068. this._scene.layers.push(this);
  11069. var vertices = [];
  11070. vertices.push(1, 1);
  11071. vertices.push(-1, 1);
  11072. vertices.push(-1, -1);
  11073. vertices.push(1, -1);
  11074. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11075. var indices = [];
  11076. indices.push(0);
  11077. indices.push(1);
  11078. indices.push(2);
  11079. indices.push(0);
  11080. indices.push(2);
  11081. indices.push(3);
  11082. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11083. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11084. }
  11085. Layer.prototype.render = function () {
  11086. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11087. return;
  11088. var engine = this._scene.getEngine();
  11089. engine.enableEffect(this._effect);
  11090. engine.setState(false);
  11091. this._effect.setTexture("textureSampler", this.texture);
  11092. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11093. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11094. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11095. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11096. engine.draw(true, 0, 6);
  11097. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11098. };
  11099. Layer.prototype.dispose = function () {
  11100. if (this._vertexBuffer) {
  11101. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11102. this._vertexBuffer = null;
  11103. }
  11104. if (this._indexBuffer) {
  11105. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11106. this._indexBuffer = null;
  11107. }
  11108. if (this.texture) {
  11109. this.texture.dispose();
  11110. this.texture = null;
  11111. }
  11112. var index = this._scene.layers.indexOf(this);
  11113. this._scene.layers.splice(index, 1);
  11114. if (this.onDispose) {
  11115. this.onDispose();
  11116. }
  11117. };
  11118. return Layer;
  11119. })();
  11120. BABYLON.Layer = Layer;
  11121. })(BABYLON || (BABYLON = {}));
  11122. var BABYLON;
  11123. (function (BABYLON) {
  11124. var Particle = (function () {
  11125. function Particle() {
  11126. this.position = BABYLON.Vector3.Zero();
  11127. this.direction = BABYLON.Vector3.Zero();
  11128. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11129. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11130. this.lifeTime = 1.0;
  11131. this.age = 0;
  11132. this.size = 0;
  11133. this.angle = 0;
  11134. this.angularSpeed = 0;
  11135. }
  11136. return Particle;
  11137. })();
  11138. BABYLON.Particle = Particle;
  11139. })(BABYLON || (BABYLON = {}));
  11140. var BABYLON;
  11141. (function (BABYLON) {
  11142. var randomNumber = function (min, max) {
  11143. if (min == max) {
  11144. return (min);
  11145. }
  11146. var random = Math.random();
  11147. return ((random * (max - min)) + min);
  11148. };
  11149. var ParticleSystem = (function () {
  11150. function ParticleSystem(name, capacity, scene, fragmentElement) {
  11151. var _this = this;
  11152. this.name = name;
  11153. this.fragmentElement = fragmentElement;
  11154. this.renderingGroupId = 0;
  11155. this.emitter = null;
  11156. this.emitRate = 10;
  11157. this.manualEmitCount = -1;
  11158. this.updateSpeed = 0.01;
  11159. this.targetStopDuration = 0;
  11160. this.disposeOnStop = false;
  11161. this.minEmitPower = 1;
  11162. this.maxEmitPower = 1;
  11163. this.minLifeTime = 1;
  11164. this.maxLifeTime = 1;
  11165. this.minSize = 1;
  11166. this.maxSize = 1;
  11167. this.minAngularSpeed = 0;
  11168. this.maxAngularSpeed = 0;
  11169. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11170. this.forceDepthWrite = false;
  11171. this.gravity = BABYLON.Vector3.Zero();
  11172. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11173. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11174. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11175. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11176. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11177. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11178. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11179. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11180. this.particles = new Array();
  11181. this._vertexDeclaration = [3, 4, 4];
  11182. this._vertexStrideSize = 11 * 4;
  11183. this._stockParticles = new Array();
  11184. this._newPartsExcess = 0;
  11185. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11186. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11187. this._scaledDirection = BABYLON.Vector3.Zero();
  11188. this._scaledGravity = BABYLON.Vector3.Zero();
  11189. this._currentRenderId = -1;
  11190. this._started = false;
  11191. this._stopped = false;
  11192. this._actualFrame = 0;
  11193. this.id = name;
  11194. this._capacity = capacity;
  11195. this._scene = scene;
  11196. scene.particleSystems.push(this);
  11197. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11198. var indices = [];
  11199. var index = 0;
  11200. for (var count = 0; count < capacity; count++) {
  11201. indices.push(index);
  11202. indices.push(index + 1);
  11203. indices.push(index + 2);
  11204. indices.push(index);
  11205. indices.push(index + 2);
  11206. indices.push(index + 3);
  11207. index += 4;
  11208. }
  11209. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11210. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11211. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11212. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11213. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11214. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11215. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11216. };
  11217. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11218. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11219. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11220. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11221. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11222. };
  11223. }
  11224. ParticleSystem.prototype.getCapacity = function () {
  11225. return this._capacity;
  11226. };
  11227. ParticleSystem.prototype.isAlive = function () {
  11228. return this._alive;
  11229. };
  11230. ParticleSystem.prototype.isStarted = function () {
  11231. return this._started;
  11232. };
  11233. ParticleSystem.prototype.start = function () {
  11234. this._started = true;
  11235. this._stopped = false;
  11236. this._actualFrame = 0;
  11237. };
  11238. ParticleSystem.prototype.stop = function () {
  11239. this._stopped = true;
  11240. };
  11241. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11242. var offset = index * 11;
  11243. this._vertices[offset] = particle.position.x;
  11244. this._vertices[offset + 1] = particle.position.y;
  11245. this._vertices[offset + 2] = particle.position.z;
  11246. this._vertices[offset + 3] = particle.color.r;
  11247. this._vertices[offset + 4] = particle.color.g;
  11248. this._vertices[offset + 5] = particle.color.b;
  11249. this._vertices[offset + 6] = particle.color.a;
  11250. this._vertices[offset + 7] = particle.angle;
  11251. this._vertices[offset + 8] = particle.size;
  11252. this._vertices[offset + 9] = offsetX;
  11253. this._vertices[offset + 10] = offsetY;
  11254. };
  11255. ParticleSystem.prototype._update = function (newParticles) {
  11256. this._alive = this.particles.length > 0;
  11257. for (var index = 0; index < this.particles.length; index++) {
  11258. var particle = this.particles[index];
  11259. particle.age += this._scaledUpdateSpeed;
  11260. if (particle.age >= particle.lifeTime) {
  11261. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11262. index--;
  11263. continue;
  11264. } else {
  11265. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11266. particle.color.addInPlace(this._scaledColorStep);
  11267. if (particle.color.a < 0)
  11268. particle.color.a = 0;
  11269. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11270. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11271. particle.position.addInPlace(this._scaledDirection);
  11272. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11273. particle.direction.addInPlace(this._scaledGravity);
  11274. }
  11275. }
  11276. var worldMatrix;
  11277. if (this.emitter.position) {
  11278. worldMatrix = this.emitter.getWorldMatrix();
  11279. } else {
  11280. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11281. }
  11282. for (index = 0; index < newParticles; index++) {
  11283. if (this.particles.length == this._capacity) {
  11284. break;
  11285. }
  11286. if (this._stockParticles.length !== 0) {
  11287. particle = this._stockParticles.pop();
  11288. particle.age = 0;
  11289. } else {
  11290. particle = new BABYLON.Particle();
  11291. }
  11292. this.particles.push(particle);
  11293. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11294. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11295. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11296. particle.size = randomNumber(this.minSize, this.maxSize);
  11297. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11298. this.startPositionFunction(worldMatrix, particle.position);
  11299. var step = randomNumber(0, 1.0);
  11300. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11301. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11302. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11303. }
  11304. };
  11305. ParticleSystem.prototype._getEffect = function () {
  11306. var defines = [];
  11307. if (this._scene.clipPlane) {
  11308. defines.push("#define CLIPPLANE");
  11309. }
  11310. var join = defines.join("\n");
  11311. if (this._cachedDefines != join) {
  11312. this._cachedDefines = join;
  11313. var baseName;
  11314. if (this.fragmentElement) {
  11315. baseName = {
  11316. vertex: "particles",
  11317. fragmentElement: this.fragmentElement
  11318. };
  11319. } else {
  11320. baseName = "particles";
  11321. }
  11322. this._effect = this._scene.getEngine().createEffect(baseName, ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11323. }
  11324. return this._effect;
  11325. };
  11326. ParticleSystem.prototype.animate = function () {
  11327. if (!this._started)
  11328. return;
  11329. var effect = this._getEffect();
  11330. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11331. return;
  11332. if (this._currentRenderId === this._scene.getRenderId()) {
  11333. return;
  11334. }
  11335. this._currentRenderId = this._scene.getRenderId();
  11336. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11337. var emitCout;
  11338. if (this.manualEmitCount > -1) {
  11339. emitCout = this.manualEmitCount;
  11340. this.manualEmitCount = 0;
  11341. } else {
  11342. emitCout = this.emitRate;
  11343. }
  11344. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11345. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11346. if (this._newPartsExcess > 1.0) {
  11347. newParticles += this._newPartsExcess >> 0;
  11348. this._newPartsExcess -= this._newPartsExcess >> 0;
  11349. }
  11350. this._alive = false;
  11351. if (!this._stopped) {
  11352. this._actualFrame += this._scaledUpdateSpeed;
  11353. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11354. this.stop();
  11355. } else {
  11356. newParticles = 0;
  11357. }
  11358. this._update(newParticles);
  11359. if (this._stopped) {
  11360. if (!this._alive) {
  11361. this._started = false;
  11362. if (this.disposeOnStop) {
  11363. this._scene._toBeDisposed.push(this);
  11364. }
  11365. }
  11366. }
  11367. var offset = 0;
  11368. for (var index = 0; index < this.particles.length; index++) {
  11369. var particle = this.particles[index];
  11370. this._appendParticleVertex(offset++, particle, 0, 0);
  11371. this._appendParticleVertex(offset++, particle, 1, 0);
  11372. this._appendParticleVertex(offset++, particle, 1, 1);
  11373. this._appendParticleVertex(offset++, particle, 0, 1);
  11374. }
  11375. var engine = this._scene.getEngine();
  11376. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11377. };
  11378. ParticleSystem.prototype.render = function () {
  11379. var effect = this._getEffect();
  11380. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11381. return 0;
  11382. var engine = this._scene.getEngine();
  11383. engine.enableEffect(effect);
  11384. var viewMatrix = this._scene.getViewMatrix();
  11385. effect.setTexture("diffuseSampler", this.particleTexture);
  11386. effect.setMatrix("view", viewMatrix);
  11387. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11388. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11389. if (this._scene.clipPlane) {
  11390. var clipPlane = this._scene.clipPlane;
  11391. var invView = viewMatrix.clone();
  11392. invView.invert();
  11393. effect.setMatrix("invView", invView);
  11394. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11395. }
  11396. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11397. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11398. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11399. } else {
  11400. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11401. }
  11402. if (this.forceDepthWrite) {
  11403. engine.setDepthWrite(true);
  11404. }
  11405. engine.draw(true, 0, this.particles.length * 6);
  11406. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11407. return this.particles.length;
  11408. };
  11409. ParticleSystem.prototype.dispose = function () {
  11410. if (this._vertexBuffer) {
  11411. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11412. this._vertexBuffer = null;
  11413. }
  11414. if (this._indexBuffer) {
  11415. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11416. this._indexBuffer = null;
  11417. }
  11418. if (this.particleTexture) {
  11419. this.particleTexture.dispose();
  11420. this.particleTexture = null;
  11421. }
  11422. var index = this._scene.particleSystems.indexOf(this);
  11423. this._scene.particleSystems.splice(index, 1);
  11424. if (this.onDispose) {
  11425. this.onDispose();
  11426. }
  11427. };
  11428. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11429. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11430. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11431. if (newEmitter === undefined) {
  11432. newEmitter = this.emitter;
  11433. }
  11434. result.emitter = newEmitter;
  11435. if (this.particleTexture) {
  11436. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11437. }
  11438. result.start();
  11439. return result;
  11440. };
  11441. ParticleSystem.BLENDMODE_ONEONE = 0;
  11442. ParticleSystem.BLENDMODE_STANDARD = 1;
  11443. return ParticleSystem;
  11444. })();
  11445. BABYLON.ParticleSystem = ParticleSystem;
  11446. })(BABYLON || (BABYLON = {}));
  11447. var BABYLON;
  11448. (function (BABYLON) {
  11449. var Animation = (function () {
  11450. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11451. this.name = name;
  11452. this.targetProperty = targetProperty;
  11453. this.framePerSecond = framePerSecond;
  11454. this.dataType = dataType;
  11455. this.loopMode = loopMode;
  11456. this._offsetsCache = {};
  11457. this._highLimitsCache = {};
  11458. this._stopped = false;
  11459. this.targetPropertyPath = targetProperty.split(".");
  11460. this.dataType = dataType;
  11461. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11462. }
  11463. Animation.prototype.isStopped = function () {
  11464. return this._stopped;
  11465. };
  11466. Animation.prototype.getKeys = function () {
  11467. return this._keys;
  11468. };
  11469. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11470. return startValue + (endValue - startValue) * gradient;
  11471. };
  11472. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11473. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11474. };
  11475. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11476. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11477. };
  11478. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11479. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11480. };
  11481. Animation.prototype.clone = function () {
  11482. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11483. clone.setKeys(this._keys);
  11484. return clone;
  11485. };
  11486. Animation.prototype.setKeys = function (values) {
  11487. this._keys = values.slice(0);
  11488. this._offsetsCache = {};
  11489. this._highLimitsCache = {};
  11490. };
  11491. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11492. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11493. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11494. }
  11495. this.currentFrame = currentFrame;
  11496. for (var key = 0; key < this._keys.length; key++) {
  11497. if (this._keys[key + 1].frame >= currentFrame) {
  11498. var startValue = this._keys[key].value;
  11499. var endValue = this._keys[key + 1].value;
  11500. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11501. switch (this.dataType) {
  11502. case Animation.ANIMATIONTYPE_FLOAT:
  11503. switch (loopMode) {
  11504. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11505. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11506. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11507. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11508. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11509. }
  11510. break;
  11511. case Animation.ANIMATIONTYPE_QUATERNION:
  11512. var quaternion = null;
  11513. switch (loopMode) {
  11514. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11515. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11516. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11517. break;
  11518. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11519. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11520. break;
  11521. }
  11522. return quaternion;
  11523. case Animation.ANIMATIONTYPE_VECTOR3:
  11524. switch (loopMode) {
  11525. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11526. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11527. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11528. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11529. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11530. }
  11531. case Animation.ANIMATIONTYPE_COLOR3:
  11532. switch (loopMode) {
  11533. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11534. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11535. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11536. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11537. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11538. }
  11539. case Animation.ANIMATIONTYPE_MATRIX:
  11540. switch (loopMode) {
  11541. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11542. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11543. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11544. return startValue;
  11545. }
  11546. default:
  11547. break;
  11548. }
  11549. break;
  11550. }
  11551. }
  11552. return this._keys[this._keys.length - 1].value;
  11553. };
  11554. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11555. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11556. this._stopped = true;
  11557. return false;
  11558. }
  11559. var returnValue = true;
  11560. if (this._keys[0].frame != 0) {
  11561. var newKey = {
  11562. frame: 0,
  11563. value: this._keys[0].value
  11564. };
  11565. this._keys.splice(0, 0, newKey);
  11566. }
  11567. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11568. from = this._keys[0].frame;
  11569. }
  11570. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11571. to = this._keys[this._keys.length - 1].frame;
  11572. }
  11573. var range = to - from;
  11574. var offsetValue;
  11575. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11576. if (ratio > range && !loop) {
  11577. returnValue = false;
  11578. highLimitValue = this._keys[this._keys.length - 1].value;
  11579. } else {
  11580. var highLimitValue = 0;
  11581. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11582. var keyOffset = to.toString() + from.toString();
  11583. if (!this._offsetsCache[keyOffset]) {
  11584. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11585. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11586. switch (this.dataType) {
  11587. case Animation.ANIMATIONTYPE_FLOAT:
  11588. this._offsetsCache[keyOffset] = toValue - fromValue;
  11589. break;
  11590. case Animation.ANIMATIONTYPE_QUATERNION:
  11591. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11592. break;
  11593. case Animation.ANIMATIONTYPE_VECTOR3:
  11594. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11595. case Animation.ANIMATIONTYPE_COLOR3:
  11596. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11597. default:
  11598. break;
  11599. }
  11600. this._highLimitsCache[keyOffset] = toValue;
  11601. }
  11602. highLimitValue = this._highLimitsCache[keyOffset];
  11603. offsetValue = this._offsetsCache[keyOffset];
  11604. }
  11605. }
  11606. if (offsetValue === undefined) {
  11607. switch (this.dataType) {
  11608. case Animation.ANIMATIONTYPE_FLOAT:
  11609. offsetValue = 0;
  11610. break;
  11611. case Animation.ANIMATIONTYPE_QUATERNION:
  11612. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11613. break;
  11614. case Animation.ANIMATIONTYPE_VECTOR3:
  11615. offsetValue = BABYLON.Vector3.Zero();
  11616. break;
  11617. case Animation.ANIMATIONTYPE_COLOR3:
  11618. offsetValue = BABYLON.Color3.Black();
  11619. }
  11620. }
  11621. var repeatCount = (ratio / range) >> 0;
  11622. var currentFrame = returnValue ? from + ratio % range : to;
  11623. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11624. if (this.targetPropertyPath.length > 1) {
  11625. var property = this._target[this.targetPropertyPath[0]];
  11626. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11627. property = property[this.targetPropertyPath[index]];
  11628. }
  11629. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11630. } else {
  11631. this._target[this.targetPropertyPath[0]] = currentValue;
  11632. }
  11633. if (this._target.markAsDirty) {
  11634. this._target.markAsDirty(this.targetProperty);
  11635. }
  11636. if (!returnValue) {
  11637. this._stopped = true;
  11638. }
  11639. return returnValue;
  11640. };
  11641. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11642. get: function () {
  11643. return Animation._ANIMATIONTYPE_FLOAT;
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11649. get: function () {
  11650. return Animation._ANIMATIONTYPE_VECTOR3;
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11656. get: function () {
  11657. return Animation._ANIMATIONTYPE_QUATERNION;
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11663. get: function () {
  11664. return Animation._ANIMATIONTYPE_MATRIX;
  11665. },
  11666. enumerable: true,
  11667. configurable: true
  11668. });
  11669. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11670. get: function () {
  11671. return Animation._ANIMATIONTYPE_COLOR3;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11677. get: function () {
  11678. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11679. },
  11680. enumerable: true,
  11681. configurable: true
  11682. });
  11683. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11684. get: function () {
  11685. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11691. get: function () {
  11692. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11693. },
  11694. enumerable: true,
  11695. configurable: true
  11696. });
  11697. Animation._ANIMATIONTYPE_FLOAT = 0;
  11698. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11699. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11700. Animation._ANIMATIONTYPE_MATRIX = 3;
  11701. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11702. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11703. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11704. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11705. return Animation;
  11706. })();
  11707. BABYLON.Animation = Animation;
  11708. })(BABYLON || (BABYLON = {}));
  11709. var BABYLON;
  11710. (function (BABYLON) {
  11711. var Animatable = (function () {
  11712. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11713. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11714. if (typeof toFrame === "undefined") { toFrame = 100; }
  11715. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11716. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11717. this.target = target;
  11718. this.fromFrame = fromFrame;
  11719. this.toFrame = toFrame;
  11720. this.loopAnimation = loopAnimation;
  11721. this.speedRatio = speedRatio;
  11722. this.onAnimationEnd = onAnimationEnd;
  11723. this._animations = new Array();
  11724. this._paused = false;
  11725. this.animationStarted = false;
  11726. if (animations) {
  11727. this.appendAnimations(target, animations);
  11728. }
  11729. this._scene = scene;
  11730. scene._activeAnimatables.push(this);
  11731. }
  11732. Animatable.prototype.appendAnimations = function (target, animations) {
  11733. for (var index = 0; index < animations.length; index++) {
  11734. var animation = animations[index];
  11735. animation._target = target;
  11736. this._animations.push(animation);
  11737. }
  11738. };
  11739. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11740. var animations = this._animations;
  11741. for (var index = 0; index < animations.length; index++) {
  11742. if (animations[index].targetProperty === property) {
  11743. return animations[index];
  11744. }
  11745. }
  11746. return null;
  11747. };
  11748. Animatable.prototype.pause = function () {
  11749. this._paused = true;
  11750. };
  11751. Animatable.prototype.restart = function () {
  11752. this._paused = false;
  11753. };
  11754. Animatable.prototype.stop = function () {
  11755. var index = this._scene._activeAnimatables.indexOf(this);
  11756. if (index > -1) {
  11757. this._scene._activeAnimatables.splice(index, 1);
  11758. }
  11759. if (this.onAnimationEnd) {
  11760. this.onAnimationEnd();
  11761. }
  11762. };
  11763. Animatable.prototype._animate = function (delay) {
  11764. if (this._paused) {
  11765. return true;
  11766. }
  11767. if (!this._localDelayOffset) {
  11768. this._localDelayOffset = delay;
  11769. }
  11770. var running = false;
  11771. var animations = this._animations;
  11772. for (var index = 0; index < animations.length; index++) {
  11773. var animation = animations[index];
  11774. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11775. running = running || isRunning;
  11776. }
  11777. if (!running && this.onAnimationEnd) {
  11778. this.onAnimationEnd();
  11779. }
  11780. return running;
  11781. };
  11782. return Animatable;
  11783. })();
  11784. BABYLON.Animatable = Animatable;
  11785. })(BABYLON || (BABYLON = {}));
  11786. var BABYLON;
  11787. (function (BABYLON) {
  11788. var Octree = (function () {
  11789. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11790. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11791. this.maxDepth = maxDepth;
  11792. this.dynamicContent = new Array();
  11793. this._maxBlockCapacity = maxBlockCapacity || 64;
  11794. this._selectionContent = new BABYLON.SmartArray(1024);
  11795. this._creationFunc = creationFunc;
  11796. }
  11797. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11798. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11799. };
  11800. Octree.prototype.addMesh = function (entry) {
  11801. for (var index = 0; index < this.blocks.length; index++) {
  11802. var block = this.blocks[index];
  11803. block.addEntry(entry);
  11804. }
  11805. };
  11806. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11807. this._selectionContent.reset();
  11808. for (var index = 0; index < this.blocks.length; index++) {
  11809. var block = this.blocks[index];
  11810. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11811. }
  11812. if (allowDuplicate) {
  11813. this._selectionContent.concat(this.dynamicContent);
  11814. } else {
  11815. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11816. }
  11817. return this._selectionContent;
  11818. };
  11819. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11820. this._selectionContent.reset();
  11821. for (var index = 0; index < this.blocks.length; index++) {
  11822. var block = this.blocks[index];
  11823. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11824. }
  11825. if (allowDuplicate) {
  11826. this._selectionContent.concat(this.dynamicContent);
  11827. } else {
  11828. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11829. }
  11830. return this._selectionContent;
  11831. };
  11832. Octree.prototype.intersectsRay = function (ray) {
  11833. this._selectionContent.reset();
  11834. for (var index = 0; index < this.blocks.length; index++) {
  11835. var block = this.blocks[index];
  11836. block.intersectsRay(ray, this._selectionContent);
  11837. }
  11838. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11839. return this._selectionContent;
  11840. };
  11841. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11842. target.blocks = new Array();
  11843. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11844. for (var x = 0; x < 2; x++) {
  11845. for (var y = 0; y < 2; y++) {
  11846. for (var z = 0; z < 2; z++) {
  11847. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11848. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11849. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11850. block.addEntries(entries);
  11851. target.blocks.push(block);
  11852. }
  11853. }
  11854. }
  11855. };
  11856. Octree.CreationFuncForMeshes = function (entry, block) {
  11857. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11858. block.entries.push(entry);
  11859. }
  11860. };
  11861. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11862. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11863. block.entries.push(entry);
  11864. }
  11865. };
  11866. return Octree;
  11867. })();
  11868. BABYLON.Octree = Octree;
  11869. })(BABYLON || (BABYLON = {}));
  11870. var BABYLON;
  11871. (function (BABYLON) {
  11872. var OctreeBlock = (function () {
  11873. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11874. this.entries = new Array();
  11875. this._boundingVectors = new Array();
  11876. this._capacity = capacity;
  11877. this._depth = depth;
  11878. this._maxDepth = maxDepth;
  11879. this._creationFunc = creationFunc;
  11880. this._minPoint = minPoint;
  11881. this._maxPoint = maxPoint;
  11882. this._boundingVectors.push(minPoint.clone());
  11883. this._boundingVectors.push(maxPoint.clone());
  11884. this._boundingVectors.push(minPoint.clone());
  11885. this._boundingVectors[2].x = maxPoint.x;
  11886. this._boundingVectors.push(minPoint.clone());
  11887. this._boundingVectors[3].y = maxPoint.y;
  11888. this._boundingVectors.push(minPoint.clone());
  11889. this._boundingVectors[4].z = maxPoint.z;
  11890. this._boundingVectors.push(maxPoint.clone());
  11891. this._boundingVectors[5].z = minPoint.z;
  11892. this._boundingVectors.push(maxPoint.clone());
  11893. this._boundingVectors[6].x = minPoint.x;
  11894. this._boundingVectors.push(maxPoint.clone());
  11895. this._boundingVectors[7].y = minPoint.y;
  11896. }
  11897. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  11898. get: function () {
  11899. return this._capacity;
  11900. },
  11901. enumerable: true,
  11902. configurable: true
  11903. });
  11904. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  11905. get: function () {
  11906. return this._minPoint;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  11912. get: function () {
  11913. return this._maxPoint;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. OctreeBlock.prototype.addEntry = function (entry) {
  11919. if (this.blocks) {
  11920. for (var index = 0; index < this.blocks.length; index++) {
  11921. var block = this.blocks[index];
  11922. block.addEntry(entry);
  11923. }
  11924. return;
  11925. }
  11926. this._creationFunc(entry, this);
  11927. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  11928. this.createInnerBlocks();
  11929. }
  11930. };
  11931. OctreeBlock.prototype.addEntries = function (entries) {
  11932. for (var index = 0; index < entries.length; index++) {
  11933. var mesh = entries[index];
  11934. this.addEntry(mesh);
  11935. }
  11936. };
  11937. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  11938. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  11939. if (this.blocks) {
  11940. for (var index = 0; index < this.blocks.length; index++) {
  11941. var block = this.blocks[index];
  11942. block.select(frustumPlanes, selection, allowDuplicate);
  11943. }
  11944. return;
  11945. }
  11946. if (allowDuplicate) {
  11947. selection.concat(this.entries);
  11948. } else {
  11949. selection.concatWithNoDuplicate(this.entries);
  11950. }
  11951. }
  11952. };
  11953. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  11954. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  11955. if (this.blocks) {
  11956. for (var index = 0; index < this.blocks.length; index++) {
  11957. var block = this.blocks[index];
  11958. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  11959. }
  11960. return;
  11961. }
  11962. if (allowDuplicate) {
  11963. selection.concat(this.entries);
  11964. } else {
  11965. selection.concatWithNoDuplicate(this.entries);
  11966. }
  11967. }
  11968. };
  11969. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  11970. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  11971. if (this.blocks) {
  11972. for (var index = 0; index < this.blocks.length; index++) {
  11973. var block = this.blocks[index];
  11974. block.intersectsRay(ray, selection);
  11975. }
  11976. return;
  11977. }
  11978. selection.concatWithNoDuplicate(this.entries);
  11979. }
  11980. };
  11981. OctreeBlock.prototype.createInnerBlocks = function () {
  11982. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  11983. };
  11984. return OctreeBlock;
  11985. })();
  11986. BABYLON.OctreeBlock = OctreeBlock;
  11987. })(BABYLON || (BABYLON = {}));
  11988. var BABYLON;
  11989. (function (BABYLON) {
  11990. var Bone = (function () {
  11991. function Bone(name, skeleton, parentBone, matrix) {
  11992. this.name = name;
  11993. this.children = new Array();
  11994. this.animations = new Array();
  11995. this._worldTransform = new BABYLON.Matrix();
  11996. this._absoluteTransform = new BABYLON.Matrix();
  11997. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  11998. this._skeleton = skeleton;
  11999. this._matrix = matrix;
  12000. this._baseMatrix = matrix;
  12001. skeleton.bones.push(this);
  12002. if (parentBone) {
  12003. this._parent = parentBone;
  12004. parentBone.children.push(this);
  12005. } else {
  12006. this._parent = null;
  12007. }
  12008. this._updateDifferenceMatrix();
  12009. }
  12010. Bone.prototype.getParent = function () {
  12011. return this._parent;
  12012. };
  12013. Bone.prototype.getLocalMatrix = function () {
  12014. return this._matrix;
  12015. };
  12016. Bone.prototype.getBaseMatrix = function () {
  12017. return this._baseMatrix;
  12018. };
  12019. Bone.prototype.getWorldMatrix = function () {
  12020. return this._worldTransform;
  12021. };
  12022. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12023. return this._invertedAbsoluteTransform;
  12024. };
  12025. Bone.prototype.getAbsoluteMatrix = function () {
  12026. var matrix = this._matrix.clone();
  12027. var parent = this._parent;
  12028. while (parent) {
  12029. matrix = matrix.multiply(parent.getLocalMatrix());
  12030. parent = parent.getParent();
  12031. }
  12032. return matrix;
  12033. };
  12034. Bone.prototype.updateMatrix = function (matrix) {
  12035. this._matrix = matrix;
  12036. this._skeleton._markAsDirty();
  12037. this._updateDifferenceMatrix();
  12038. };
  12039. Bone.prototype._updateDifferenceMatrix = function () {
  12040. if (this._parent) {
  12041. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12042. } else {
  12043. this._absoluteTransform.copyFrom(this._matrix);
  12044. }
  12045. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12046. for (var index = 0; index < this.children.length; index++) {
  12047. this.children[index]._updateDifferenceMatrix();
  12048. }
  12049. };
  12050. Bone.prototype.markAsDirty = function () {
  12051. this._skeleton._markAsDirty();
  12052. };
  12053. return Bone;
  12054. })();
  12055. BABYLON.Bone = Bone;
  12056. })(BABYLON || (BABYLON = {}));
  12057. var BABYLON;
  12058. (function (BABYLON) {
  12059. var Skeleton = (function () {
  12060. function Skeleton(name, id, scene) {
  12061. this.name = name;
  12062. this.id = id;
  12063. this.bones = new Array();
  12064. this._isDirty = true;
  12065. this._identity = BABYLON.Matrix.Identity();
  12066. this.bones = [];
  12067. this._scene = scene;
  12068. scene.skeletons.push(this);
  12069. }
  12070. Skeleton.prototype.getTransformMatrices = function () {
  12071. return this._transformMatrices;
  12072. };
  12073. Skeleton.prototype._markAsDirty = function () {
  12074. this._isDirty = true;
  12075. };
  12076. Skeleton.prototype.prepare = function () {
  12077. if (!this._isDirty) {
  12078. return;
  12079. }
  12080. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12081. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12082. }
  12083. for (var index = 0; index < this.bones.length; index++) {
  12084. var bone = this.bones[index];
  12085. var parentBone = bone.getParent();
  12086. if (parentBone) {
  12087. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12088. } else {
  12089. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12090. }
  12091. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12092. }
  12093. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12094. this._isDirty = false;
  12095. };
  12096. Skeleton.prototype.getAnimatables = function () {
  12097. if (!this._animatables || this._animatables.length != this.bones.length) {
  12098. this._animatables = [];
  12099. for (var index = 0; index < this.bones.length; index++) {
  12100. this._animatables.push(this.bones[index]);
  12101. }
  12102. }
  12103. return this._animatables;
  12104. };
  12105. Skeleton.prototype.clone = function (name, id) {
  12106. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12107. for (var index = 0; index < this.bones.length; index++) {
  12108. var source = this.bones[index];
  12109. var parentBone = null;
  12110. if (source.getParent()) {
  12111. var parentIndex = this.bones.indexOf(source.getParent());
  12112. parentBone = result.bones[parentIndex];
  12113. }
  12114. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12115. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12116. }
  12117. return result;
  12118. };
  12119. return Skeleton;
  12120. })();
  12121. BABYLON.Skeleton = Skeleton;
  12122. })(BABYLON || (BABYLON = {}));
  12123. var BABYLON;
  12124. (function (BABYLON) {
  12125. var PostProcess = (function () {
  12126. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12127. this.name = name;
  12128. this.width = -1;
  12129. this.height = -1;
  12130. this._reusable = false;
  12131. this._textures = new BABYLON.SmartArray(2);
  12132. this._currentRenderTextureInd = 0;
  12133. if (camera != null) {
  12134. this._camera = camera;
  12135. this._scene = camera.getScene();
  12136. camera.attachPostProcess(this);
  12137. this._engine = this._scene.getEngine();
  12138. } else {
  12139. this._engine = engine;
  12140. }
  12141. this._renderRatio = ratio;
  12142. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12143. this._reusable = reusable || false;
  12144. samplers = samplers || [];
  12145. samplers.push("textureSampler");
  12146. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12147. }
  12148. PostProcess.prototype.isReusable = function () {
  12149. return this._reusable;
  12150. };
  12151. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12152. camera = camera || this._camera;
  12153. var scene = camera.getScene();
  12154. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12155. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12156. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12157. if (this._textures.length > 0) {
  12158. for (var i = 0; i < this._textures.length; i++) {
  12159. this._engine._releaseTexture(this._textures.data[i]);
  12160. }
  12161. this._textures.reset();
  12162. }
  12163. this.width = desiredWidth;
  12164. this.height = desiredHeight;
  12165. 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 }));
  12166. if (this._reusable) {
  12167. 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 }));
  12168. }
  12169. if (this.onSizeChanged) {
  12170. this.onSizeChanged();
  12171. }
  12172. }
  12173. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12174. if (this.onActivate) {
  12175. this.onActivate(camera);
  12176. }
  12177. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12178. if (this._reusable) {
  12179. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12180. }
  12181. };
  12182. PostProcess.prototype.apply = function () {
  12183. if (!this._effect.isReady())
  12184. return null;
  12185. this._engine.enableEffect(this._effect);
  12186. this._engine.setState(false);
  12187. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12188. this._engine.setDepthBuffer(false);
  12189. this._engine.setDepthWrite(false);
  12190. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12191. if (this.onApply) {
  12192. this.onApply(this._effect);
  12193. }
  12194. return this._effect;
  12195. };
  12196. PostProcess.prototype.dispose = function (camera) {
  12197. camera = camera || this._camera;
  12198. if (this._textures.length > 0) {
  12199. for (var i = 0; i < this._textures.length; i++) {
  12200. this._engine._releaseTexture(this._textures.data[i]);
  12201. }
  12202. this._textures.reset();
  12203. }
  12204. camera.detachPostProcess(this);
  12205. var index = camera._postProcesses.indexOf(this);
  12206. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12207. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12208. }
  12209. };
  12210. return PostProcess;
  12211. })();
  12212. BABYLON.PostProcess = PostProcess;
  12213. })(BABYLON || (BABYLON = {}));
  12214. var BABYLON;
  12215. (function (BABYLON) {
  12216. var PostProcessManager = (function () {
  12217. function PostProcessManager(scene) {
  12218. this._vertexDeclaration = [2];
  12219. this._vertexStrideSize = 2 * 4;
  12220. this._scene = scene;
  12221. var vertices = [];
  12222. vertices.push(1, 1);
  12223. vertices.push(-1, 1);
  12224. vertices.push(-1, -1);
  12225. vertices.push(1, -1);
  12226. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12227. var indices = [];
  12228. indices.push(0);
  12229. indices.push(1);
  12230. indices.push(2);
  12231. indices.push(0);
  12232. indices.push(2);
  12233. indices.push(3);
  12234. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12235. }
  12236. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12237. var postProcesses = this._scene.activeCamera._postProcesses;
  12238. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12239. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12240. return false;
  12241. }
  12242. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12243. return true;
  12244. };
  12245. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12246. var postProcesses = this._scene.activeCamera._postProcesses;
  12247. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12248. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12249. return;
  12250. }
  12251. var engine = this._scene.getEngine();
  12252. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12253. if (index < postProcessesTakenIndices.length - 1) {
  12254. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12255. } else {
  12256. if (targetTexture) {
  12257. engine.bindFramebuffer(targetTexture);
  12258. } else {
  12259. engine.restoreDefaultFramebuffer();
  12260. }
  12261. }
  12262. if (doNotPresent) {
  12263. break;
  12264. }
  12265. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12266. if (effect) {
  12267. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12268. engine.draw(true, 0, 6);
  12269. }
  12270. }
  12271. engine.setDepthBuffer(true);
  12272. engine.setDepthWrite(true);
  12273. };
  12274. PostProcessManager.prototype.dispose = function () {
  12275. if (this._vertexBuffer) {
  12276. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12277. this._vertexBuffer = null;
  12278. }
  12279. if (this._indexBuffer) {
  12280. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12281. this._indexBuffer = null;
  12282. }
  12283. };
  12284. return PostProcessManager;
  12285. })();
  12286. BABYLON.PostProcessManager = PostProcessManager;
  12287. })(BABYLON || (BABYLON = {}));
  12288. var __extends = this.__extends || function (d, b) {
  12289. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12290. function __() { this.constructor = d; }
  12291. __.prototype = b.prototype;
  12292. d.prototype = new __();
  12293. };
  12294. var BABYLON;
  12295. (function (BABYLON) {
  12296. var PassPostProcess = (function (_super) {
  12297. __extends(PassPostProcess, _super);
  12298. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12299. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12300. }
  12301. return PassPostProcess;
  12302. })(BABYLON.PostProcess);
  12303. BABYLON.PassPostProcess = PassPostProcess;
  12304. })(BABYLON || (BABYLON = {}));
  12305. var __extends = this.__extends || function (d, b) {
  12306. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12307. function __() { this.constructor = d; }
  12308. __.prototype = b.prototype;
  12309. d.prototype = new __();
  12310. };
  12311. var BABYLON;
  12312. (function (BABYLON) {
  12313. var BlurPostProcess = (function (_super) {
  12314. __extends(BlurPostProcess, _super);
  12315. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12316. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12317. var _this = this;
  12318. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12319. this.direction = direction;
  12320. this.blurWidth = blurWidth;
  12321. this.onApply = function (effect) {
  12322. effect.setFloat2("screenSize", _this.width, _this.height);
  12323. effect.setVector2("direction", _this.direction);
  12324. effect.setFloat("blurWidth", _this.blurWidth);
  12325. };
  12326. }
  12327. return BlurPostProcess;
  12328. })(BABYLON.PostProcess);
  12329. BABYLON.BlurPostProcess = BlurPostProcess;
  12330. })(BABYLON || (BABYLON = {}));
  12331. var __extends = this.__extends || function (d, b) {
  12332. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12333. function __() { this.constructor = d; }
  12334. __.prototype = b.prototype;
  12335. d.prototype = new __();
  12336. };
  12337. var BABYLON;
  12338. (function (BABYLON) {
  12339. var FilterPostProcess = (function (_super) {
  12340. __extends(FilterPostProcess, _super);
  12341. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12342. var _this = this;
  12343. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12344. this.kernelMatrix = kernelMatrix;
  12345. this.onApply = function (effect) {
  12346. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12347. };
  12348. }
  12349. return FilterPostProcess;
  12350. })(BABYLON.PostProcess);
  12351. BABYLON.FilterPostProcess = FilterPostProcess;
  12352. })(BABYLON || (BABYLON = {}));
  12353. var __extends = this.__extends || function (d, b) {
  12354. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12355. function __() { this.constructor = d; }
  12356. __.prototype = b.prototype;
  12357. d.prototype = new __();
  12358. };
  12359. var BABYLON;
  12360. (function (BABYLON) {
  12361. var RefractionPostProcess = (function (_super) {
  12362. __extends(RefractionPostProcess, _super);
  12363. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12364. var _this = this;
  12365. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12366. this.color = color;
  12367. this.depth = depth;
  12368. this.colorLevel = colorLevel;
  12369. this.onActivate = function (cam) {
  12370. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12371. };
  12372. this.onApply = function (effect) {
  12373. effect.setColor3("baseColor", _this.color);
  12374. effect.setFloat("depth", _this.depth);
  12375. effect.setFloat("colorLevel", _this.colorLevel);
  12376. effect.setTexture("refractionSampler", _this._refRexture);
  12377. };
  12378. }
  12379. RefractionPostProcess.prototype.dispose = function (camera) {
  12380. if (this._refRexture) {
  12381. this._refRexture.dispose();
  12382. }
  12383. _super.prototype.dispose.call(this, camera);
  12384. };
  12385. return RefractionPostProcess;
  12386. })(BABYLON.PostProcess);
  12387. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12388. })(BABYLON || (BABYLON = {}));
  12389. var __extends = this.__extends || function (d, b) {
  12390. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12391. function __() { this.constructor = d; }
  12392. __.prototype = b.prototype;
  12393. d.prototype = new __();
  12394. };
  12395. var BABYLON;
  12396. (function (BABYLON) {
  12397. var BlackAndWhitePostProcess = (function (_super) {
  12398. __extends(BlackAndWhitePostProcess, _super);
  12399. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12400. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12401. }
  12402. return BlackAndWhitePostProcess;
  12403. })(BABYLON.PostProcess);
  12404. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12405. })(BABYLON || (BABYLON = {}));
  12406. var __extends = this.__extends || function (d, b) {
  12407. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12408. function __() { this.constructor = d; }
  12409. __.prototype = b.prototype;
  12410. d.prototype = new __();
  12411. };
  12412. var BABYLON;
  12413. (function (BABYLON) {
  12414. var ConvolutionPostProcess = (function (_super) {
  12415. __extends(ConvolutionPostProcess, _super);
  12416. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12417. var _this = this;
  12418. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12419. this.kernel = kernel;
  12420. this.onApply = function (effect) {
  12421. effect.setFloat2("screenSize", _this.width, _this.height);
  12422. effect.setArray("kernel", _this.kernel);
  12423. };
  12424. }
  12425. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12426. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12427. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12428. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12429. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12430. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12431. return ConvolutionPostProcess;
  12432. })(BABYLON.PostProcess);
  12433. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12434. })(BABYLON || (BABYLON = {}));
  12435. var __extends = this.__extends || function (d, b) {
  12436. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12437. function __() { this.constructor = d; }
  12438. __.prototype = b.prototype;
  12439. d.prototype = new __();
  12440. };
  12441. var BABYLON;
  12442. (function (BABYLON) {
  12443. var FxaaPostProcess = (function (_super) {
  12444. __extends(FxaaPostProcess, _super);
  12445. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12446. var _this = this;
  12447. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12448. this.onSizeChanged = function () {
  12449. _this.texelWidth = 1.0 / _this.width;
  12450. _this.texelHeight = 1.0 / _this.height;
  12451. };
  12452. this.onApply = function (effect) {
  12453. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12454. };
  12455. }
  12456. return FxaaPostProcess;
  12457. })(BABYLON.PostProcess);
  12458. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12459. })(BABYLON || (BABYLON = {}));
  12460. var BABYLON;
  12461. (function (BABYLON) {
  12462. var LensFlare = (function () {
  12463. function LensFlare(size, position, color, imgUrl, system) {
  12464. this.size = size;
  12465. this.position = position;
  12466. this.dispose = function () {
  12467. if (this.texture) {
  12468. this.texture.dispose();
  12469. }
  12470. var index = this._system.lensFlares.indexOf(this);
  12471. this._system.lensFlares.splice(index, 1);
  12472. };
  12473. this.color = color || new BABYLON.Color3(1, 1, 1);
  12474. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12475. this._system = system;
  12476. system.lensFlares.push(this);
  12477. }
  12478. return LensFlare;
  12479. })();
  12480. BABYLON.LensFlare = LensFlare;
  12481. })(BABYLON || (BABYLON = {}));
  12482. var BABYLON;
  12483. (function (BABYLON) {
  12484. var LensFlareSystem = (function () {
  12485. function LensFlareSystem(name, emitter, scene) {
  12486. this.name = name;
  12487. this.lensFlares = new Array();
  12488. this.borderLimit = 300;
  12489. this._vertexDeclaration = [2];
  12490. this._vertexStrideSize = 2 * 4;
  12491. this._isEnabled = true;
  12492. this._scene = scene;
  12493. this._emitter = emitter;
  12494. scene.lensFlareSystems.push(this);
  12495. this.meshesSelectionPredicate = function (m) {
  12496. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12497. };
  12498. var vertices = [];
  12499. vertices.push(1, 1);
  12500. vertices.push(-1, 1);
  12501. vertices.push(-1, -1);
  12502. vertices.push(1, -1);
  12503. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12504. var indices = [];
  12505. indices.push(0);
  12506. indices.push(1);
  12507. indices.push(2);
  12508. indices.push(0);
  12509. indices.push(2);
  12510. indices.push(3);
  12511. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12512. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12513. }
  12514. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12515. get: function () {
  12516. return this._isEnabled;
  12517. },
  12518. set: function (value) {
  12519. this._isEnabled = value;
  12520. },
  12521. enumerable: true,
  12522. configurable: true
  12523. });
  12524. LensFlareSystem.prototype.getScene = function () {
  12525. return this._scene;
  12526. };
  12527. LensFlareSystem.prototype.getEmitter = function () {
  12528. return this._emitter;
  12529. };
  12530. LensFlareSystem.prototype.getEmitterPosition = function () {
  12531. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12532. };
  12533. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12534. var position = this.getEmitterPosition();
  12535. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12536. this._positionX = position.x;
  12537. this._positionY = position.y;
  12538. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12539. if (position.z > 0) {
  12540. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12541. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12542. return true;
  12543. }
  12544. }
  12545. return false;
  12546. };
  12547. LensFlareSystem.prototype._isVisible = function () {
  12548. if (!this._isEnabled) {
  12549. return false;
  12550. }
  12551. var emitterPosition = this.getEmitterPosition();
  12552. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12553. var distance = direction.length();
  12554. direction.normalize();
  12555. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12556. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12557. return !pickInfo.hit || pickInfo.distance > distance;
  12558. };
  12559. LensFlareSystem.prototype.render = function () {
  12560. if (!this._effect.isReady())
  12561. return false;
  12562. var engine = this._scene.getEngine();
  12563. var viewport = this._scene.activeCamera.viewport;
  12564. var globalViewport = viewport.toGlobal(engine);
  12565. if (!this.computeEffectivePosition(globalViewport)) {
  12566. return false;
  12567. }
  12568. if (!this._isVisible()) {
  12569. return false;
  12570. }
  12571. var awayX;
  12572. var awayY;
  12573. if (this._positionX < this.borderLimit + globalViewport.x) {
  12574. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12575. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12576. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12577. } else {
  12578. awayX = 0;
  12579. }
  12580. if (this._positionY < this.borderLimit + globalViewport.y) {
  12581. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12582. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12583. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12584. } else {
  12585. awayY = 0;
  12586. }
  12587. var away = (awayX > awayY) ? awayX : awayY;
  12588. if (away > this.borderLimit) {
  12589. away = this.borderLimit;
  12590. }
  12591. var intensity = 1.0 - (away / this.borderLimit);
  12592. if (intensity < 0) {
  12593. return false;
  12594. }
  12595. if (intensity > 1.0) {
  12596. intensity = 1.0;
  12597. }
  12598. var centerX = globalViewport.x + globalViewport.width / 2;
  12599. var centerY = globalViewport.y + globalViewport.height / 2;
  12600. var distX = centerX - this._positionX;
  12601. var distY = centerY - this._positionY;
  12602. engine.enableEffect(this._effect);
  12603. engine.setState(false);
  12604. engine.setDepthBuffer(false);
  12605. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12606. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12607. for (var index = 0; index < this.lensFlares.length; index++) {
  12608. var flare = this.lensFlares[index];
  12609. var x = centerX - (distX * flare.position);
  12610. var y = centerY - (distY * flare.position);
  12611. var cw = flare.size;
  12612. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12613. var cx = 2 * (x / globalViewport.width) - 1.0;
  12614. var cy = 1.0 - 2 * (y / globalViewport.height);
  12615. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12616. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12617. this._effect.setTexture("textureSampler", flare.texture);
  12618. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12619. engine.draw(true, 0, 6);
  12620. }
  12621. engine.setDepthBuffer(true);
  12622. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12623. return true;
  12624. };
  12625. LensFlareSystem.prototype.dispose = function () {
  12626. if (this._vertexBuffer) {
  12627. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12628. this._vertexBuffer = null;
  12629. }
  12630. if (this._indexBuffer) {
  12631. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12632. this._indexBuffer = null;
  12633. }
  12634. while (this.lensFlares.length) {
  12635. this.lensFlares[0].dispose();
  12636. }
  12637. var index = this._scene.lensFlareSystems.indexOf(this);
  12638. this._scene.lensFlareSystems.splice(index, 1);
  12639. };
  12640. return LensFlareSystem;
  12641. })();
  12642. BABYLON.LensFlareSystem = LensFlareSystem;
  12643. })(BABYLON || (BABYLON = {}));
  12644. var BABYLON;
  12645. (function (BABYLON) {
  12646. var IntersectionInfo = (function () {
  12647. function IntersectionInfo(bu, bv, distance) {
  12648. this.bu = bu;
  12649. this.bv = bv;
  12650. this.distance = distance;
  12651. this.faceId = 0;
  12652. }
  12653. return IntersectionInfo;
  12654. })();
  12655. BABYLON.IntersectionInfo = IntersectionInfo;
  12656. var PickingInfo = (function () {
  12657. function PickingInfo() {
  12658. this.hit = false;
  12659. this.distance = 0;
  12660. this.pickedPoint = null;
  12661. this.pickedMesh = null;
  12662. this.bu = 0;
  12663. this.bv = 0;
  12664. this.faceId = -1;
  12665. }
  12666. PickingInfo.prototype.getNormal = function () {
  12667. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12668. return null;
  12669. }
  12670. var indices = this.pickedMesh.getIndices();
  12671. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12672. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12673. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12674. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12675. normal0 = normal0.scale(this.bu);
  12676. normal1 = normal1.scale(this.bv);
  12677. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12678. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12679. };
  12680. PickingInfo.prototype.getTextureCoordinates = function () {
  12681. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12682. return null;
  12683. }
  12684. var indices = this.pickedMesh.getIndices();
  12685. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12686. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12687. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12688. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12689. uv0 = uv0.scale(this.bu);
  12690. uv1 = uv1.scale(this.bv);
  12691. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12692. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12693. };
  12694. return PickingInfo;
  12695. })();
  12696. BABYLON.PickingInfo = PickingInfo;
  12697. })(BABYLON || (BABYLON = {}));
  12698. var BABYLON;
  12699. (function (BABYLON) {
  12700. var FilesInput = (function () {
  12701. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12702. this.engine = p_engine;
  12703. this.canvas = p_canvas;
  12704. this.currentScene = p_scene;
  12705. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12706. this.progressCallback = p_progressCallback;
  12707. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12708. this.textureLoadingCallback = p_textureLoadingCallback;
  12709. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12710. }
  12711. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12712. var _this = this;
  12713. if (p_elementToMonitor) {
  12714. this.elementToMonitor = p_elementToMonitor;
  12715. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12716. _this.drag(e);
  12717. }, false);
  12718. this.elementToMonitor.addEventListener("dragover", function (e) {
  12719. _this.drag(e);
  12720. }, false);
  12721. this.elementToMonitor.addEventListener("drop", function (e) {
  12722. _this.drop(e);
  12723. }, false);
  12724. }
  12725. };
  12726. FilesInput.prototype.renderFunction = function () {
  12727. if (this.additionnalRenderLoopLogicCallback) {
  12728. this.additionnalRenderLoopLogicCallback();
  12729. }
  12730. if (this.currentScene) {
  12731. if (this.textureLoadingCallback) {
  12732. var remaining = this.currentScene.getWaitingItemsCount();
  12733. if (remaining > 0) {
  12734. this.textureLoadingCallback(remaining);
  12735. }
  12736. }
  12737. this.currentScene.render();
  12738. }
  12739. };
  12740. FilesInput.prototype.drag = function (e) {
  12741. e.stopPropagation();
  12742. e.preventDefault();
  12743. };
  12744. FilesInput.prototype.drop = function (eventDrop) {
  12745. eventDrop.stopPropagation();
  12746. eventDrop.preventDefault();
  12747. this.loadFiles(eventDrop);
  12748. };
  12749. FilesInput.prototype.loadFiles = function (event) {
  12750. var _this = this;
  12751. var that = this;
  12752. if (this.startingProcessingFilesCallback)
  12753. this.startingProcessingFilesCallback();
  12754. var sceneFileToLoad;
  12755. var filesToLoad;
  12756. if (event && event.dataTransfer && event.dataTransfer.files) {
  12757. filesToLoad = event.dataTransfer.files;
  12758. }
  12759. if (event && event.target && event.target.files) {
  12760. filesToLoad = event.target.files;
  12761. }
  12762. if (filesToLoad && filesToLoad.length > 0) {
  12763. for (var i = 0; i < filesToLoad.length; i++) {
  12764. switch (filesToLoad[i].type) {
  12765. case "image/jpeg":
  12766. case "image/png":
  12767. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12768. break;
  12769. case "image/targa":
  12770. case "image/vnd.ms-dds":
  12771. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12772. break;
  12773. default:
  12774. 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) {
  12775. sceneFileToLoad = filesToLoad[i];
  12776. }
  12777. break;
  12778. }
  12779. }
  12780. if (sceneFileToLoad) {
  12781. if (this.currentScene) {
  12782. this.engine.stopRenderLoop();
  12783. this.currentScene.dispose();
  12784. }
  12785. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12786. that.currentScene = newScene;
  12787. that.currentScene.executeWhenReady(function () {
  12788. if (that.currentScene.activeCamera) {
  12789. that.currentScene.activeCamera.attachControl(that.canvas);
  12790. }
  12791. if (that.sceneLoadedCallback) {
  12792. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12793. }
  12794. that.engine.runRenderLoop(function () {
  12795. that.renderFunction();
  12796. });
  12797. });
  12798. }, function (progress) {
  12799. if (_this.progressCallback) {
  12800. _this.progressCallback(progress);
  12801. }
  12802. });
  12803. } else {
  12804. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12805. }
  12806. }
  12807. };
  12808. FilesInput.FilesTextures = new Array();
  12809. FilesInput.FilesToLoad = new Array();
  12810. return FilesInput;
  12811. })();
  12812. BABYLON.FilesInput = FilesInput;
  12813. })(BABYLON || (BABYLON = {}));
  12814. var BABYLON;
  12815. (function (BABYLON) {
  12816. var OimoJSPlugin = (function () {
  12817. function OimoJSPlugin() {
  12818. this._registeredMeshes = [];
  12819. /**
  12820. * Update the body position according to the mesh position
  12821. * @param mesh
  12822. */
  12823. this.updateBodyPosition = function (mesh) {
  12824. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12825. var registeredMesh = this._registeredMeshes[index];
  12826. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12827. var body = registeredMesh.body.body;
  12828. var center = mesh.getBoundingInfo().boundingBox.center;
  12829. body.setPosition(center.x, center.y, center.z);
  12830. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12831. return;
  12832. }
  12833. if (registeredMesh.mesh.parent === mesh) {
  12834. mesh.computeWorldMatrix(true);
  12835. registeredMesh.mesh.computeWorldMatrix(true);
  12836. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12837. var absoluteRotation = mesh.rotation;
  12838. body = registeredMesh.body.body;
  12839. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12840. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12841. return;
  12842. }
  12843. }
  12844. };
  12845. }
  12846. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12847. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12848. };
  12849. OimoJSPlugin.prototype.initialize = function (iterations) {
  12850. this._world = new OIMO.World();
  12851. this._world.clear();
  12852. };
  12853. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12854. this._world.gravity = gravity;
  12855. };
  12856. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12857. var body = null;
  12858. this.unregisterMesh(mesh);
  12859. mesh.computeWorldMatrix(true);
  12860. switch (impostor) {
  12861. case BABYLON.PhysicsEngine.SphereImpostor:
  12862. var bbox = mesh.getBoundingInfo().boundingBox;
  12863. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12864. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12865. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12866. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12867. var deltaPosition = mesh.position.subtract(bbox.center);
  12868. body = new OIMO.Body({
  12869. type: 'sphere',
  12870. size: [size],
  12871. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12872. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12873. move: options.mass != 0,
  12874. config: [options.mass, options.friction, options.restitution],
  12875. world: this._world
  12876. });
  12877. this._registeredMeshes.push({
  12878. mesh: mesh,
  12879. body: body,
  12880. delta: deltaPosition
  12881. });
  12882. break;
  12883. case BABYLON.PhysicsEngine.PlaneImpostor:
  12884. case BABYLON.PhysicsEngine.BoxImpostor:
  12885. bbox = mesh.getBoundingInfo().boundingBox;
  12886. var min = bbox.minimumWorld;
  12887. var max = bbox.maximumWorld;
  12888. var box = max.subtract(min);
  12889. var sizeX = this._checkWithEpsilon(box.x);
  12890. var sizeY = this._checkWithEpsilon(box.y);
  12891. var sizeZ = this._checkWithEpsilon(box.z);
  12892. var deltaPosition = mesh.position.subtract(bbox.center);
  12893. body = new OIMO.Body({
  12894. type: 'box',
  12895. size: [sizeX, sizeY, sizeZ],
  12896. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12897. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12898. move: options.mass != 0,
  12899. config: [options.mass, options.friction, options.restitution],
  12900. world: this._world
  12901. });
  12902. this._registeredMeshes.push({
  12903. mesh: mesh,
  12904. body: body,
  12905. delta: deltaPosition
  12906. });
  12907. break;
  12908. }
  12909. return body;
  12910. };
  12911. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  12912. var types = [], sizes = [], positions = [], rotations = [];
  12913. var initialMesh = parts[0].mesh;
  12914. for (var index = 0; index < parts.length; index++) {
  12915. var part = parts[index];
  12916. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  12917. types.push(bodyParameters.type);
  12918. sizes.push.apply(sizes, bodyParameters.size);
  12919. positions.push.apply(positions, bodyParameters.pos);
  12920. rotations.push.apply(rotations, bodyParameters.rot);
  12921. }
  12922. var body = new OIMO.Body({
  12923. type: types,
  12924. size: sizes,
  12925. pos: positions,
  12926. rot: rotations,
  12927. move: options.mass != 0,
  12928. config: [options.mass, options.friction, options.restitution],
  12929. world: this._world
  12930. });
  12931. this._registeredMeshes.push({
  12932. mesh: initialMesh,
  12933. body: body
  12934. });
  12935. return body;
  12936. };
  12937. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  12938. var bodyParameters = null;
  12939. var mesh = part.mesh;
  12940. switch (part.impostor) {
  12941. case BABYLON.PhysicsEngine.SphereImpostor:
  12942. var bbox = mesh.getBoundingInfo().boundingBox;
  12943. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12944. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12945. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12946. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12947. bodyParameters = {
  12948. type: 'sphere',
  12949. /* bug with oimo : sphere needs 3 sizes in this case */
  12950. size: [size, -1, -1],
  12951. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  12952. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12953. };
  12954. break;
  12955. case BABYLON.PhysicsEngine.PlaneImpostor:
  12956. case BABYLON.PhysicsEngine.BoxImpostor:
  12957. bbox = mesh.getBoundingInfo().boundingBox;
  12958. var min = bbox.minimumWorld;
  12959. var max = bbox.maximumWorld;
  12960. var box = max.subtract(min);
  12961. var sizeX = this._checkWithEpsilon(box.x);
  12962. var sizeY = this._checkWithEpsilon(box.y);
  12963. var sizeZ = this._checkWithEpsilon(box.z);
  12964. var relativePosition = mesh.position;
  12965. bodyParameters = {
  12966. type: 'box',
  12967. size: [sizeX, sizeY, sizeZ],
  12968. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  12969. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12970. };
  12971. break;
  12972. }
  12973. return bodyParameters;
  12974. };
  12975. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  12976. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12977. var registeredMesh = this._registeredMeshes[index];
  12978. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12979. if (registeredMesh.body) {
  12980. this._world.removeRigidBody(registeredMesh.body.body);
  12981. this._unbindBody(registeredMesh.body);
  12982. }
  12983. this._registeredMeshes.splice(index, 1);
  12984. return;
  12985. }
  12986. }
  12987. };
  12988. OimoJSPlugin.prototype._unbindBody = function (body) {
  12989. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12990. var registeredMesh = this._registeredMeshes[index];
  12991. if (registeredMesh.body === body) {
  12992. registeredMesh.body = null;
  12993. }
  12994. }
  12995. };
  12996. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  12997. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12998. var registeredMesh = this._registeredMeshes[index];
  12999. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13000. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE));
  13001. return;
  13002. }
  13003. }
  13004. };
  13005. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13006. var body1 = null, body2 = null;
  13007. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13008. var registeredMesh = this._registeredMeshes[index];
  13009. if (registeredMesh.mesh === mesh1) {
  13010. body1 = registeredMesh.body.body;
  13011. } else if (registeredMesh.mesh === mesh2) {
  13012. body2 = registeredMesh.body.body;
  13013. }
  13014. }
  13015. if (!body1 || !body2) {
  13016. return false;
  13017. }
  13018. if (!options) {
  13019. options = {};
  13020. }
  13021. new OIMO.Link({
  13022. type: options.type,
  13023. body1: body1,
  13024. body2: body2,
  13025. min: options.min,
  13026. max: options.max,
  13027. axe1: options.axe1,
  13028. axe2: options.axe2,
  13029. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13030. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13031. collision: options.collision,
  13032. spring: options.spring,
  13033. world: this._world
  13034. });
  13035. return true;
  13036. };
  13037. OimoJSPlugin.prototype.dispose = function () {
  13038. this._world.clear();
  13039. while (this._registeredMeshes.length) {
  13040. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13041. }
  13042. };
  13043. OimoJSPlugin.prototype.isSupported = function () {
  13044. return OIMO !== undefined;
  13045. };
  13046. OimoJSPlugin.prototype._getLastShape = function (body) {
  13047. var lastShape = body.shapes;
  13048. while (lastShape.next) {
  13049. lastShape = lastShape.next;
  13050. }
  13051. return lastShape;
  13052. };
  13053. OimoJSPlugin.prototype.runOneStep = function (time) {
  13054. this._world.step();
  13055. var i = this._registeredMeshes.length;
  13056. var m;
  13057. while (i--) {
  13058. var body = this._registeredMeshes[i].body.body;
  13059. var mesh = this._registeredMeshes[i].mesh;
  13060. var delta = this._registeredMeshes[i].delta;
  13061. if (!body.sleeping) {
  13062. if (body.shapes.next) {
  13063. var parentShape = this._getLastShape(body);
  13064. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13065. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13066. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13067. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13068. if (!mesh.rotationQuaternion) {
  13069. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13070. }
  13071. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13072. } else {
  13073. m = body.getMatrix();
  13074. mtx = BABYLON.Matrix.FromArray(m);
  13075. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13076. if (!delta) {
  13077. mesh.position.x = bodyX;
  13078. mesh.position.y = bodyY;
  13079. mesh.position.z = bodyZ;
  13080. } else {
  13081. mesh.position.x = bodyX + delta.x;
  13082. mesh.position.y = bodyY + delta.y;
  13083. mesh.position.z = bodyZ + delta.z;
  13084. }
  13085. if (!mesh.rotationQuaternion) {
  13086. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13087. }
  13088. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13089. }
  13090. }
  13091. }
  13092. };
  13093. return OimoJSPlugin;
  13094. })();
  13095. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13096. })(BABYLON || (BABYLON = {}));
  13097. var BABYLON;
  13098. (function (BABYLON) {
  13099. var PhysicsEngine = (function () {
  13100. function PhysicsEngine(plugin) {
  13101. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13102. }
  13103. PhysicsEngine.prototype._initialize = function (gravity) {
  13104. this._currentPlugin.initialize();
  13105. this._setGravity(gravity);
  13106. };
  13107. PhysicsEngine.prototype._runOneStep = function (delta) {
  13108. if (delta > 0.1) {
  13109. delta = 0.1;
  13110. } else if (delta <= 0) {
  13111. delta = 1.0 / 60.0;
  13112. }
  13113. this._currentPlugin.runOneStep(delta);
  13114. };
  13115. PhysicsEngine.prototype._setGravity = function (gravity) {
  13116. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13117. this._currentPlugin.setGravity(this.gravity);
  13118. };
  13119. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13120. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13121. };
  13122. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13123. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13124. };
  13125. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13126. this._currentPlugin.unregisterMesh(mesh);
  13127. };
  13128. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13129. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13130. };
  13131. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13132. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13133. };
  13134. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13135. this._currentPlugin.updateBodyPosition(mesh);
  13136. };
  13137. PhysicsEngine.prototype.dispose = function () {
  13138. this._currentPlugin.dispose();
  13139. };
  13140. PhysicsEngine.prototype.isSupported = function () {
  13141. return this._currentPlugin.isSupported();
  13142. };
  13143. PhysicsEngine.NoImpostor = 0;
  13144. PhysicsEngine.SphereImpostor = 1;
  13145. PhysicsEngine.BoxImpostor = 2;
  13146. PhysicsEngine.PlaneImpostor = 3;
  13147. PhysicsEngine.CompoundImpostor = 4;
  13148. PhysicsEngine.MeshImpostor = 4;
  13149. PhysicsEngine.CapsuleImpostor = 5;
  13150. PhysicsEngine.ConeImpostor = 6;
  13151. PhysicsEngine.CylinderImpostor = 7;
  13152. PhysicsEngine.ConvexHullImpostor = 8;
  13153. PhysicsEngine.Epsilon = 0.001;
  13154. return PhysicsEngine;
  13155. })();
  13156. BABYLON.PhysicsEngine = PhysicsEngine;
  13157. })(BABYLON || (BABYLON = {}));
  13158. var BABYLON;
  13159. (function (BABYLON) {
  13160. var serializeLight = function (light) {
  13161. var serializationObject = {};
  13162. serializationObject.name = light.name;
  13163. serializationObject.id = light.id;
  13164. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13165. if (light instanceof BABYLON.PointLight) {
  13166. serializationObject.type = 0;
  13167. serializationObject.position = light.position.asArray();
  13168. } else if (light instanceof BABYLON.DirectionalLight) {
  13169. serializationObject.type = 1;
  13170. var directionalLight = light;
  13171. serializationObject.position = directionalLight.position.asArray();
  13172. serializationObject.direction = directionalLight.direction.asArray();
  13173. } else if (light instanceof BABYLON.SpotLight) {
  13174. serializationObject.type = 2;
  13175. var spotLight = light;
  13176. serializationObject.position = spotLight.position.asArray();
  13177. serializationObject.direction = spotLight.position.asArray();
  13178. serializationObject.angle = spotLight.angle;
  13179. serializationObject.exponent = spotLight.exponent;
  13180. } else if (light instanceof BABYLON.HemisphericLight) {
  13181. serializationObject.type = 3;
  13182. var hemisphericLight = light;
  13183. serializationObject.direction = hemisphericLight.direction.asArray();
  13184. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13185. }
  13186. if (light.intensity) {
  13187. serializationObject.intensity = light.intensity;
  13188. }
  13189. serializationObject.range = light.range;
  13190. serializationObject.diffuse = light.diffuse.asArray();
  13191. serializationObject.specular = light.specular.asArray();
  13192. return serializationObject;
  13193. };
  13194. var serializeCamera = function (camera) {
  13195. var serializationObject = {};
  13196. serializationObject.name = camera.name;
  13197. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13198. serializationObject.id = camera.id;
  13199. serializationObject.position = camera.position.asArray();
  13200. if (camera.parent) {
  13201. serializationObject.parentId = camera.parent.id;
  13202. }
  13203. serializationObject.rotation = camera.rotation.asArray();
  13204. if (camera.lockedTarget && camera.lockedTarget.id) {
  13205. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13206. }
  13207. serializationObject.fov = camera.fov;
  13208. serializationObject.minZ = camera.minZ;
  13209. serializationObject.maxZ = camera.maxZ;
  13210. serializationObject.speed = camera.speed;
  13211. serializationObject.inertia = camera.inertia;
  13212. serializationObject.checkCollisions = camera.checkCollisions;
  13213. serializationObject.applyGravity = camera.applyGravity;
  13214. if (camera.ellipsoid) {
  13215. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13216. }
  13217. appendAnimations(camera, serializationObject);
  13218. serializationObject.layerMask = camera.layerMask;
  13219. return serializationObject;
  13220. };
  13221. var appendAnimations = function (source, destination) {
  13222. if (source.animations) {
  13223. destination.animations = [];
  13224. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13225. var animation = source.animations[animationIndex];
  13226. destination.animations.push(serializeAnimation(animation));
  13227. }
  13228. }
  13229. };
  13230. var serializeAnimation = function (animation) {
  13231. var serializationObject = {};
  13232. serializationObject.name = animation.name;
  13233. serializationObject.property = animation.targetProperty;
  13234. serializationObject.framePerSecond = animation.framePerSecond;
  13235. serializationObject.dataType = animation.dataType;
  13236. serializationObject.loopBehavior = animation.loopMode;
  13237. var dataType = animation.dataType;
  13238. serializationObject.keys = [];
  13239. var keys = animation.getKeys();
  13240. for (var index = 0; index < keys.length; index++) {
  13241. var animationKey = keys[index];
  13242. var key = {};
  13243. key.frame = animationKey.frame;
  13244. switch (dataType) {
  13245. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13246. key.values = [animationKey.value];
  13247. break;
  13248. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13249. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13250. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13251. key.values = animationKey.value.asArray();
  13252. break;
  13253. }
  13254. serializationObject.keys.push(key);
  13255. }
  13256. return serializationObject;
  13257. };
  13258. var serializeMultiMaterial = function (material) {
  13259. var serializationObject = {};
  13260. serializationObject.name = material.name;
  13261. serializationObject.id = material.id;
  13262. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13263. serializationObject.materials = [];
  13264. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13265. var subMat = material.subMaterials[matIndex];
  13266. if (subMat) {
  13267. serializationObject.materials.push(subMat.id);
  13268. } else {
  13269. serializationObject.materials.push(null);
  13270. }
  13271. }
  13272. return serializationObject;
  13273. };
  13274. var serializeMaterial = function (material) {
  13275. var serializationObject = {};
  13276. serializationObject.name = material.name;
  13277. serializationObject.ambient = material.ambientColor.asArray();
  13278. serializationObject.diffuse = material.diffuseColor.asArray();
  13279. serializationObject.specular = material.specularColor.asArray();
  13280. serializationObject.specularPower = material.specularPower;
  13281. serializationObject.emissive = material.emissiveColor.asArray();
  13282. serializationObject.alpha = material.alpha;
  13283. serializationObject.id = material.id;
  13284. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13285. serializationObject.backFaceCulling = material.backFaceCulling;
  13286. if (material.diffuseTexture) {
  13287. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13288. }
  13289. if (material.ambientTexture) {
  13290. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13291. }
  13292. if (material.opacityTexture) {
  13293. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13294. }
  13295. if (material.reflectionTexture) {
  13296. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13297. }
  13298. if (material.emissiveTexture) {
  13299. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13300. }
  13301. if (material.specularTexture) {
  13302. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13303. }
  13304. if (material.bumpTexture) {
  13305. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13306. }
  13307. return serializationObject;
  13308. };
  13309. var serializeTexture = function (texture) {
  13310. var serializationObject = {};
  13311. if (!texture.name) {
  13312. return null;
  13313. }
  13314. if (texture instanceof BABYLON.CubeTexture) {
  13315. serializationObject.name = texture.name;
  13316. serializationObject.hasAlpha = texture.hasAlpha;
  13317. serializationObject.level = texture.level;
  13318. serializationObject.coordinatesMode = texture.coordinatesMode;
  13319. return serializationObject;
  13320. }
  13321. if (texture instanceof BABYLON.MirrorTexture) {
  13322. var mirrorTexture = texture;
  13323. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13324. serializationObject.renderList = [];
  13325. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13326. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13327. }
  13328. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13329. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13330. var renderTargetTexture = texture;
  13331. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13332. serializationObject.renderList = [];
  13333. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13334. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13335. }
  13336. }
  13337. var regularTexture = texture;
  13338. serializationObject.name = texture.name;
  13339. serializationObject.hasAlpha = texture.hasAlpha;
  13340. serializationObject.level = texture.level;
  13341. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13342. serializationObject.coordinatesMode = texture.coordinatesMode;
  13343. serializationObject.uOffset = regularTexture.uOffset;
  13344. serializationObject.vOffset = regularTexture.vOffset;
  13345. serializationObject.uScale = regularTexture.uScale;
  13346. serializationObject.vScale = regularTexture.vScale;
  13347. serializationObject.uAng = regularTexture.uAng;
  13348. serializationObject.vAng = regularTexture.vAng;
  13349. serializationObject.wAng = regularTexture.wAng;
  13350. serializationObject.wrapU = texture.wrapU;
  13351. serializationObject.wrapV = texture.wrapV;
  13352. appendAnimations(texture, serializationObject);
  13353. return serializationObject;
  13354. };
  13355. var serializeSkeleton = function (skeleton) {
  13356. var serializationObject = {};
  13357. serializationObject.name = skeleton.name;
  13358. serializationObject.id = skeleton.id;
  13359. serializationObject.bones = [];
  13360. for (var index = 0; index < skeleton.bones.length; index++) {
  13361. var bone = skeleton.bones[index];
  13362. var serializedBone = {
  13363. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13364. name: bone.name,
  13365. matrix: bone.getLocalMatrix().toArray()
  13366. };
  13367. serializationObject.bones.push(serializedBone);
  13368. if (bone.animations && bone.animations.length > 0) {
  13369. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13370. }
  13371. }
  13372. return serializationObject;
  13373. };
  13374. var serializeParticleSystem = function (particleSystem) {
  13375. var serializationObject = {};
  13376. serializationObject.emitterId = particleSystem.emitter.id;
  13377. serializationObject.capacity = particleSystem.getCapacity();
  13378. if (particleSystem.particleTexture) {
  13379. serializationObject.textureName = particleSystem.particleTexture.name;
  13380. }
  13381. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13382. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13383. serializationObject.minSize = particleSystem.minSize;
  13384. serializationObject.maxSize = particleSystem.maxSize;
  13385. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13386. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13387. serializationObject.emitRate = particleSystem.emitRate;
  13388. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13389. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13390. serializationObject.gravity = particleSystem.gravity.asArray();
  13391. serializationObject.direction1 = particleSystem.direction1.asArray();
  13392. serializationObject.direction2 = particleSystem.direction2.asArray();
  13393. serializationObject.color1 = particleSystem.color1.asArray();
  13394. serializationObject.color2 = particleSystem.color2.asArray();
  13395. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13396. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13397. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13398. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13399. serializationObject.blendMode = particleSystem.blendMode;
  13400. return serializationObject;
  13401. };
  13402. var serializeLensFlareSystem = function (lensFlareSystem) {
  13403. var serializationObject = {};
  13404. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13405. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13406. serializationObject.flares = [];
  13407. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13408. var flare = lensFlareSystem.lensFlares[index];
  13409. serializationObject.flares.push({
  13410. size: flare.size,
  13411. position: flare.position,
  13412. color: flare.color.asArray(),
  13413. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13414. });
  13415. }
  13416. return serializationObject;
  13417. };
  13418. var serializeShadowGenerator = function (light) {
  13419. var serializationObject = {};
  13420. var shadowGenerator = light.getShadowGenerator();
  13421. serializationObject.lightId = light.id;
  13422. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13423. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13424. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13425. serializationObject.renderList = [];
  13426. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13427. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13428. serializationObject.renderList.push(mesh.id);
  13429. }
  13430. return serializationObject;
  13431. };
  13432. var serializedGeometries = [];
  13433. var serializeGeometry = function (geometry, serializationGeometries) {
  13434. if (serializedGeometries[geometry.id]) {
  13435. return;
  13436. }
  13437. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13438. serializationGeometries.boxes.push(serializeBox(geometry));
  13439. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13440. serializationGeometries.spheres.push(serializeSphere(geometry));
  13441. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13442. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13443. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13444. serializationGeometries.toruses.push(serializeTorus(geometry));
  13445. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13446. serializationGeometries.grounds.push(serializeGround(geometry));
  13447. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13448. serializationGeometries.planes.push(serializePlane(geometry));
  13449. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13450. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13451. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13452. throw new Error("Unknow primitive type");
  13453. } else {
  13454. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13455. }
  13456. serializedGeometries[geometry.id] = true;
  13457. };
  13458. var serializeGeometryBase = function (geometry) {
  13459. var serializationObject = {};
  13460. serializationObject.id = geometry.id;
  13461. if (BABYLON.Tags.HasTags(geometry)) {
  13462. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13463. }
  13464. return serializationObject;
  13465. };
  13466. var serializeVertexData = function (vertexData) {
  13467. var serializationObject = serializeGeometryBase(vertexData);
  13468. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13469. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13470. }
  13471. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13472. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13473. }
  13474. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13475. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13476. }
  13477. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13478. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13479. }
  13480. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13481. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13482. }
  13483. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13484. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13485. serializationObject.matricesIndices._isExpanded = true;
  13486. }
  13487. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13488. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13489. }
  13490. serializationObject.indices = vertexData.getIndices();
  13491. return serializationObject;
  13492. };
  13493. var serializePrimitive = function (primitive) {
  13494. var serializationObject = serializeGeometryBase(primitive);
  13495. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13496. return serializationObject;
  13497. };
  13498. var serializeBox = function (box) {
  13499. var serializationObject = serializePrimitive(box);
  13500. serializationObject.size = box.size;
  13501. return serializationObject;
  13502. };
  13503. var serializeSphere = function (sphere) {
  13504. var serializationObject = serializePrimitive(sphere);
  13505. serializationObject.segments = sphere.segments;
  13506. serializationObject.diameter = sphere.diameter;
  13507. return serializationObject;
  13508. };
  13509. var serializeCylinder = function (cylinder) {
  13510. var serializationObject = serializePrimitive(cylinder);
  13511. serializationObject.height = cylinder.height;
  13512. serializationObject.diameterTop = cylinder.diameterTop;
  13513. serializationObject.diameterBottom = cylinder.diameterBottom;
  13514. serializationObject.tessellation = cylinder.tessellation;
  13515. return serializationObject;
  13516. };
  13517. var serializeTorus = function (torus) {
  13518. var serializationObject = serializePrimitive(torus);
  13519. serializationObject.diameter = torus.diameter;
  13520. serializationObject.thickness = torus.thickness;
  13521. serializationObject.tessellation = torus.tessellation;
  13522. return serializationObject;
  13523. };
  13524. var serializeGround = function (ground) {
  13525. var serializationObject = serializePrimitive(ground);
  13526. serializationObject.width = ground.width;
  13527. serializationObject.height = ground.height;
  13528. serializationObject.subdivisions = ground.subdivisions;
  13529. return serializationObject;
  13530. };
  13531. var serializePlane = function (plane) {
  13532. var serializationObject = serializePrimitive(plane);
  13533. serializationObject.size = plane.size;
  13534. return serializationObject;
  13535. };
  13536. var serializeTorusKnot = function (torusKnot) {
  13537. var serializationObject = serializePrimitive(torusKnot);
  13538. serializationObject.radius = torusKnot.radius;
  13539. serializationObject.tube = torusKnot.tube;
  13540. serializationObject.radialSegments = torusKnot.radialSegments;
  13541. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13542. serializationObject.p = torusKnot.p;
  13543. serializationObject.q = torusKnot.q;
  13544. return serializationObject;
  13545. };
  13546. var serializeMesh = function (mesh, serializationScene) {
  13547. var serializationObject = {};
  13548. serializationObject.name = mesh.name;
  13549. serializationObject.id = mesh.id;
  13550. if (BABYLON.Tags.HasTags(mesh)) {
  13551. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13552. }
  13553. serializationObject.position = mesh.position.asArray();
  13554. if (mesh.rotationQuaternion) {
  13555. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13556. } else if (mesh.rotation) {
  13557. serializationObject.rotation = mesh.rotation.asArray();
  13558. }
  13559. serializationObject.scaling = mesh.scaling.asArray();
  13560. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13561. serializationObject.isEnabled = mesh.isEnabled();
  13562. serializationObject.isVisible = mesh.isVisible;
  13563. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13564. serializationObject.pickable = mesh.isPickable;
  13565. serializationObject.receiveShadows = mesh.receiveShadows;
  13566. serializationObject.billboardMode = mesh.billboardMode;
  13567. serializationObject.visibility = mesh.visibility;
  13568. serializationObject.checkCollisions = mesh.checkCollisions;
  13569. if (mesh.parent) {
  13570. serializationObject.parentId = mesh.parent.id;
  13571. }
  13572. var geometry = mesh._geometry;
  13573. if (geometry) {
  13574. var geometryId = geometry.id;
  13575. serializationObject.geometryId = geometryId;
  13576. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13577. serializeGeometry(geometry, serializationScene.geometries);
  13578. }
  13579. serializationObject.subMeshes = [];
  13580. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13581. var subMesh = mesh.subMeshes[subIndex];
  13582. serializationObject.subMeshes.push({
  13583. materialIndex: subMesh.materialIndex,
  13584. verticesStart: subMesh.verticesStart,
  13585. verticesCount: subMesh.verticesCount,
  13586. indexStart: subMesh.indexStart,
  13587. indexCount: subMesh.indexCount
  13588. });
  13589. }
  13590. }
  13591. if (mesh.material) {
  13592. serializationObject.materialId = mesh.material.id;
  13593. } else {
  13594. mesh.material = null;
  13595. }
  13596. if (mesh.skeleton) {
  13597. serializationObject.skeletonId = mesh.skeleton.id;
  13598. }
  13599. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13600. serializationObject.physicsMass = mesh.getPhysicsMass();
  13601. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13602. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13603. switch (mesh.getPhysicsImpostor()) {
  13604. case BABYLON.PhysicsEngine.BoxImpostor:
  13605. serializationObject.physicsImpostor = 1;
  13606. break;
  13607. case BABYLON.PhysicsEngine.SphereImpostor:
  13608. serializationObject.physicsImpostor = 2;
  13609. break;
  13610. }
  13611. }
  13612. serializationObject.instances = [];
  13613. for (var index = 0; index < mesh.instances.length; index++) {
  13614. var instance = mesh.instances[index];
  13615. var serializationInstance = {
  13616. name: instance.name,
  13617. position: instance.position,
  13618. rotation: instance.rotation,
  13619. rotationQuaternion: instance.rotationQuaternion,
  13620. scaling: instance.scaling
  13621. };
  13622. serializationObject.instances.push(serializationInstance);
  13623. appendAnimations(instance, serializationInstance);
  13624. }
  13625. appendAnimations(mesh, serializationObject);
  13626. serializationObject.layerMask = mesh.layerMask;
  13627. return serializationObject;
  13628. };
  13629. var SceneSerializer = (function () {
  13630. function SceneSerializer() {
  13631. }
  13632. SceneSerializer.Serialize = function (scene) {
  13633. var serializationObject = {};
  13634. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13635. serializationObject.autoClear = scene.autoClear;
  13636. serializationObject.clearColor = scene.clearColor.asArray();
  13637. serializationObject.ambientColor = scene.ambientColor.asArray();
  13638. serializationObject.gravity = scene.gravity.asArray();
  13639. if (scene.fogMode && scene.fogMode !== 0) {
  13640. serializationObject.fogMode = scene.fogMode;
  13641. serializationObject.fogColor = scene.fogColor.asArray();
  13642. serializationObject.fogStart = scene.fogStart;
  13643. serializationObject.fogEnd = scene.fogEnd;
  13644. serializationObject.fogDensity = scene.fogDensity;
  13645. }
  13646. serializationObject.lights = [];
  13647. for (var index = 0; index < scene.lights.length; index++) {
  13648. var light = scene.lights[index];
  13649. serializationObject.lights.push(serializeLight(light));
  13650. }
  13651. serializationObject.cameras = [];
  13652. for (index = 0; index < scene.cameras.length; index++) {
  13653. var camera = scene.cameras[index];
  13654. if (camera instanceof BABYLON.FreeCamera) {
  13655. serializationObject.cameras.push(serializeCamera(camera));
  13656. }
  13657. }
  13658. if (scene.activeCamera) {
  13659. serializationObject.activeCameraID = scene.activeCamera.id;
  13660. }
  13661. serializationObject.materials = [];
  13662. serializationObject.multiMaterials = [];
  13663. for (index = 0; index < scene.materials.length; index++) {
  13664. var material = scene.materials[index];
  13665. if (material instanceof BABYLON.StandardMaterial) {
  13666. serializationObject.materials.push(serializeMaterial(material));
  13667. } else if (material instanceof BABYLON.MultiMaterial) {
  13668. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13669. }
  13670. }
  13671. serializationObject.skeletons = [];
  13672. for (index = 0; index < scene.skeletons.length; index++) {
  13673. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13674. }
  13675. serializationObject.geometries = {};
  13676. serializationObject.geometries.boxes = [];
  13677. serializationObject.geometries.spheres = [];
  13678. serializationObject.geometries.cylinders = [];
  13679. serializationObject.geometries.toruses = [];
  13680. serializationObject.geometries.grounds = [];
  13681. serializationObject.geometries.planes = [];
  13682. serializationObject.geometries.torusKnots = [];
  13683. serializationObject.geometries.vertexData = [];
  13684. serializedGeometries = [];
  13685. var geometries = scene.getGeometries();
  13686. for (var index = 0; index < geometries.length; index++) {
  13687. var geometry = geometries[index];
  13688. if (geometry.isReady()) {
  13689. serializeGeometry(geometry, serializationObject.geometries);
  13690. }
  13691. }
  13692. serializationObject.meshes = [];
  13693. for (index = 0; index < scene.meshes.length; index++) {
  13694. var abstractMesh = scene.meshes[index];
  13695. if (abstractMesh instanceof BABYLON.Mesh) {
  13696. var mesh = abstractMesh;
  13697. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13698. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13699. }
  13700. }
  13701. }
  13702. serializationObject.particleSystems = [];
  13703. for (index = 0; index < scene.particleSystems.length; index++) {
  13704. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13705. }
  13706. serializationObject.lensFlareSystems = [];
  13707. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13708. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13709. }
  13710. serializationObject.shadowGenerators = [];
  13711. for (index = 0; index < scene.lights.length; index++) {
  13712. light = scene.lights[index];
  13713. if (light.getShadowGenerator()) {
  13714. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13715. }
  13716. }
  13717. return serializationObject;
  13718. };
  13719. return SceneSerializer;
  13720. })();
  13721. BABYLON.SceneSerializer = SceneSerializer;
  13722. })(BABYLON || (BABYLON = {}));
  13723. var BABYLON;
  13724. (function (BABYLON) {
  13725. var SceneLoader = (function () {
  13726. function SceneLoader() {
  13727. }
  13728. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13729. get: function () {
  13730. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13731. },
  13732. set: function (value) {
  13733. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13734. },
  13735. enumerable: true,
  13736. configurable: true
  13737. });
  13738. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13739. get: function () {
  13740. return SceneLoader._ShowLoadingScreen;
  13741. },
  13742. set: function (value) {
  13743. SceneLoader._ShowLoadingScreen = value;
  13744. },
  13745. enumerable: true,
  13746. configurable: true
  13747. });
  13748. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13749. var dotPosition = sceneFilename.lastIndexOf(".");
  13750. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13751. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13752. var plugin = this._registeredPlugins[index];
  13753. if (plugin.extensions.indexOf(extension) !== -1) {
  13754. return plugin;
  13755. }
  13756. }
  13757. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13758. };
  13759. SceneLoader.RegisterPlugin = function (plugin) {
  13760. plugin.extensions = plugin.extensions.toLowerCase();
  13761. SceneLoader._registeredPlugins.push(plugin);
  13762. };
  13763. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13764. var _this = this;
  13765. var manifestChecked = function (success) {
  13766. scene.database = database;
  13767. var plugin = _this._getPluginForFilename(sceneFilename);
  13768. var importMeshFromData = function (data) {
  13769. var meshes = [];
  13770. var particleSystems = [];
  13771. var skeletons = [];
  13772. try {
  13773. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13774. if (onerror) {
  13775. onerror(scene);
  13776. }
  13777. return;
  13778. }
  13779. } catch (e) {
  13780. if (onerror) {
  13781. onerror(scene);
  13782. }
  13783. return;
  13784. }
  13785. if (onsuccess) {
  13786. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13787. onsuccess(meshes, particleSystems, skeletons);
  13788. }
  13789. };
  13790. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13791. importMeshFromData(sceneFilename.substr(5));
  13792. return;
  13793. }
  13794. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13795. importMeshFromData(data);
  13796. }, progressCallBack, database);
  13797. };
  13798. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13799. };
  13800. /**
  13801. * Load a scene
  13802. * @param rootUrl a string that defines the root url for scene and resources
  13803. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13804. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13805. */
  13806. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13807. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13808. };
  13809. /**
  13810. * Append a scene
  13811. * @param rootUrl a string that defines the root url for scene and resources
  13812. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13813. * @param scene is the instance of BABYLON.Scene to append to
  13814. */
  13815. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13816. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13817. var database;
  13818. if (SceneLoader.ShowLoadingScreen) {
  13819. scene.getEngine().displayLoadingUI();
  13820. }
  13821. var loadSceneFromData = function (data) {
  13822. scene.database = database;
  13823. if (!plugin.load(scene, data, rootUrl)) {
  13824. if (onerror) {
  13825. onerror(scene);
  13826. }
  13827. scene.getEngine().hideLoadingUI();
  13828. return;
  13829. }
  13830. if (onsuccess) {
  13831. onsuccess(scene);
  13832. }
  13833. if (SceneLoader.ShowLoadingScreen) {
  13834. scene.executeWhenReady(function () {
  13835. scene.getEngine().hideLoadingUI();
  13836. });
  13837. }
  13838. };
  13839. var manifestChecked = function (success) {
  13840. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13841. };
  13842. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13843. loadSceneFromData(sceneFilename.substr(5));
  13844. return;
  13845. }
  13846. if (rootUrl.indexOf("file:") === -1) {
  13847. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13848. } else {
  13849. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13850. }
  13851. };
  13852. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13853. SceneLoader._ShowLoadingScreen = true;
  13854. SceneLoader._registeredPlugins = new Array();
  13855. return SceneLoader;
  13856. })();
  13857. BABYLON.SceneLoader = SceneLoader;
  13858. ;
  13859. })(BABYLON || (BABYLON = {}));
  13860. var BABYLON;
  13861. (function (BABYLON) {
  13862. (function (Internals) {
  13863. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13864. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13865. texture.name = parsedTexture.name;
  13866. texture.hasAlpha = parsedTexture.hasAlpha;
  13867. texture.level = parsedTexture.level;
  13868. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13869. return texture;
  13870. };
  13871. var loadTexture = function (rootUrl, parsedTexture, scene) {
  13872. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  13873. return null;
  13874. }
  13875. if (parsedTexture.isCube) {
  13876. return loadCubeTexture(rootUrl, parsedTexture, scene);
  13877. }
  13878. var texture;
  13879. if (parsedTexture.mirrorPlane) {
  13880. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13881. texture._waitingRenderList = parsedTexture.renderList;
  13882. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  13883. } else if (parsedTexture.isRenderTarget) {
  13884. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13885. texture._waitingRenderList = parsedTexture.renderList;
  13886. } else {
  13887. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  13888. }
  13889. texture.name = parsedTexture.name;
  13890. texture.hasAlpha = parsedTexture.hasAlpha;
  13891. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  13892. texture.level = parsedTexture.level;
  13893. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  13894. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13895. texture.uOffset = parsedTexture.uOffset;
  13896. texture.vOffset = parsedTexture.vOffset;
  13897. texture.uScale = parsedTexture.uScale;
  13898. texture.vScale = parsedTexture.vScale;
  13899. texture.uAng = parsedTexture.uAng;
  13900. texture.vAng = parsedTexture.vAng;
  13901. texture.wAng = parsedTexture.wAng;
  13902. texture.wrapU = parsedTexture.wrapU;
  13903. texture.wrapV = parsedTexture.wrapV;
  13904. if (parsedTexture.animations) {
  13905. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  13906. var parsedAnimation = parsedTexture.animations[animationIndex];
  13907. texture.animations.push(parseAnimation(parsedAnimation));
  13908. }
  13909. }
  13910. return texture;
  13911. };
  13912. var parseSkeleton = function (parsedSkeleton, scene) {
  13913. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  13914. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  13915. var parsedBone = parsedSkeleton.bones[index];
  13916. var parentBone = null;
  13917. if (parsedBone.parentBoneIndex > -1) {
  13918. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  13919. }
  13920. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  13921. if (parsedBone.animation) {
  13922. bone.animations.push(parseAnimation(parsedBone.animation));
  13923. }
  13924. }
  13925. return skeleton;
  13926. };
  13927. var parseFresnelParameters = function (parsedFresnelParameters) {
  13928. var fresnelParameters = new BABYLON.FresnelParameters();
  13929. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  13930. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  13931. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  13932. fresnelParameters.bias = parsedFresnelParameters.bias;
  13933. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  13934. return fresnelParameters;
  13935. };
  13936. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  13937. var material;
  13938. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  13939. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  13940. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  13941. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  13942. material.specularPower = parsedMaterial.specularPower;
  13943. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  13944. material.alpha = parsedMaterial.alpha;
  13945. material.id = parsedMaterial.id;
  13946. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  13947. material.backFaceCulling = parsedMaterial.backFaceCulling;
  13948. material.wireframe = parsedMaterial.wireframe;
  13949. if (parsedMaterial.diffuseTexture) {
  13950. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  13951. }
  13952. if (parsedMaterial.diffuseFresnelParameters) {
  13953. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  13954. }
  13955. if (parsedMaterial.ambientTexture) {
  13956. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  13957. }
  13958. if (parsedMaterial.opacityTexture) {
  13959. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  13960. }
  13961. if (parsedMaterial.opacityFresnelParameters) {
  13962. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  13963. }
  13964. if (parsedMaterial.reflectionTexture) {
  13965. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  13966. }
  13967. if (parsedMaterial.reflectionFresnelParameters) {
  13968. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  13969. }
  13970. if (parsedMaterial.emissiveTexture) {
  13971. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  13972. }
  13973. if (parsedMaterial.emissiveFresnelParameters) {
  13974. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  13975. }
  13976. if (parsedMaterial.specularTexture) {
  13977. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  13978. }
  13979. if (parsedMaterial.bumpTexture) {
  13980. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  13981. }
  13982. return material;
  13983. };
  13984. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  13985. for (var index = 0; index < parsedData.materials.length; index++) {
  13986. var parsedMaterial = parsedData.materials[index];
  13987. if (parsedMaterial.id === id) {
  13988. return parseMaterial(parsedMaterial, scene, rootUrl);
  13989. }
  13990. }
  13991. return null;
  13992. };
  13993. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  13994. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  13995. multiMaterial.id = parsedMultiMaterial.id;
  13996. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  13997. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  13998. var subMatId = parsedMultiMaterial.materials[matIndex];
  13999. if (subMatId) {
  14000. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14001. } else {
  14002. multiMaterial.subMaterials.push(null);
  14003. }
  14004. }
  14005. return multiMaterial;
  14006. };
  14007. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14008. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14009. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14010. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14011. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14012. var parsedFlare = parsedLensFlareSystem.flares[index];
  14013. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14014. }
  14015. return lensFlareSystem;
  14016. };
  14017. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14018. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14019. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14020. if (parsedParticleSystem.textureName) {
  14021. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14022. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14023. }
  14024. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14025. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14026. particleSystem.minSize = parsedParticleSystem.minSize;
  14027. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14028. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14029. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14030. particleSystem.emitter = emitter;
  14031. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14032. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14033. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14034. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14035. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14036. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14037. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14038. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14039. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14040. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14041. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14042. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14043. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14044. particleSystem.start();
  14045. return particleSystem;
  14046. };
  14047. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14048. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14049. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14050. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14051. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14052. shadowGenerator.getShadowMap().renderList.push(mesh);
  14053. }
  14054. if (parsedShadowGenerator.usePoissonSampling) {
  14055. shadowGenerator.usePoissonSampling = true;
  14056. } else {
  14057. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14058. }
  14059. return shadowGenerator;
  14060. };
  14061. var parseAnimation = function (parsedAnimation) {
  14062. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14063. var dataType = parsedAnimation.dataType;
  14064. var keys = [];
  14065. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14066. var key = parsedAnimation.keys[index];
  14067. var data;
  14068. switch (dataType) {
  14069. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14070. data = key.values[0];
  14071. break;
  14072. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14073. data = BABYLON.Quaternion.FromArray(key.values);
  14074. break;
  14075. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14076. data = BABYLON.Matrix.FromArray(key.values);
  14077. break;
  14078. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14079. default:
  14080. data = BABYLON.Vector3.FromArray(key.values);
  14081. break;
  14082. }
  14083. keys.push({
  14084. frame: key.frame,
  14085. value: data
  14086. });
  14087. }
  14088. animation.setKeys(keys);
  14089. return animation;
  14090. };
  14091. var parseLight = function (parsedLight, scene) {
  14092. var light;
  14093. switch (parsedLight.type) {
  14094. case 0:
  14095. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14096. break;
  14097. case 1:
  14098. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14099. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14100. break;
  14101. case 2:
  14102. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14103. break;
  14104. case 3:
  14105. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14106. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14107. break;
  14108. }
  14109. light.id = parsedLight.id;
  14110. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14111. if (parsedLight.intensity !== undefined) {
  14112. light.intensity = parsedLight.intensity;
  14113. }
  14114. if (parsedLight.range) {
  14115. light.range = parsedLight.range;
  14116. }
  14117. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14118. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14119. if (parsedLight.excludedMeshesIds) {
  14120. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14121. }
  14122. if (parsedLight.includedOnlyMeshesIds) {
  14123. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14124. }
  14125. if (parsedLight.animations) {
  14126. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14127. var parsedAnimation = parsedLight.animations[animationIndex];
  14128. light.animations.push(parseAnimation(parsedAnimation));
  14129. }
  14130. }
  14131. if (parsedLight.autoAnimate) {
  14132. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14133. }
  14134. };
  14135. var parseCamera = function (parsedCamera, scene) {
  14136. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14137. camera.id = parsedCamera.id;
  14138. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14139. if (parsedCamera.parentId) {
  14140. camera._waitingParentId = parsedCamera.parentId;
  14141. }
  14142. if (parsedCamera.target) {
  14143. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14144. } else {
  14145. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14146. }
  14147. if (parsedCamera.lockedTargetId) {
  14148. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14149. }
  14150. camera.fov = parsedCamera.fov;
  14151. camera.minZ = parsedCamera.minZ;
  14152. camera.maxZ = parsedCamera.maxZ;
  14153. camera.speed = parsedCamera.speed;
  14154. camera.inertia = parsedCamera.inertia;
  14155. camera.checkCollisions = parsedCamera.checkCollisions;
  14156. camera.applyGravity = parsedCamera.applyGravity;
  14157. if (parsedCamera.ellipsoid) {
  14158. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14159. }
  14160. if (parsedCamera.animations) {
  14161. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14162. var parsedAnimation = parsedCamera.animations[animationIndex];
  14163. camera.animations.push(parseAnimation(parsedAnimation));
  14164. }
  14165. }
  14166. if (parsedCamera.autoAnimate) {
  14167. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14168. }
  14169. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14170. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14171. } else {
  14172. camera.layerMask = 0xFFFFFFFF;
  14173. }
  14174. return camera;
  14175. };
  14176. var parseGeometry = function (parsedGeometry, scene) {
  14177. var id = parsedGeometry.id;
  14178. return scene.getGeometryByID(id);
  14179. };
  14180. var parseBox = function (parsedBox, scene) {
  14181. if (parseGeometry(parsedBox, scene)) {
  14182. return null;
  14183. }
  14184. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14185. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14186. scene.pushGeometry(box, true);
  14187. return box;
  14188. };
  14189. var parseSphere = function (parsedSphere, scene) {
  14190. if (parseGeometry(parsedSphere, scene)) {
  14191. return null;
  14192. }
  14193. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14194. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14195. scene.pushGeometry(sphere, true);
  14196. return sphere;
  14197. };
  14198. var parseCylinder = function (parsedCylinder, scene) {
  14199. if (parseGeometry(parsedCylinder, scene)) {
  14200. return null;
  14201. }
  14202. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14203. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14204. scene.pushGeometry(cylinder, true);
  14205. return cylinder;
  14206. };
  14207. var parseTorus = function (parsedTorus, scene) {
  14208. if (parseGeometry(parsedTorus, scene)) {
  14209. return null;
  14210. }
  14211. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14212. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14213. scene.pushGeometry(torus, true);
  14214. return torus;
  14215. };
  14216. var parseGround = function (parsedGround, scene) {
  14217. if (parseGeometry(parsedGround, scene)) {
  14218. return null;
  14219. }
  14220. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14221. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14222. scene.pushGeometry(ground, true);
  14223. return ground;
  14224. };
  14225. var parsePlane = function (parsedPlane, scene) {
  14226. if (parseGeometry(parsedPlane, scene)) {
  14227. return null;
  14228. }
  14229. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14230. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14231. scene.pushGeometry(plane, true);
  14232. return plane;
  14233. };
  14234. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14235. if (parseGeometry(parsedTorusKnot, scene)) {
  14236. return null;
  14237. }
  14238. 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);
  14239. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14240. scene.pushGeometry(torusKnot, true);
  14241. return torusKnot;
  14242. };
  14243. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14244. if (parseGeometry(parsedVertexData, scene)) {
  14245. return null;
  14246. }
  14247. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14248. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14249. if (parsedVertexData.delayLoadingFile) {
  14250. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14251. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14252. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14253. geometry._delayInfo = [];
  14254. if (parsedVertexData.hasUVs) {
  14255. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14256. }
  14257. if (parsedVertexData.hasUVs2) {
  14258. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14259. }
  14260. if (parsedVertexData.hasColors) {
  14261. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14262. }
  14263. if (parsedVertexData.hasMatricesIndices) {
  14264. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14265. }
  14266. if (parsedVertexData.hasMatricesWeights) {
  14267. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14268. }
  14269. geometry._delayLoadingFunction = importVertexData;
  14270. } else {
  14271. importVertexData(parsedVertexData, geometry);
  14272. }
  14273. scene.pushGeometry(geometry, true);
  14274. return geometry;
  14275. };
  14276. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14277. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14278. mesh.id = parsedMesh.id;
  14279. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14280. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14281. if (parsedMesh.rotationQuaternion) {
  14282. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14283. } else if (parsedMesh.rotation) {
  14284. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14285. }
  14286. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14287. if (parsedMesh.localMatrix) {
  14288. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14289. } else if (parsedMesh.pivotMatrix) {
  14290. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14291. }
  14292. mesh.setEnabled(parsedMesh.isEnabled);
  14293. mesh.isVisible = parsedMesh.isVisible;
  14294. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14295. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14296. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14297. if (parsedMesh.pickable !== undefined) {
  14298. mesh.isPickable = parsedMesh.pickable;
  14299. }
  14300. mesh.receiveShadows = parsedMesh.receiveShadows;
  14301. mesh.billboardMode = parsedMesh.billboardMode;
  14302. if (parsedMesh.visibility !== undefined) {
  14303. mesh.visibility = parsedMesh.visibility;
  14304. }
  14305. mesh.checkCollisions = parsedMesh.checkCollisions;
  14306. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14307. if (parsedMesh.parentId) {
  14308. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14309. }
  14310. if (parsedMesh.delayLoadingFile) {
  14311. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14312. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14313. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14314. mesh._delayInfo = [];
  14315. if (parsedMesh.hasUVs) {
  14316. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14317. }
  14318. if (parsedMesh.hasUVs2) {
  14319. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14320. }
  14321. if (parsedMesh.hasColors) {
  14322. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14323. }
  14324. if (parsedMesh.hasMatricesIndices) {
  14325. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14326. }
  14327. if (parsedMesh.hasMatricesWeights) {
  14328. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14329. }
  14330. mesh._delayLoadingFunction = importGeometry;
  14331. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14332. mesh._checkDelayState();
  14333. }
  14334. } else {
  14335. importGeometry(parsedMesh, mesh);
  14336. }
  14337. if (parsedMesh.materialId) {
  14338. mesh.setMaterialByID(parsedMesh.materialId);
  14339. } else {
  14340. mesh.material = null;
  14341. }
  14342. if (parsedMesh.skeletonId > -1) {
  14343. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14344. }
  14345. if (parsedMesh.physicsImpostor) {
  14346. if (!scene.isPhysicsEnabled()) {
  14347. scene.enablePhysics();
  14348. }
  14349. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14350. }
  14351. if (parsedMesh.animations) {
  14352. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14353. var parsedAnimation = parsedMesh.animations[animationIndex];
  14354. mesh.animations.push(parseAnimation(parsedAnimation));
  14355. }
  14356. }
  14357. if (parsedMesh.autoAnimate) {
  14358. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14359. }
  14360. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14361. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14362. } else {
  14363. mesh.layerMask = 0xFFFFFFFF;
  14364. }
  14365. if (parsedMesh.instances) {
  14366. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14367. var parsedInstance = parsedMesh.instances[index];
  14368. var instance = mesh.createInstance(parsedInstance.name);
  14369. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14370. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14371. if (parsedInstance.rotationQuaternion) {
  14372. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14373. } else if (parsedInstance.rotation) {
  14374. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14375. }
  14376. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14377. instance.checkCollisions = mesh.checkCollisions;
  14378. if (parsedMesh.animations) {
  14379. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14380. parsedAnimation = parsedMesh.animations[animationIndex];
  14381. instance.animations.push(parseAnimation(parsedAnimation));
  14382. }
  14383. }
  14384. }
  14385. }
  14386. return mesh;
  14387. };
  14388. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14389. names = (names instanceof Array) ? names : [names];
  14390. for (var i in names) {
  14391. if (mesh.name === names[i]) {
  14392. hierarchyIds.push(mesh.id);
  14393. return true;
  14394. }
  14395. }
  14396. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14397. hierarchyIds.push(mesh.id);
  14398. return true;
  14399. }
  14400. return false;
  14401. };
  14402. var importVertexData = function (parsedVertexData, geometry) {
  14403. var vertexData = new BABYLON.VertexData();
  14404. var positions = parsedVertexData.positions;
  14405. if (positions) {
  14406. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14407. }
  14408. var normals = parsedVertexData.normals;
  14409. if (normals) {
  14410. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14411. }
  14412. var uvs = parsedVertexData.uvs;
  14413. if (uvs) {
  14414. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14415. }
  14416. var uv2s = parsedVertexData.uv2s;
  14417. if (uv2s) {
  14418. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14419. }
  14420. var colors = parsedVertexData.colors;
  14421. if (colors) {
  14422. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14423. }
  14424. var matricesIndices = parsedVertexData.matricesIndices;
  14425. if (matricesIndices) {
  14426. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14427. }
  14428. var matricesWeights = parsedVertexData.matricesWeights;
  14429. if (matricesWeights) {
  14430. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14431. }
  14432. var indices = parsedVertexData.indices;
  14433. if (indices) {
  14434. vertexData.indices = indices;
  14435. }
  14436. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14437. };
  14438. var importGeometry = function (parsedGeometry, mesh) {
  14439. var scene = mesh.getScene();
  14440. var geometryId = parsedGeometry.geometryId;
  14441. if (geometryId) {
  14442. var geometry = scene.getGeometryByID(geometryId);
  14443. if (geometry) {
  14444. geometry.applyToMesh(mesh);
  14445. }
  14446. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14447. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14448. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14449. if (parsedGeometry.uvs) {
  14450. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14451. }
  14452. if (parsedGeometry.uvs2) {
  14453. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14454. }
  14455. if (parsedGeometry.colors) {
  14456. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14457. }
  14458. if (parsedGeometry.matricesIndices) {
  14459. if (!parsedGeometry.matricesIndices._isExpanded) {
  14460. var floatIndices = [];
  14461. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14462. var matricesIndex = parsedGeometry.matricesIndices[i];
  14463. floatIndices.push(matricesIndex & 0x000000FF);
  14464. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14465. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14466. floatIndices.push(matricesIndex >> 24);
  14467. }
  14468. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14469. } else {
  14470. delete parsedGeometry.matricesIndices._isExpanded;
  14471. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14472. }
  14473. }
  14474. if (parsedGeometry.matricesWeights) {
  14475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14476. }
  14477. mesh.setIndices(parsedGeometry.indices);
  14478. }
  14479. if (parsedGeometry.subMeshes) {
  14480. mesh.subMeshes = [];
  14481. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14482. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14483. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14484. }
  14485. }
  14486. if (mesh._shouldGenerateFlatShading) {
  14487. mesh.convertToFlatShadedMesh();
  14488. delete mesh._shouldGenerateFlatShading;
  14489. }
  14490. mesh.computeWorldMatrix(true);
  14491. if (scene._selectionOctree) {
  14492. scene._selectionOctree.addMesh(mesh);
  14493. }
  14494. };
  14495. BABYLON.SceneLoader.RegisterPlugin({
  14496. extensions: ".babylon",
  14497. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14498. var parsedData = JSON.parse(data);
  14499. var loadedSkeletonsIds = [];
  14500. var loadedMaterialsIds = [];
  14501. var hierarchyIds = [];
  14502. for (var index = 0; index < parsedData.meshes.length; index++) {
  14503. var parsedMesh = parsedData.meshes[index];
  14504. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14505. if (meshesNames instanceof Array) {
  14506. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14507. }
  14508. if (parsedMesh.materialId) {
  14509. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14510. if (!materialFound) {
  14511. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14512. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14513. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14514. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14515. var subMatId = parsedMultiMaterial.materials[matIndex];
  14516. loadedMaterialsIds.push(subMatId);
  14517. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14518. }
  14519. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14520. parseMultiMaterial(parsedMultiMaterial, scene);
  14521. materialFound = true;
  14522. break;
  14523. }
  14524. }
  14525. }
  14526. if (!materialFound) {
  14527. loadedMaterialsIds.push(parsedMesh.materialId);
  14528. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14529. }
  14530. }
  14531. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14532. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14533. if (!skeletonAlreadyLoaded) {
  14534. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14535. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14536. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14537. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14538. loadedSkeletonsIds.push(parsedSkeleton.id);
  14539. }
  14540. }
  14541. }
  14542. }
  14543. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14544. meshes.push(mesh);
  14545. }
  14546. }
  14547. if (parsedData.particleSystems) {
  14548. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14549. var parsedParticleSystem = parsedData.particleSystems[index];
  14550. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14551. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14552. }
  14553. }
  14554. }
  14555. return true;
  14556. },
  14557. load: function (scene, data, rootUrl) {
  14558. var parsedData = JSON.parse(data);
  14559. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14560. scene.autoClear = parsedData.autoClear;
  14561. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14562. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14563. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14564. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14565. scene.fogMode = parsedData.fogMode;
  14566. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14567. scene.fogStart = parsedData.fogStart;
  14568. scene.fogEnd = parsedData.fogEnd;
  14569. scene.fogDensity = parsedData.fogDensity;
  14570. }
  14571. for (var index = 0; index < parsedData.lights.length; index++) {
  14572. var parsedLight = parsedData.lights[index];
  14573. parseLight(parsedLight, scene);
  14574. }
  14575. for (index = 0; index < parsedData.cameras.length; index++) {
  14576. var parsedCamera = parsedData.cameras[index];
  14577. parseCamera(parsedCamera, scene);
  14578. }
  14579. if (parsedData.activeCameraID) {
  14580. scene.setActiveCameraByID(parsedData.activeCameraID);
  14581. }
  14582. if (parsedData.materials) {
  14583. for (index = 0; index < parsedData.materials.length; index++) {
  14584. var parsedMaterial = parsedData.materials[index];
  14585. parseMaterial(parsedMaterial, scene, rootUrl);
  14586. }
  14587. }
  14588. if (parsedData.multiMaterials) {
  14589. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14590. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14591. parseMultiMaterial(parsedMultiMaterial, scene);
  14592. }
  14593. }
  14594. if (parsedData.skeletons) {
  14595. for (index = 0; index < parsedData.skeletons.length; index++) {
  14596. var parsedSkeleton = parsedData.skeletons[index];
  14597. parseSkeleton(parsedSkeleton, scene);
  14598. }
  14599. }
  14600. var geometries = parsedData.geometries;
  14601. if (geometries) {
  14602. var boxes = geometries.boxes;
  14603. if (boxes) {
  14604. for (index = 0; index < boxes.length; index++) {
  14605. var parsedBox = boxes[index];
  14606. parseBox(parsedBox, scene);
  14607. }
  14608. }
  14609. var spheres = geometries.spheres;
  14610. if (spheres) {
  14611. for (index = 0; index < spheres.length; index++) {
  14612. var parsedSphere = spheres[index];
  14613. parseSphere(parsedSphere, scene);
  14614. }
  14615. }
  14616. var cylinders = geometries.cylinders;
  14617. if (cylinders) {
  14618. for (index = 0; index < cylinders.length; index++) {
  14619. var parsedCylinder = cylinders[index];
  14620. parseCylinder(parsedCylinder, scene);
  14621. }
  14622. }
  14623. var toruses = geometries.toruses;
  14624. if (toruses) {
  14625. for (index = 0; index < toruses.length; index++) {
  14626. var parsedTorus = toruses[index];
  14627. parseTorus(parsedTorus, scene);
  14628. }
  14629. }
  14630. var grounds = geometries.grounds;
  14631. if (grounds) {
  14632. for (index = 0; index < grounds.length; index++) {
  14633. var parsedGround = grounds[index];
  14634. parseGround(parsedGround, scene);
  14635. }
  14636. }
  14637. var planes = geometries.planes;
  14638. if (planes) {
  14639. for (index = 0; index < planes.length; index++) {
  14640. var parsedPlane = planes[index];
  14641. parsePlane(parsedPlane, scene);
  14642. }
  14643. }
  14644. var torusKnots = geometries.torusKnots;
  14645. if (torusKnots) {
  14646. for (index = 0; index < torusKnots.length; index++) {
  14647. var parsedTorusKnot = torusKnots[index];
  14648. parseTorusKnot(parsedTorusKnot, scene);
  14649. }
  14650. }
  14651. var vertexData = geometries.vertexData;
  14652. if (vertexData) {
  14653. for (index = 0; index < vertexData.length; index++) {
  14654. var parsedVertexData = vertexData[index];
  14655. parseVertexData(parsedVertexData, scene, rootUrl);
  14656. }
  14657. }
  14658. }
  14659. for (index = 0; index < parsedData.meshes.length; index++) {
  14660. var parsedMesh = parsedData.meshes[index];
  14661. parseMesh(parsedMesh, scene, rootUrl);
  14662. }
  14663. for (index = 0; index < scene.cameras.length; index++) {
  14664. var camera = scene.cameras[index];
  14665. if (camera._waitingParentId) {
  14666. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14667. delete camera._waitingParentId;
  14668. }
  14669. if (camera instanceof BABYLON.FreeCamera) {
  14670. var freecamera = camera;
  14671. if (freecamera._waitingLockedTargetId) {
  14672. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14673. delete freecamera._waitingLockedTargetId;
  14674. }
  14675. }
  14676. }
  14677. if (parsedData.particleSystems) {
  14678. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14679. var parsedParticleSystem = parsedData.particleSystems[index];
  14680. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14681. }
  14682. }
  14683. if (parsedData.lensFlareSystems) {
  14684. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14685. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14686. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14687. }
  14688. }
  14689. if (parsedData.shadowGenerators) {
  14690. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14691. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14692. parseShadowGenerator(parsedShadowGenerator, scene);
  14693. }
  14694. }
  14695. return true;
  14696. }
  14697. });
  14698. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14699. var Internals = BABYLON.Internals;
  14700. })(BABYLON || (BABYLON = {}));
  14701. var BABYLON;
  14702. (function (BABYLON) {
  14703. var currentCSGMeshId = 0;
  14704. var Vertex = (function () {
  14705. function Vertex(pos, normal, uv) {
  14706. this.pos = pos;
  14707. this.normal = normal;
  14708. this.uv = uv;
  14709. }
  14710. Vertex.prototype.clone = function () {
  14711. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14712. };
  14713. Vertex.prototype.flip = function () {
  14714. this.normal = this.normal.scale(-1);
  14715. };
  14716. Vertex.prototype.interpolate = function (other, t) {
  14717. 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));
  14718. };
  14719. return Vertex;
  14720. })();
  14721. var Plane = (function () {
  14722. function Plane(normal, w) {
  14723. this.normal = normal;
  14724. this.w = w;
  14725. }
  14726. Plane.FromPoints = function (a, b, c) {
  14727. var v0 = c.subtract(a);
  14728. var v1 = b.subtract(a);
  14729. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14730. return null;
  14731. }
  14732. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14733. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14734. };
  14735. Plane.prototype.clone = function () {
  14736. return new Plane(this.normal.clone(), this.w);
  14737. };
  14738. Plane.prototype.flip = function () {
  14739. this.normal.scaleInPlace(-1);
  14740. this.w = -this.w;
  14741. };
  14742. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14743. var COPLANAR = 0;
  14744. var FRONT = 1;
  14745. var BACK = 2;
  14746. var SPANNING = 3;
  14747. var polygonType = 0;
  14748. var types = [];
  14749. for (var i = 0; i < polygon.vertices.length; i++) {
  14750. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14751. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14752. polygonType |= type;
  14753. types.push(type);
  14754. }
  14755. switch (polygonType) {
  14756. case COPLANAR:
  14757. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14758. break;
  14759. case FRONT:
  14760. front.push(polygon);
  14761. break;
  14762. case BACK:
  14763. back.push(polygon);
  14764. break;
  14765. case SPANNING:
  14766. var f = [], b = [];
  14767. for (i = 0; i < polygon.vertices.length; i++) {
  14768. var j = (i + 1) % polygon.vertices.length;
  14769. var ti = types[i], tj = types[j];
  14770. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14771. if (ti != BACK)
  14772. f.push(vi);
  14773. if (ti != FRONT)
  14774. b.push(ti != BACK ? vi.clone() : vi);
  14775. if ((ti | tj) == SPANNING) {
  14776. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14777. var v = vi.interpolate(vj, t);
  14778. f.push(v);
  14779. b.push(v.clone());
  14780. }
  14781. }
  14782. if (f.length >= 3) {
  14783. var poly = new Polygon(f, polygon.shared);
  14784. if (poly.plane)
  14785. front.push(poly);
  14786. }
  14787. if (b.length >= 3) {
  14788. poly = new Polygon(b, polygon.shared);
  14789. if (poly.plane)
  14790. back.push(poly);
  14791. }
  14792. break;
  14793. }
  14794. };
  14795. Plane.EPSILON = 1e-5;
  14796. return Plane;
  14797. })();
  14798. var Polygon = (function () {
  14799. function Polygon(vertices, shared) {
  14800. this.vertices = vertices;
  14801. this.shared = shared;
  14802. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14803. }
  14804. Polygon.prototype.clone = function () {
  14805. var vertices = this.vertices.map(function (v) {
  14806. return v.clone();
  14807. });
  14808. return new Polygon(vertices, this.shared);
  14809. };
  14810. Polygon.prototype.flip = function () {
  14811. this.vertices.reverse().map(function (v) {
  14812. v.flip();
  14813. });
  14814. this.plane.flip();
  14815. };
  14816. return Polygon;
  14817. })();
  14818. var Node = (function () {
  14819. function Node(polygons) {
  14820. this.plane = null;
  14821. this.front = null;
  14822. this.back = null;
  14823. this.polygons = [];
  14824. if (polygons) {
  14825. this.build(polygons);
  14826. }
  14827. }
  14828. Node.prototype.clone = function () {
  14829. var node = new Node();
  14830. node.plane = this.plane && this.plane.clone();
  14831. node.front = this.front && this.front.clone();
  14832. node.back = this.back && this.back.clone();
  14833. node.polygons = this.polygons.map(function (p) {
  14834. return p.clone();
  14835. });
  14836. return node;
  14837. };
  14838. Node.prototype.invert = function () {
  14839. for (var i = 0; i < this.polygons.length; i++) {
  14840. this.polygons[i].flip();
  14841. }
  14842. if (this.plane) {
  14843. this.plane.flip();
  14844. }
  14845. if (this.front) {
  14846. this.front.invert();
  14847. }
  14848. if (this.back) {
  14849. this.back.invert();
  14850. }
  14851. var temp = this.front;
  14852. this.front = this.back;
  14853. this.back = temp;
  14854. };
  14855. Node.prototype.clipPolygons = function (polygons) {
  14856. if (!this.plane)
  14857. return polygons.slice();
  14858. var front = [], back = [];
  14859. for (var i = 0; i < polygons.length; i++) {
  14860. this.plane.splitPolygon(polygons[i], front, back, front, back);
  14861. }
  14862. if (this.front) {
  14863. front = this.front.clipPolygons(front);
  14864. }
  14865. if (this.back) {
  14866. back = this.back.clipPolygons(back);
  14867. } else {
  14868. back = [];
  14869. }
  14870. return front.concat(back);
  14871. };
  14872. Node.prototype.clipTo = function (bsp) {
  14873. this.polygons = bsp.clipPolygons(this.polygons);
  14874. if (this.front)
  14875. this.front.clipTo(bsp);
  14876. if (this.back)
  14877. this.back.clipTo(bsp);
  14878. };
  14879. Node.prototype.allPolygons = function () {
  14880. var polygons = this.polygons.slice();
  14881. if (this.front)
  14882. polygons = polygons.concat(this.front.allPolygons());
  14883. if (this.back)
  14884. polygons = polygons.concat(this.back.allPolygons());
  14885. return polygons;
  14886. };
  14887. Node.prototype.build = function (polygons) {
  14888. if (!polygons.length)
  14889. return;
  14890. if (!this.plane)
  14891. this.plane = polygons[0].plane.clone();
  14892. var front = [], back = [];
  14893. for (var i = 0; i < polygons.length; i++) {
  14894. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  14895. }
  14896. if (front.length) {
  14897. if (!this.front)
  14898. this.front = new Node();
  14899. this.front.build(front);
  14900. }
  14901. if (back.length) {
  14902. if (!this.back)
  14903. this.back = new Node();
  14904. this.back.build(back);
  14905. }
  14906. };
  14907. return Node;
  14908. })();
  14909. var CSG = (function () {
  14910. function CSG() {
  14911. this.polygons = new Array();
  14912. }
  14913. CSG.FromMesh = function (mesh) {
  14914. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  14915. if (mesh instanceof BABYLON.Mesh) {
  14916. mesh.computeWorldMatrix(true);
  14917. var matrix = mesh.getWorldMatrix();
  14918. var meshPosition = mesh.position.clone();
  14919. var meshRotation = mesh.rotation.clone();
  14920. var meshScaling = mesh.scaling.clone();
  14921. } else {
  14922. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  14923. }
  14924. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14925. var subMeshes = mesh.subMeshes;
  14926. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  14927. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  14928. vertices = [];
  14929. for (var j = 0; j < 3; j++) {
  14930. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  14931. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  14932. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  14933. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  14934. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  14935. vertex = new Vertex(position, normal, uv);
  14936. vertices.push(vertex);
  14937. }
  14938. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  14939. if (polygon.plane)
  14940. polygons.push(polygon);
  14941. }
  14942. }
  14943. var csg = CSG.FromPolygons(polygons);
  14944. csg.matrix = matrix;
  14945. csg.position = meshPosition;
  14946. csg.rotation = meshRotation;
  14947. csg.scaling = meshScaling;
  14948. currentCSGMeshId++;
  14949. return csg;
  14950. };
  14951. CSG.FromPolygons = function (polygons) {
  14952. var csg = new BABYLON.CSG();
  14953. csg.polygons = polygons;
  14954. return csg;
  14955. };
  14956. CSG.prototype.clone = function () {
  14957. var csg = new BABYLON.CSG();
  14958. csg.polygons = this.polygons.map(function (p) {
  14959. return p.clone();
  14960. });
  14961. csg.copyTransformAttributes(this);
  14962. return csg;
  14963. };
  14964. CSG.prototype.toPolygons = function () {
  14965. return this.polygons;
  14966. };
  14967. CSG.prototype.union = function (csg) {
  14968. var a = new Node(this.clone().polygons);
  14969. var b = new Node(csg.clone().polygons);
  14970. a.clipTo(b);
  14971. b.clipTo(a);
  14972. b.invert();
  14973. b.clipTo(a);
  14974. b.invert();
  14975. a.build(b.allPolygons());
  14976. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  14977. };
  14978. CSG.prototype.unionInPlace = function (csg) {
  14979. var a = new Node(this.polygons);
  14980. var b = new Node(csg.polygons);
  14981. a.clipTo(b);
  14982. b.clipTo(a);
  14983. b.invert();
  14984. b.clipTo(a);
  14985. b.invert();
  14986. a.build(b.allPolygons());
  14987. this.polygons = a.allPolygons();
  14988. };
  14989. CSG.prototype.subtract = function (csg) {
  14990. var a = new Node(this.clone().polygons);
  14991. var b = new Node(csg.clone().polygons);
  14992. a.invert();
  14993. a.clipTo(b);
  14994. b.clipTo(a);
  14995. b.invert();
  14996. b.clipTo(a);
  14997. b.invert();
  14998. a.build(b.allPolygons());
  14999. a.invert();
  15000. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15001. };
  15002. CSG.prototype.subtractInPlace = function (csg) {
  15003. var a = new Node(this.polygons);
  15004. var b = new Node(csg.polygons);
  15005. a.invert();
  15006. a.clipTo(b);
  15007. b.clipTo(a);
  15008. b.invert();
  15009. b.clipTo(a);
  15010. b.invert();
  15011. a.build(b.allPolygons());
  15012. a.invert();
  15013. this.polygons = a.allPolygons();
  15014. };
  15015. CSG.prototype.intersect = function (csg) {
  15016. var a = new Node(this.clone().polygons);
  15017. var b = new Node(csg.clone().polygons);
  15018. a.invert();
  15019. b.clipTo(a);
  15020. b.invert();
  15021. a.clipTo(b);
  15022. b.clipTo(a);
  15023. a.build(b.allPolygons());
  15024. a.invert();
  15025. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15026. };
  15027. CSG.prototype.intersectInPlace = function (csg) {
  15028. var a = new Node(this.polygons);
  15029. var b = new Node(csg.polygons);
  15030. a.invert();
  15031. b.clipTo(a);
  15032. b.invert();
  15033. a.clipTo(b);
  15034. b.clipTo(a);
  15035. a.build(b.allPolygons());
  15036. a.invert();
  15037. this.polygons = a.allPolygons();
  15038. };
  15039. CSG.prototype.inverse = function () {
  15040. var csg = this.clone();
  15041. csg.inverseInPlace();
  15042. return csg;
  15043. };
  15044. CSG.prototype.inverseInPlace = function () {
  15045. this.polygons.map(function (p) {
  15046. p.flip();
  15047. });
  15048. };
  15049. CSG.prototype.copyTransformAttributes = function (csg) {
  15050. this.matrix = csg.matrix;
  15051. this.position = csg.position;
  15052. this.rotation = csg.rotation;
  15053. this.scaling = csg.scaling;
  15054. return this;
  15055. };
  15056. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15057. var matrix = this.matrix.clone();
  15058. matrix.invert();
  15059. 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;
  15060. if (keepSubMeshes) {
  15061. polygons.sort(function (a, b) {
  15062. if (a.shared.meshId === b.shared.meshId) {
  15063. return a.shared.subMeshId - b.shared.subMeshId;
  15064. } else {
  15065. return a.shared.meshId - b.shared.meshId;
  15066. }
  15067. });
  15068. }
  15069. for (var i = 0, il = polygons.length; i < il; i++) {
  15070. polygon = polygons[i];
  15071. if (!subMesh_dict[polygon.shared.meshId]) {
  15072. subMesh_dict[polygon.shared.meshId] = {};
  15073. }
  15074. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15075. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15076. indexStart: +Infinity,
  15077. indexEnd: -Infinity,
  15078. materialIndex: polygon.shared.materialIndex
  15079. };
  15080. }
  15081. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15082. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15083. polygonIndices[0] = 0;
  15084. polygonIndices[1] = j - 1;
  15085. polygonIndices[2] = j;
  15086. for (var k = 0; k < 3; k++) {
  15087. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15088. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15089. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15090. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15091. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15092. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15093. 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)) {
  15094. vertices.push(vertex.x, vertex.y, vertex.z);
  15095. uvs.push(uv.x, uv.y);
  15096. normals.push(normal.x, normal.y, normal.z);
  15097. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15098. }
  15099. indices.push(vertex_idx);
  15100. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15101. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15102. currentIndex++;
  15103. }
  15104. }
  15105. }
  15106. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15107. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15108. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15109. mesh.setIndices(indices);
  15110. if (keepSubMeshes) {
  15111. var materialIndexOffset = 0, materialMaxIndex;
  15112. mesh.subMeshes.length = 0;
  15113. for (var m in subMesh_dict) {
  15114. materialMaxIndex = -1;
  15115. for (var sm in subMesh_dict[m]) {
  15116. subMesh_obj = subMesh_dict[m][sm];
  15117. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15118. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15119. }
  15120. materialIndexOffset += ++materialMaxIndex;
  15121. }
  15122. }
  15123. return mesh;
  15124. };
  15125. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15126. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15127. mesh.material = material;
  15128. mesh.position.copyFrom(this.position);
  15129. mesh.rotation.copyFrom(this.rotation);
  15130. mesh.scaling.copyFrom(this.scaling);
  15131. mesh.computeWorldMatrix(true);
  15132. return mesh;
  15133. };
  15134. return CSG;
  15135. })();
  15136. BABYLON.CSG = CSG;
  15137. })(BABYLON || (BABYLON = {}));
  15138. var __extends = this.__extends || function (d, b) {
  15139. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15140. function __() { this.constructor = d; }
  15141. __.prototype = b.prototype;
  15142. d.prototype = new __();
  15143. };
  15144. var BABYLON;
  15145. (function (BABYLON) {
  15146. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15147. __extends(OculusDistortionCorrectionPostProcess, _super);
  15148. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15149. var _this = this;
  15150. _super.call(this, name, "oculusDistortionCorrection", [
  15151. 'LensCenter',
  15152. 'Scale',
  15153. 'ScaleIn',
  15154. 'HmdWarpParam'
  15155. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15156. this._isRightEye = isRightEye;
  15157. this._distortionFactors = cameraSettings.DistortionK;
  15158. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15159. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15160. this.onSizeChanged = function () {
  15161. _this.aspectRatio = _this.width * .5 / _this.height;
  15162. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15163. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15164. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15165. };
  15166. this.onApply = function (effect) {
  15167. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15168. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15169. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15170. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15171. };
  15172. }
  15173. return OculusDistortionCorrectionPostProcess;
  15174. })(BABYLON.PostProcess);
  15175. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15176. })(BABYLON || (BABYLON = {}));
  15177. var BABYLON;
  15178. (function (BABYLON) {
  15179. (function (JoystickAxis) {
  15180. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15181. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15182. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15183. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15184. var JoystickAxis = BABYLON.JoystickAxis;
  15185. var VirtualJoystick = (function () {
  15186. function VirtualJoystick(leftJoystick) {
  15187. var _this = this;
  15188. if (leftJoystick) {
  15189. this._leftJoystick = true;
  15190. } else {
  15191. this._leftJoystick = false;
  15192. }
  15193. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15194. VirtualJoystick._globalJoystickIndex++;
  15195. this._axisTargetedByLeftAndRight = 0 /* X */;
  15196. this._axisTargetedByUpAndDown = 1 /* Y */;
  15197. this.reverseLeftRight = false;
  15198. this.reverseUpDown = false;
  15199. this._touches = new BABYLON.VirtualJoystick.Collection();
  15200. this.deltaPosition = BABYLON.Vector3.Zero();
  15201. this._joystickSensibility = 25;
  15202. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15203. this._rotationSpeed = 25;
  15204. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15205. this._rotateOnAxisRelativeToMesh = false;
  15206. if (!VirtualJoystick.vjCanvas) {
  15207. window.addEventListener("resize", function () {
  15208. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15209. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15210. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15211. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15212. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15213. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15214. }, false);
  15215. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15216. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15217. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15218. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15219. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15220. VirtualJoystick.vjCanvas.style.width = "100%";
  15221. VirtualJoystick.vjCanvas.style.height = "100%";
  15222. VirtualJoystick.vjCanvas.style.position = "absolute";
  15223. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15224. VirtualJoystick.vjCanvas.style.top = "0px";
  15225. VirtualJoystick.vjCanvas.style.left = "0px";
  15226. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15227. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15228. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15229. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15230. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15231. document.body.appendChild(VirtualJoystick.vjCanvas);
  15232. }
  15233. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15234. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15235. this.pressed = false;
  15236. this._joystickColor = "cyan";
  15237. this._joystickPointerID = -1;
  15238. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15239. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15240. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15241. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15242. _this._onPointerDown(evt);
  15243. }, false);
  15244. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15245. _this._onPointerMove(evt);
  15246. }, false);
  15247. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15248. _this._onPointerUp(evt);
  15249. }, false);
  15250. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15251. _this._onPointerUp(evt);
  15252. }, false);
  15253. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15254. evt.preventDefault();
  15255. }, false);
  15256. requestAnimationFrame(function () {
  15257. _this._drawVirtualJoystick();
  15258. });
  15259. }
  15260. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15261. this._joystickSensibility = newJoystickSensibility;
  15262. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15263. };
  15264. VirtualJoystick.prototype._onPointerDown = function (e) {
  15265. var positionOnScreenCondition;
  15266. e.preventDefault();
  15267. if (this._leftJoystick === true) {
  15268. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15269. } else {
  15270. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15271. }
  15272. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15273. this._joystickPointerID = e.pointerId;
  15274. this._joystickPointerStartPos.x = e.clientX;
  15275. this._joystickPointerStartPos.y = e.clientY;
  15276. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15277. this._deltaJoystickVector.x = 0;
  15278. this._deltaJoystickVector.y = 0;
  15279. this.pressed = true;
  15280. this._touches.add(e.pointerId.toString(), e);
  15281. } else {
  15282. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15283. this._action();
  15284. this._touches.add(e.pointerId.toString(), e);
  15285. }
  15286. }
  15287. };
  15288. VirtualJoystick.prototype._onPointerMove = function (e) {
  15289. if (this._joystickPointerID == e.pointerId) {
  15290. this._joystickPointerPos.x = e.clientX;
  15291. this._joystickPointerPos.y = e.clientY;
  15292. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15293. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15294. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15295. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15296. switch (this._axisTargetedByLeftAndRight) {
  15297. case 0 /* X */:
  15298. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15299. break;
  15300. case 1 /* Y */:
  15301. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15302. break;
  15303. case 2 /* Z */:
  15304. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15305. break;
  15306. }
  15307. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15308. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15309. switch (this._axisTargetedByUpAndDown) {
  15310. case 0 /* X */:
  15311. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15312. break;
  15313. case 1 /* Y */:
  15314. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15315. break;
  15316. case 2 /* Z */:
  15317. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15318. break;
  15319. }
  15320. } else {
  15321. if (this._touches.item(e.pointerId.toString())) {
  15322. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15323. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15324. }
  15325. }
  15326. };
  15327. VirtualJoystick.prototype._onPointerUp = function (e) {
  15328. this._clearCanvas();
  15329. if (this._joystickPointerID == e.pointerId) {
  15330. this._joystickPointerID = -1;
  15331. this.pressed = false;
  15332. }
  15333. this._deltaJoystickVector.x = 0;
  15334. this._deltaJoystickVector.y = 0;
  15335. this._touches.remove(e.pointerId.toString());
  15336. };
  15337. /**
  15338. * Change the color of the virtual joystick
  15339. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15340. */
  15341. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15342. this._joystickColor = newColor;
  15343. };
  15344. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15345. this._action = action;
  15346. };
  15347. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15348. switch (axis) {
  15349. case 0 /* X */:
  15350. case 1 /* Y */:
  15351. case 2 /* Z */:
  15352. this._axisTargetedByLeftAndRight = axis;
  15353. break;
  15354. default:
  15355. this._axisTargetedByLeftAndRight = 0 /* X */;
  15356. break;
  15357. }
  15358. };
  15359. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15360. switch (axis) {
  15361. case 0 /* X */:
  15362. case 1 /* Y */:
  15363. case 2 /* Z */:
  15364. this._axisTargetedByUpAndDown = axis;
  15365. break;
  15366. default:
  15367. this._axisTargetedByUpAndDown = 1 /* Y */;
  15368. break;
  15369. }
  15370. };
  15371. VirtualJoystick.prototype._clearCanvas = function () {
  15372. if (this._leftJoystick) {
  15373. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15374. } else {
  15375. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15376. }
  15377. };
  15378. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15379. var _this = this;
  15380. if (this.pressed) {
  15381. this._clearCanvas();
  15382. this._touches.forEach(function (touch) {
  15383. if (touch.pointerId === _this._joystickPointerID) {
  15384. VirtualJoystick.vjCanvasContext.beginPath();
  15385. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15386. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15387. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15388. VirtualJoystick.vjCanvasContext.stroke();
  15389. VirtualJoystick.vjCanvasContext.beginPath();
  15390. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15391. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15392. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15393. VirtualJoystick.vjCanvasContext.stroke();
  15394. VirtualJoystick.vjCanvasContext.beginPath();
  15395. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15396. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15397. VirtualJoystick.vjCanvasContext.stroke();
  15398. } else {
  15399. VirtualJoystick.vjCanvasContext.beginPath();
  15400. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15401. VirtualJoystick.vjCanvasContext.beginPath();
  15402. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15403. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15404. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15405. VirtualJoystick.vjCanvasContext.stroke();
  15406. }
  15407. ;
  15408. });
  15409. }
  15410. requestAnimationFrame(function () {
  15411. _this._drawVirtualJoystick();
  15412. });
  15413. };
  15414. VirtualJoystick.prototype.releaseCanvas = function () {
  15415. if (VirtualJoystick.vjCanvas) {
  15416. document.body.removeChild(VirtualJoystick.vjCanvas);
  15417. VirtualJoystick.vjCanvas = null;
  15418. }
  15419. };
  15420. VirtualJoystick._globalJoystickIndex = 0;
  15421. return VirtualJoystick;
  15422. })();
  15423. BABYLON.VirtualJoystick = VirtualJoystick;
  15424. })(BABYLON || (BABYLON = {}));
  15425. var BABYLON;
  15426. (function (BABYLON) {
  15427. (function (VirtualJoystick) {
  15428. var Collection = (function () {
  15429. function Collection() {
  15430. this._count = 0;
  15431. this._collection = new Array();
  15432. }
  15433. Collection.prototype.Count = function () {
  15434. return this._count;
  15435. };
  15436. Collection.prototype.add = function (key, item) {
  15437. if (this._collection[key] != undefined) {
  15438. return undefined;
  15439. }
  15440. this._collection[key] = item;
  15441. return ++this._count;
  15442. };
  15443. Collection.prototype.remove = function (key) {
  15444. if (this._collection[key] == undefined) {
  15445. return undefined;
  15446. }
  15447. delete this._collection[key];
  15448. return --this._count;
  15449. };
  15450. Collection.prototype.item = function (key) {
  15451. return this._collection[key];
  15452. };
  15453. Collection.prototype.forEach = function (block) {
  15454. var key;
  15455. for (key in this._collection) {
  15456. if (this._collection.hasOwnProperty(key)) {
  15457. block(this._collection[key]);
  15458. }
  15459. }
  15460. };
  15461. return Collection;
  15462. })();
  15463. VirtualJoystick.Collection = Collection;
  15464. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15465. var VirtualJoystick = BABYLON.VirtualJoystick;
  15466. })(BABYLON || (BABYLON = {}));
  15467. var __extends = this.__extends || function (d, b) {
  15468. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15469. function __() { this.constructor = d; }
  15470. __.prototype = b.prototype;
  15471. d.prototype = new __();
  15472. };
  15473. var BABYLON;
  15474. (function (BABYLON) {
  15475. var OculusRiftDevKit2013_Metric = {
  15476. HResolution: 1280,
  15477. VResolution: 800,
  15478. HScreenSize: 0.149759993,
  15479. VScreenSize: 0.0935999975,
  15480. VScreenCenter: 0.0467999987,
  15481. EyeToScreenDistance: 0.0410000011,
  15482. LensSeparationDistance: 0.0635000020,
  15483. InterpupillaryDistance: 0.0640000030,
  15484. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15485. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15486. PostProcessScaleFactor: 1.714605507808412,
  15487. LensCenterOffset: 0.151976421
  15488. };
  15489. var _OculusInnerCamera = (function (_super) {
  15490. __extends(_OculusInnerCamera, _super);
  15491. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15492. _super.call(this, name, position, scene);
  15493. this._workMatrix = new BABYLON.Matrix();
  15494. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15495. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15496. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15497. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15498. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15499. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15500. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15501. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15502. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15503. }
  15504. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15505. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15506. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15507. return this._projectionMatrix;
  15508. };
  15509. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15510. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15511. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15512. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15513. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15514. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15515. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15516. return this._viewMatrix;
  15517. };
  15518. return _OculusInnerCamera;
  15519. })(BABYLON.FreeCamera);
  15520. var OculusCamera = (function (_super) {
  15521. __extends(OculusCamera, _super);
  15522. function OculusCamera(name, position, scene) {
  15523. _super.call(this, name, position, scene);
  15524. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15525. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15526. this.subCameras.push(this._leftCamera);
  15527. this.subCameras.push(this._rightCamera);
  15528. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15529. }
  15530. OculusCamera.prototype._update = function () {
  15531. this._leftCamera.position.copyFrom(this.position);
  15532. this._rightCamera.position.copyFrom(this.position);
  15533. this._updateCamera(this._leftCamera);
  15534. this._updateCamera(this._rightCamera);
  15535. _super.prototype._update.call(this);
  15536. };
  15537. OculusCamera.prototype._updateCamera = function (camera) {
  15538. camera.minZ = this.minZ;
  15539. camera.maxZ = this.maxZ;
  15540. camera.rotation.x = this.rotation.x;
  15541. camera.rotation.y = this.rotation.y;
  15542. camera.rotation.z = this.rotation.z;
  15543. };
  15544. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15545. var yaw = evt.alpha / 180 * Math.PI;
  15546. var pitch = evt.beta / 180 * Math.PI;
  15547. var roll = evt.gamma / 180 * Math.PI;
  15548. if (!this._offsetOrientation) {
  15549. this._offsetOrientation = {
  15550. yaw: yaw,
  15551. pitch: pitch,
  15552. roll: roll
  15553. };
  15554. return;
  15555. } else {
  15556. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15557. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15558. this.rotation.z += this._offsetOrientation.roll - roll;
  15559. this._offsetOrientation.yaw = yaw;
  15560. this._offsetOrientation.pitch = pitch;
  15561. this._offsetOrientation.roll = roll;
  15562. }
  15563. };
  15564. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15565. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15566. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15567. };
  15568. OculusCamera.prototype.detachControl = function (element) {
  15569. _super.prototype.detachControl.call(this, element);
  15570. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15571. };
  15572. return OculusCamera;
  15573. })(BABYLON.FreeCamera);
  15574. BABYLON.OculusCamera = OculusCamera;
  15575. })(BABYLON || (BABYLON = {}));
  15576. var __extends = this.__extends || function (d, b) {
  15577. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15578. function __() { this.constructor = d; }
  15579. __.prototype = b.prototype;
  15580. d.prototype = new __();
  15581. };
  15582. var BABYLON;
  15583. (function (BABYLON) {
  15584. var VirtualJoysticksCamera = (function (_super) {
  15585. __extends(VirtualJoysticksCamera, _super);
  15586. function VirtualJoysticksCamera(name, position, scene) {
  15587. _super.call(this, name, position, scene);
  15588. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15589. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15590. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15591. this._leftjoystick.setJoystickSensibility(0.15);
  15592. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15593. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15594. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15595. this._rightjoystick.reverseUpDown = true;
  15596. this._rightjoystick.setJoystickSensibility(0.05);
  15597. this._rightjoystick.setJoystickColor("yellow");
  15598. }
  15599. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15600. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15601. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15602. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15603. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15604. if (!this._leftjoystick.pressed) {
  15605. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15606. }
  15607. if (!this._rightjoystick.pressed) {
  15608. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15609. }
  15610. };
  15611. VirtualJoysticksCamera.prototype.dispose = function () {
  15612. this._leftjoystick.releaseCanvas();
  15613. _super.prototype.dispose.call(this);
  15614. };
  15615. return VirtualJoysticksCamera;
  15616. })(BABYLON.FreeCamera);
  15617. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15618. })(BABYLON || (BABYLON = {}));
  15619. var __extends = this.__extends || function (d, b) {
  15620. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15621. function __() { this.constructor = d; }
  15622. __.prototype = b.prototype;
  15623. d.prototype = new __();
  15624. };
  15625. var BABYLON;
  15626. (function (BABYLON) {
  15627. var ShaderMaterial = (function (_super) {
  15628. __extends(ShaderMaterial, _super);
  15629. function ShaderMaterial(name, scene, shaderPath, options) {
  15630. _super.call(this, name, scene);
  15631. this._textures = new Array();
  15632. this._floats = new Array();
  15633. this._floatsArrays = {};
  15634. this._colors3 = new Array();
  15635. this._colors4 = new Array();
  15636. this._vectors2 = new Array();
  15637. this._vectors3 = new Array();
  15638. this._matrices = new Array();
  15639. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15640. this._shaderPath = shaderPath;
  15641. options.needAlphaBlending = options.needAlphaBlending || false;
  15642. options.needAlphaTesting = options.needAlphaTesting || false;
  15643. options.attributes = options.attributes || ["position", "normal", "uv"];
  15644. options.uniforms = options.uniforms || ["worldViewProjection"];
  15645. options.samplers = options.samplers || [];
  15646. this._options = options;
  15647. }
  15648. ShaderMaterial.prototype.needAlphaBlending = function () {
  15649. return this._options.needAlphaBlending;
  15650. };
  15651. ShaderMaterial.prototype.needAlphaTesting = function () {
  15652. return this._options.needAlphaTesting;
  15653. };
  15654. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15655. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15656. this._options.uniforms.push(uniformName);
  15657. }
  15658. };
  15659. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15660. if (this._options.samplers.indexOf(name) === -1) {
  15661. this._options.samplers.push(name);
  15662. }
  15663. this._textures[name] = texture;
  15664. return this;
  15665. };
  15666. ShaderMaterial.prototype.setFloat = function (name, value) {
  15667. this._checkUniform(name);
  15668. this._floats[name] = value;
  15669. return this;
  15670. };
  15671. ShaderMaterial.prototype.setFloats = function (name, value) {
  15672. this._checkUniform(name);
  15673. this._floatsArrays[name] = value;
  15674. return this;
  15675. };
  15676. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15677. this._checkUniform(name);
  15678. this._colors3[name] = value;
  15679. return this;
  15680. };
  15681. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15682. this._checkUniform(name);
  15683. this._colors4[name] = value;
  15684. return this;
  15685. };
  15686. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15687. this._checkUniform(name);
  15688. this._vectors2[name] = value;
  15689. return this;
  15690. };
  15691. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15692. this._checkUniform(name);
  15693. this._vectors3[name] = value;
  15694. return this;
  15695. };
  15696. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15697. this._checkUniform(name);
  15698. this._matrices[name] = value;
  15699. return this;
  15700. };
  15701. ShaderMaterial.prototype.isReady = function () {
  15702. var engine = this.getScene().getEngine();
  15703. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15704. if (!this._effect.isReady()) {
  15705. return false;
  15706. }
  15707. return true;
  15708. };
  15709. ShaderMaterial.prototype.bind = function (world) {
  15710. if (this._options.uniforms.indexOf("world") !== -1) {
  15711. this._effect.setMatrix("world", world);
  15712. }
  15713. if (this._options.uniforms.indexOf("view") !== -1) {
  15714. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15715. }
  15716. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15717. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15718. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15719. }
  15720. if (this._options.uniforms.indexOf("projection") !== -1) {
  15721. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15722. }
  15723. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15724. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15725. }
  15726. for (var name in this._textures) {
  15727. this._effect.setTexture(name, this._textures[name]);
  15728. }
  15729. for (name in this._floats) {
  15730. this._effect.setFloat(name, this._floats[name]);
  15731. }
  15732. for (name in this._floatsArrays) {
  15733. this._effect.setArray(name, this._floatsArrays[name]);
  15734. }
  15735. for (name in this._colors3) {
  15736. this._effect.setColor3(name, this._colors3[name]);
  15737. }
  15738. for (name in this._colors4) {
  15739. var color = this._colors4[name];
  15740. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15741. }
  15742. for (name in this._vectors2) {
  15743. this._effect.setVector2(name, this._vectors2[name]);
  15744. }
  15745. for (name in this._vectors3) {
  15746. this._effect.setVector3(name, this._vectors3[name]);
  15747. }
  15748. for (name in this._matrices) {
  15749. this._effect.setMatrix(name, this._matrices[name]);
  15750. }
  15751. };
  15752. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15753. for (var name in this._textures) {
  15754. this._textures[name].dispose();
  15755. }
  15756. this._textures = [];
  15757. _super.prototype.dispose.call(this, forceDisposeEffect);
  15758. };
  15759. return ShaderMaterial;
  15760. })(BABYLON.Material);
  15761. BABYLON.ShaderMaterial = ShaderMaterial;
  15762. })(BABYLON || (BABYLON = {}));
  15763. var BABYLON;
  15764. (function (BABYLON) {
  15765. var VertexData = (function () {
  15766. function VertexData() {
  15767. }
  15768. VertexData.prototype.set = function (data, kind) {
  15769. switch (kind) {
  15770. case BABYLON.VertexBuffer.PositionKind:
  15771. this.positions = data;
  15772. break;
  15773. case BABYLON.VertexBuffer.NormalKind:
  15774. this.normals = data;
  15775. break;
  15776. case BABYLON.VertexBuffer.UVKind:
  15777. this.uvs = data;
  15778. break;
  15779. case BABYLON.VertexBuffer.UV2Kind:
  15780. this.uv2s = data;
  15781. break;
  15782. case BABYLON.VertexBuffer.ColorKind:
  15783. this.colors = data;
  15784. break;
  15785. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15786. this.matricesIndices = data;
  15787. break;
  15788. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15789. this.matricesWeights = data;
  15790. break;
  15791. }
  15792. };
  15793. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15794. this._applyTo(mesh, updatable);
  15795. };
  15796. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15797. this._applyTo(geometry, updatable);
  15798. };
  15799. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15800. this._update(mesh);
  15801. };
  15802. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15803. this._update(geometry);
  15804. };
  15805. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15806. if (this.positions) {
  15807. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15808. }
  15809. if (this.normals) {
  15810. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15811. }
  15812. if (this.uvs) {
  15813. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15814. }
  15815. if (this.uv2s) {
  15816. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  15817. }
  15818. if (this.colors) {
  15819. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  15820. }
  15821. if (this.matricesIndices) {
  15822. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  15823. }
  15824. if (this.matricesWeights) {
  15825. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  15826. }
  15827. if (this.indices) {
  15828. meshOrGeometry.setIndices(this.indices);
  15829. }
  15830. };
  15831. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  15832. if (this.positions) {
  15833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  15834. }
  15835. if (this.normals) {
  15836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  15837. }
  15838. if (this.uvs) {
  15839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  15840. }
  15841. if (this.uv2s) {
  15842. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  15843. }
  15844. if (this.colors) {
  15845. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  15846. }
  15847. if (this.matricesIndices) {
  15848. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  15849. }
  15850. if (this.matricesWeights) {
  15851. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  15852. }
  15853. if (this.indices) {
  15854. meshOrGeometry.setIndices(this.indices);
  15855. }
  15856. };
  15857. VertexData.prototype.transform = function (matrix) {
  15858. var transformed = BABYLON.Vector3.Zero();
  15859. if (this.positions) {
  15860. var position = BABYLON.Vector3.Zero();
  15861. for (var index = 0; index < this.positions.length; index += 3) {
  15862. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  15863. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  15864. this.positions[index] = transformed.x;
  15865. this.positions[index + 1] = transformed.y;
  15866. this.positions[index + 2] = transformed.z;
  15867. }
  15868. }
  15869. if (this.normals) {
  15870. var normal = BABYLON.Vector3.Zero();
  15871. for (index = 0; index < this.normals.length; index += 3) {
  15872. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  15873. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  15874. this.normals[index] = transformed.x;
  15875. this.normals[index + 1] = transformed.y;
  15876. this.normals[index + 2] = transformed.z;
  15877. }
  15878. }
  15879. };
  15880. VertexData.prototype.merge = function (other) {
  15881. if (other.indices) {
  15882. if (!this.indices) {
  15883. this.indices = [];
  15884. }
  15885. var offset = this.positions ? this.positions.length / 3 : 0;
  15886. for (var index = 0; index < other.indices.length; index++) {
  15887. this.indices.push(other.indices[index] + offset);
  15888. }
  15889. }
  15890. if (other.positions) {
  15891. if (!this.positions) {
  15892. this.positions = [];
  15893. }
  15894. for (index = 0; index < other.positions.length; index++) {
  15895. this.positions.push(other.positions[index]);
  15896. }
  15897. }
  15898. if (other.normals) {
  15899. if (!this.normals) {
  15900. this.normals = [];
  15901. }
  15902. for (index = 0; index < other.normals.length; index++) {
  15903. this.normals.push(other.normals[index]);
  15904. }
  15905. }
  15906. if (other.uvs) {
  15907. if (!this.uvs) {
  15908. this.uvs = [];
  15909. }
  15910. for (index = 0; index < other.uvs.length; index++) {
  15911. this.uvs.push(other.uvs[index]);
  15912. }
  15913. }
  15914. if (other.uv2s) {
  15915. if (!this.uv2s) {
  15916. this.uv2s = [];
  15917. }
  15918. for (index = 0; index < other.uv2s.length; index++) {
  15919. this.uv2s.push(other.uv2s[index]);
  15920. }
  15921. }
  15922. if (other.matricesIndices) {
  15923. if (!this.matricesIndices) {
  15924. this.matricesIndices = [];
  15925. }
  15926. for (index = 0; index < other.matricesIndices.length; index++) {
  15927. this.matricesIndices.push(other.matricesIndices[index]);
  15928. }
  15929. }
  15930. if (other.matricesWeights) {
  15931. if (!this.matricesWeights) {
  15932. this.matricesWeights = [];
  15933. }
  15934. for (index = 0; index < other.matricesWeights.length; index++) {
  15935. this.matricesWeights.push(other.matricesWeights[index]);
  15936. }
  15937. }
  15938. if (other.colors) {
  15939. if (!this.colors) {
  15940. this.colors = [];
  15941. }
  15942. for (index = 0; index < other.colors.length; index++) {
  15943. this.colors.push(other.colors[index]);
  15944. }
  15945. }
  15946. };
  15947. VertexData.ExtractFromMesh = function (mesh) {
  15948. return VertexData._ExtractFrom(mesh);
  15949. };
  15950. VertexData.ExtractFromGeometry = function (geometry) {
  15951. return VertexData._ExtractFrom(geometry);
  15952. };
  15953. VertexData._ExtractFrom = function (meshOrGeometry) {
  15954. var result = new BABYLON.VertexData();
  15955. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15956. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15957. }
  15958. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15959. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15960. }
  15961. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15962. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15963. }
  15964. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15965. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15966. }
  15967. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15968. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15969. }
  15970. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15971. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15972. }
  15973. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15974. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15975. }
  15976. result.indices = meshOrGeometry.getIndices();
  15977. return result;
  15978. };
  15979. VertexData.CreateBox = function (size) {
  15980. var normalsSource = [
  15981. new BABYLON.Vector3(0, 0, 1),
  15982. new BABYLON.Vector3(0, 0, -1),
  15983. new BABYLON.Vector3(1, 0, 0),
  15984. new BABYLON.Vector3(-1, 0, 0),
  15985. new BABYLON.Vector3(0, 1, 0),
  15986. new BABYLON.Vector3(0, -1, 0)
  15987. ];
  15988. var indices = [];
  15989. var positions = [];
  15990. var normals = [];
  15991. var uvs = [];
  15992. size = size || 1;
  15993. for (var index = 0; index < normalsSource.length; index++) {
  15994. var normal = normalsSource[index];
  15995. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  15996. var side2 = BABYLON.Vector3.Cross(normal, side1);
  15997. var verticesLength = positions.length / 3;
  15998. indices.push(verticesLength);
  15999. indices.push(verticesLength + 1);
  16000. indices.push(verticesLength + 2);
  16001. indices.push(verticesLength);
  16002. indices.push(verticesLength + 2);
  16003. indices.push(verticesLength + 3);
  16004. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16005. positions.push(vertex.x, vertex.y, vertex.z);
  16006. normals.push(normal.x, normal.y, normal.z);
  16007. uvs.push(1.0, 1.0);
  16008. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16009. positions.push(vertex.x, vertex.y, vertex.z);
  16010. normals.push(normal.x, normal.y, normal.z);
  16011. uvs.push(0.0, 1.0);
  16012. vertex = normal.add(side1).add(side2).scale(size / 2);
  16013. positions.push(vertex.x, vertex.y, vertex.z);
  16014. normals.push(normal.x, normal.y, normal.z);
  16015. uvs.push(0.0, 0.0);
  16016. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16017. positions.push(vertex.x, vertex.y, vertex.z);
  16018. normals.push(normal.x, normal.y, normal.z);
  16019. uvs.push(1.0, 0.0);
  16020. }
  16021. var vertexData = new BABYLON.VertexData();
  16022. vertexData.indices = indices;
  16023. vertexData.positions = positions;
  16024. vertexData.normals = normals;
  16025. vertexData.uvs = uvs;
  16026. return vertexData;
  16027. };
  16028. VertexData.CreateSphere = function (segments, diameter) {
  16029. segments = segments || 32;
  16030. diameter = diameter || 1;
  16031. var radius = diameter / 2;
  16032. var totalZRotationSteps = 2 + segments;
  16033. var totalYRotationSteps = 2 * totalZRotationSteps;
  16034. var indices = [];
  16035. var positions = [];
  16036. var normals = [];
  16037. var uvs = [];
  16038. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16039. var normalizedZ = zRotationStep / totalZRotationSteps;
  16040. var angleZ = (normalizedZ * Math.PI);
  16041. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16042. var normalizedY = yRotationStep / totalYRotationSteps;
  16043. var angleY = normalizedY * Math.PI * 2;
  16044. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16045. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16046. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16047. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16048. var vertex = complete.scale(radius);
  16049. var normal = BABYLON.Vector3.Normalize(vertex);
  16050. positions.push(vertex.x, vertex.y, vertex.z);
  16051. normals.push(normal.x, normal.y, normal.z);
  16052. uvs.push(normalizedZ, normalizedY);
  16053. }
  16054. if (zRotationStep > 0) {
  16055. var verticesCount = positions.length / 3;
  16056. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16057. indices.push((firstIndex));
  16058. indices.push((firstIndex + 1));
  16059. indices.push(firstIndex + totalYRotationSteps + 1);
  16060. indices.push((firstIndex + totalYRotationSteps + 1));
  16061. indices.push((firstIndex + 1));
  16062. indices.push((firstIndex + totalYRotationSteps + 2));
  16063. }
  16064. }
  16065. }
  16066. var vertexData = new BABYLON.VertexData();
  16067. vertexData.indices = indices;
  16068. vertexData.positions = positions;
  16069. vertexData.normals = normals;
  16070. vertexData.uvs = uvs;
  16071. return vertexData;
  16072. };
  16073. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16074. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16075. var radiusTop = diameterTop / 2;
  16076. var radiusBottom = diameterBottom / 2;
  16077. var indices = [];
  16078. var positions = [];
  16079. var normals = [];
  16080. var uvs = [];
  16081. height = height || 1;
  16082. diameterTop = diameterTop || 0.5;
  16083. diameterBottom = diameterBottom || 1;
  16084. tessellation = tessellation || 16;
  16085. subdivisions = subdivisions || 1;
  16086. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16087. var getCircleVector = function (i) {
  16088. var angle = (i * 2.0 * Math.PI / tessellation);
  16089. var dx = Math.cos(angle);
  16090. var dz = Math.sin(angle);
  16091. return new BABYLON.Vector3(dx, 0, dz);
  16092. };
  16093. var createCylinderCap = function (isTop) {
  16094. var radius = isTop ? radiusTop : radiusBottom;
  16095. if (radius == 0) {
  16096. return;
  16097. }
  16098. var vbase = positions.length / 3;
  16099. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16100. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16101. if (!isTop) {
  16102. offset.scaleInPlace(-1);
  16103. textureScale.x = -textureScale.x;
  16104. }
  16105. for (i = 0; i < tessellation; i++) {
  16106. var circleVector = getCircleVector(i);
  16107. var position = circleVector.scale(radius).add(offset);
  16108. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16109. positions.push(position.x, position.y, position.z);
  16110. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16111. }
  16112. for (var i = 0; i < tessellation - 2; i++) {
  16113. if (!isTop) {
  16114. indices.push(vbase);
  16115. indices.push(vbase + (i + 2) % tessellation);
  16116. indices.push(vbase + (i + 1) % tessellation);
  16117. } else {
  16118. indices.push(vbase);
  16119. indices.push(vbase + (i + 1) % tessellation);
  16120. indices.push(vbase + (i + 2) % tessellation);
  16121. }
  16122. }
  16123. };
  16124. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16125. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16126. var stride = tessellation + 1;
  16127. for (var i = 0; i <= tessellation; i++) {
  16128. var circleVector = getCircleVector(i);
  16129. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16130. var position, radius = radiusBottom;
  16131. for (var s = 0; s <= subdivisions; s++) {
  16132. position = circleVector.scale(radius);
  16133. position.addInPlace(base.add(offset.scale(s)));
  16134. textureCoordinate.y += 1 / subdivisions;
  16135. radius += (radiusTop - radiusBottom) / subdivisions;
  16136. positions.push(position.x, position.y, position.z);
  16137. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16138. }
  16139. }
  16140. subdivisions += 1;
  16141. for (var s = 0; s < subdivisions - 1; s++) {
  16142. for (var i = 0; i <= tessellation; i++) {
  16143. indices.push(i * subdivisions + s);
  16144. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16145. indices.push(i * subdivisions + (s + 1));
  16146. indices.push(i * subdivisions + (s + 1));
  16147. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16148. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16149. }
  16150. }
  16151. createCylinderCap(true);
  16152. createCylinderCap(false);
  16153. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16154. var vertexData = new BABYLON.VertexData();
  16155. vertexData.indices = indices;
  16156. vertexData.positions = positions;
  16157. vertexData.normals = normals;
  16158. vertexData.uvs = uvs;
  16159. return vertexData;
  16160. };
  16161. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16162. var indices = [];
  16163. var positions = [];
  16164. var normals = [];
  16165. var uvs = [];
  16166. diameter = diameter || 1;
  16167. thickness = thickness || 0.5;
  16168. tessellation = tessellation || 16;
  16169. var stride = tessellation + 1;
  16170. for (var i = 0; i <= tessellation; i++) {
  16171. var u = i / tessellation;
  16172. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16173. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16174. for (var j = 0; j <= tessellation; j++) {
  16175. var v = 1 - j / tessellation;
  16176. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16177. var dx = Math.cos(innerAngle);
  16178. var dy = Math.sin(innerAngle);
  16179. var normal = new BABYLON.Vector3(dx, dy, 0);
  16180. var position = normal.scale(thickness / 2);
  16181. var textureCoordinate = new BABYLON.Vector2(u, v);
  16182. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16183. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16184. positions.push(position.x, position.y, position.z);
  16185. normals.push(normal.x, normal.y, normal.z);
  16186. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16187. var nextI = (i + 1) % stride;
  16188. var nextJ = (j + 1) % stride;
  16189. indices.push(i * stride + j);
  16190. indices.push(i * stride + nextJ);
  16191. indices.push(nextI * stride + j);
  16192. indices.push(i * stride + nextJ);
  16193. indices.push(nextI * stride + nextJ);
  16194. indices.push(nextI * stride + j);
  16195. }
  16196. }
  16197. var vertexData = new BABYLON.VertexData();
  16198. vertexData.indices = indices;
  16199. vertexData.positions = positions;
  16200. vertexData.normals = normals;
  16201. vertexData.uvs = uvs;
  16202. return vertexData;
  16203. };
  16204. VertexData.CreateLines = function (points) {
  16205. var indices = [];
  16206. var positions = [];
  16207. for (var index = 0; index < points.length; index++) {
  16208. positions.push(points[index].x, points[index].y, points[index].z);
  16209. if (index > 0) {
  16210. indices.push(index - 1);
  16211. indices.push(index);
  16212. }
  16213. }
  16214. var vertexData = new BABYLON.VertexData();
  16215. vertexData.indices = indices;
  16216. vertexData.positions = positions;
  16217. return vertexData;
  16218. };
  16219. VertexData.CreateGround = function (width, height, subdivisions) {
  16220. var indices = [];
  16221. var positions = [];
  16222. var normals = [];
  16223. var uvs = [];
  16224. var row, col;
  16225. width = width || 1;
  16226. height = height || 1;
  16227. subdivisions = subdivisions || 1;
  16228. for (row = 0; row <= subdivisions; row++) {
  16229. for (col = 0; col <= subdivisions; col++) {
  16230. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16231. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16232. positions.push(position.x, position.y, position.z);
  16233. normals.push(normal.x, normal.y, normal.z);
  16234. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16235. }
  16236. }
  16237. for (row = 0; row < subdivisions; row++) {
  16238. for (col = 0; col < subdivisions; col++) {
  16239. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16240. indices.push(col + 1 + row * (subdivisions + 1));
  16241. indices.push(col + row * (subdivisions + 1));
  16242. indices.push(col + (row + 1) * (subdivisions + 1));
  16243. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16244. indices.push(col + row * (subdivisions + 1));
  16245. }
  16246. }
  16247. var vertexData = new BABYLON.VertexData();
  16248. vertexData.indices = indices;
  16249. vertexData.positions = positions;
  16250. vertexData.normals = normals;
  16251. vertexData.uvs = uvs;
  16252. return vertexData;
  16253. };
  16254. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16255. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16256. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16257. var indices = [];
  16258. var positions = [];
  16259. var normals = [];
  16260. var uvs = [];
  16261. var row, col, tileRow, tileCol;
  16262. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16263. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16264. precision.w = (precision.w < 1) ? 1 : precision.w;
  16265. precision.h = (precision.h < 1) ? 1 : precision.h;
  16266. var tileSize = {
  16267. 'w': (xmax - xmin) / subdivisions.w,
  16268. 'h': (zmax - zmin) / subdivisions.h
  16269. };
  16270. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16271. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16272. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16273. }
  16274. }
  16275. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16276. var base = positions.length / 3;
  16277. var rowLength = precision.w + 1;
  16278. for (row = 0; row < precision.h; row++) {
  16279. for (col = 0; col < precision.w; col++) {
  16280. var square = [
  16281. base + col + row * rowLength,
  16282. base + (col + 1) + row * rowLength,
  16283. base + (col + 1) + (row + 1) * rowLength,
  16284. base + col + (row + 1) * rowLength
  16285. ];
  16286. indices.push(square[1]);
  16287. indices.push(square[2]);
  16288. indices.push(square[3]);
  16289. indices.push(square[0]);
  16290. indices.push(square[1]);
  16291. indices.push(square[3]);
  16292. }
  16293. }
  16294. var position = BABYLON.Vector3.Zero();
  16295. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16296. for (row = 0; row <= precision.h; row++) {
  16297. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16298. for (col = 0; col <= precision.w; col++) {
  16299. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16300. position.y = 0;
  16301. positions.push(position.x, position.y, position.z);
  16302. normals.push(normal.x, normal.y, normal.z);
  16303. uvs.push(col / precision.w, row / precision.h);
  16304. }
  16305. }
  16306. }
  16307. var vertexData = new BABYLON.VertexData();
  16308. vertexData.indices = indices;
  16309. vertexData.positions = positions;
  16310. vertexData.normals = normals;
  16311. vertexData.uvs = uvs;
  16312. return vertexData;
  16313. };
  16314. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16315. var indices = [];
  16316. var positions = [];
  16317. var normals = [];
  16318. var uvs = [];
  16319. var row, col;
  16320. for (row = 0; row <= subdivisions; row++) {
  16321. for (col = 0; col <= subdivisions; col++) {
  16322. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16323. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16324. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16325. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16326. var r = buffer[pos] / 255.0;
  16327. var g = buffer[pos + 1] / 255.0;
  16328. var b = buffer[pos + 2] / 255.0;
  16329. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16330. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16331. positions.push(position.x, position.y, position.z);
  16332. normals.push(0, 0, 0);
  16333. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16334. }
  16335. }
  16336. for (row = 0; row < subdivisions; row++) {
  16337. for (col = 0; col < subdivisions; col++) {
  16338. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16339. indices.push(col + 1 + row * (subdivisions + 1));
  16340. indices.push(col + row * (subdivisions + 1));
  16341. indices.push(col + (row + 1) * (subdivisions + 1));
  16342. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16343. indices.push(col + row * (subdivisions + 1));
  16344. }
  16345. }
  16346. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  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.CreatePlane = function (size) {
  16355. var indices = [];
  16356. var positions = [];
  16357. var normals = [];
  16358. var uvs = [];
  16359. size = size || 1;
  16360. var halfSize = size / 2.0;
  16361. positions.push(-halfSize, -halfSize, 0);
  16362. normals.push(0, 0, -1.0);
  16363. uvs.push(0.0, 0.0);
  16364. positions.push(halfSize, -halfSize, 0);
  16365. normals.push(0, 0, -1.0);
  16366. uvs.push(1.0, 0.0);
  16367. positions.push(halfSize, halfSize, 0);
  16368. normals.push(0, 0, -1.0);
  16369. uvs.push(1.0, 1.0);
  16370. positions.push(-halfSize, halfSize, 0);
  16371. normals.push(0, 0, -1.0);
  16372. uvs.push(0.0, 1.0);
  16373. indices.push(0);
  16374. indices.push(1);
  16375. indices.push(2);
  16376. indices.push(0);
  16377. indices.push(2);
  16378. indices.push(3);
  16379. var vertexData = new BABYLON.VertexData();
  16380. vertexData.indices = indices;
  16381. vertexData.positions = positions;
  16382. vertexData.normals = normals;
  16383. vertexData.uvs = uvs;
  16384. return vertexData;
  16385. };
  16386. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16387. var indices = [];
  16388. var positions = [];
  16389. var normals = [];
  16390. var uvs = [];
  16391. radius = radius || 2;
  16392. tube = tube || 0.5;
  16393. radialSegments = radialSegments || 32;
  16394. tubularSegments = tubularSegments || 32;
  16395. p = p || 2;
  16396. q = q || 3;
  16397. var getPos = function (angle) {
  16398. var cu = Math.cos(angle);
  16399. var su = Math.sin(angle);
  16400. var quOverP = q / p * angle;
  16401. var cs = Math.cos(quOverP);
  16402. var tx = radius * (2 + cs) * 0.5 * cu;
  16403. var ty = radius * (2 + cs) * su * 0.5;
  16404. var tz = radius * Math.sin(quOverP) * 0.5;
  16405. return new BABYLON.Vector3(tx, ty, tz);
  16406. };
  16407. for (var i = 0; i <= radialSegments; i++) {
  16408. var modI = i % radialSegments;
  16409. var u = modI / radialSegments * 2 * p * Math.PI;
  16410. var p1 = getPos(u);
  16411. var p2 = getPos(u + 0.01);
  16412. var tang = p2.subtract(p1);
  16413. var n = p2.add(p1);
  16414. var bitan = BABYLON.Vector3.Cross(tang, n);
  16415. n = BABYLON.Vector3.Cross(bitan, tang);
  16416. bitan.normalize();
  16417. n.normalize();
  16418. for (var j = 0; j < tubularSegments; j++) {
  16419. var modJ = j % tubularSegments;
  16420. var v = modJ / tubularSegments * 2 * Math.PI;
  16421. var cx = -tube * Math.cos(v);
  16422. var cy = tube * Math.sin(v);
  16423. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16424. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16425. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16426. uvs.push(i / radialSegments);
  16427. uvs.push(j / tubularSegments);
  16428. }
  16429. }
  16430. for (i = 0; i < radialSegments; i++) {
  16431. for (j = 0; j < tubularSegments; j++) {
  16432. var jNext = (j + 1) % tubularSegments;
  16433. var a = i * tubularSegments + j;
  16434. var b = (i + 1) * tubularSegments + j;
  16435. var c = (i + 1) * tubularSegments + jNext;
  16436. var d = i * tubularSegments + jNext;
  16437. indices.push(d);
  16438. indices.push(b);
  16439. indices.push(a);
  16440. indices.push(d);
  16441. indices.push(c);
  16442. indices.push(b);
  16443. }
  16444. }
  16445. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16446. var vertexData = new BABYLON.VertexData();
  16447. vertexData.indices = indices;
  16448. vertexData.positions = positions;
  16449. vertexData.normals = normals;
  16450. vertexData.uvs = uvs;
  16451. return vertexData;
  16452. };
  16453. VertexData.ComputeNormals = function (positions, indices, normals) {
  16454. var positionVectors = [];
  16455. var facesOfVertices = [];
  16456. var index;
  16457. for (index = 0; index < positions.length; index += 3) {
  16458. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16459. positionVectors.push(vector3);
  16460. facesOfVertices.push([]);
  16461. }
  16462. var facesNormals = [];
  16463. for (index = 0; index < indices.length / 3; index++) {
  16464. var i1 = indices[index * 3];
  16465. var i2 = indices[index * 3 + 1];
  16466. var i3 = indices[index * 3 + 2];
  16467. var p1 = positionVectors[i1];
  16468. var p2 = positionVectors[i2];
  16469. var p3 = positionVectors[i3];
  16470. var p1p2 = p1.subtract(p2);
  16471. var p3p2 = p3.subtract(p2);
  16472. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16473. facesOfVertices[i1].push(index);
  16474. facesOfVertices[i2].push(index);
  16475. facesOfVertices[i3].push(index);
  16476. }
  16477. for (index = 0; index < positionVectors.length; index++) {
  16478. var faces = facesOfVertices[index];
  16479. var normal = BABYLON.Vector3.Zero();
  16480. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16481. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16482. }
  16483. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16484. normals[index * 3] = normal.x;
  16485. normals[index * 3 + 1] = normal.y;
  16486. normals[index * 3 + 2] = normal.z;
  16487. }
  16488. };
  16489. return VertexData;
  16490. })();
  16491. BABYLON.VertexData = VertexData;
  16492. })(BABYLON || (BABYLON = {}));
  16493. var __extends = this.__extends || function (d, b) {
  16494. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16495. function __() { this.constructor = d; }
  16496. __.prototype = b.prototype;
  16497. d.prototype = new __();
  16498. };
  16499. var BABYLON;
  16500. (function (BABYLON) {
  16501. var buildCamera = function (that, name) {
  16502. that._leftCamera.isIntermediate = true;
  16503. that.subCameras.push(that._leftCamera);
  16504. that.subCameras.push(that._rightCamera);
  16505. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16506. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16507. that._anaglyphPostProcess.onApply = function (effect) {
  16508. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16509. };
  16510. that._update();
  16511. };
  16512. var AnaglyphArcRotateCamera = (function (_super) {
  16513. __extends(AnaglyphArcRotateCamera, _super);
  16514. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16515. _super.call(this, name, alpha, beta, radius, target, scene);
  16516. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16517. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16518. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16519. buildCamera(this, name);
  16520. }
  16521. AnaglyphArcRotateCamera.prototype._update = function () {
  16522. this._updateCamera(this._leftCamera);
  16523. this._updateCamera(this._rightCamera);
  16524. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16525. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16526. _super.prototype._update.call(this);
  16527. };
  16528. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16529. camera.beta = this.beta;
  16530. camera.radius = this.radius;
  16531. camera.minZ = this.minZ;
  16532. camera.maxZ = this.maxZ;
  16533. camera.fov = this.fov;
  16534. camera.target = this.target;
  16535. };
  16536. return AnaglyphArcRotateCamera;
  16537. })(BABYLON.ArcRotateCamera);
  16538. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16539. var AnaglyphFreeCamera = (function (_super) {
  16540. __extends(AnaglyphFreeCamera, _super);
  16541. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16542. _super.call(this, name, position, scene);
  16543. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16544. this._transformMatrix = new BABYLON.Matrix();
  16545. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16546. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16547. buildCamera(this, name);
  16548. }
  16549. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16550. var target = this.getTarget();
  16551. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16552. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16553. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16554. };
  16555. AnaglyphFreeCamera.prototype._update = function () {
  16556. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16557. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16558. this._updateCamera(this._leftCamera);
  16559. this._updateCamera(this._rightCamera);
  16560. _super.prototype._update.call(this);
  16561. };
  16562. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16563. camera.minZ = this.minZ;
  16564. camera.maxZ = this.maxZ;
  16565. camera.fov = this.fov;
  16566. camera.viewport = this.viewport;
  16567. camera.setTarget(this.getTarget());
  16568. };
  16569. return AnaglyphFreeCamera;
  16570. })(BABYLON.FreeCamera);
  16571. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16572. })(BABYLON || (BABYLON = {}));
  16573. var __extends = this.__extends || function (d, b) {
  16574. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16575. function __() { this.constructor = d; }
  16576. __.prototype = b.prototype;
  16577. d.prototype = new __();
  16578. };
  16579. var BABYLON;
  16580. (function (BABYLON) {
  16581. var AnaglyphPostProcess = (function (_super) {
  16582. __extends(AnaglyphPostProcess, _super);
  16583. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16584. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16585. }
  16586. return AnaglyphPostProcess;
  16587. })(BABYLON.PostProcess);
  16588. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16589. })(BABYLON || (BABYLON = {}));
  16590. var BABYLON;
  16591. (function (BABYLON) {
  16592. var Tags = (function () {
  16593. function Tags() {
  16594. }
  16595. Tags.EnableFor = function (obj) {
  16596. obj._tags = obj._tags || {};
  16597. obj.hasTags = function () {
  16598. return Tags.HasTags(obj);
  16599. };
  16600. obj.addTags = function (tagsString) {
  16601. return Tags.AddTagsTo(obj, tagsString);
  16602. };
  16603. obj.removeTags = function (tagsString) {
  16604. return Tags.RemoveTagsFrom(obj, tagsString);
  16605. };
  16606. obj.matchesTagsQuery = function (tagsQuery) {
  16607. return Tags.MatchesQuery(obj, tagsQuery);
  16608. };
  16609. };
  16610. Tags.DisableFor = function (obj) {
  16611. delete obj._tags;
  16612. delete obj.hasTags;
  16613. delete obj.addTags;
  16614. delete obj.removeTags;
  16615. delete obj.matchesTagsQuery;
  16616. };
  16617. Tags.HasTags = function (obj) {
  16618. if (!obj._tags) {
  16619. return false;
  16620. }
  16621. return !BABYLON.Tools.IsEmpty(obj._tags);
  16622. };
  16623. Tags.GetTags = function (obj) {
  16624. if (!obj._tags) {
  16625. return null;
  16626. }
  16627. return obj._tags;
  16628. };
  16629. Tags.AddTagsTo = function (obj, tagsString) {
  16630. if (!tagsString) {
  16631. return;
  16632. }
  16633. var tags = tagsString.split(" ");
  16634. for (var t in tags) {
  16635. Tags._AddTagTo(obj, tags[t]);
  16636. }
  16637. };
  16638. Tags._AddTagTo = function (obj, tag) {
  16639. tag = tag.trim();
  16640. if (tag === "" || tag === "true" || tag === "false") {
  16641. return;
  16642. }
  16643. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16644. return;
  16645. }
  16646. Tags.EnableFor(obj);
  16647. obj._tags[tag] = true;
  16648. };
  16649. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16650. if (!Tags.HasTags(obj)) {
  16651. return;
  16652. }
  16653. var tags = tagsString.split(" ");
  16654. for (var t in tags) {
  16655. Tags._RemoveTagFrom(obj, tags[t]);
  16656. }
  16657. };
  16658. Tags._RemoveTagFrom = function (obj, tag) {
  16659. delete obj._tags[tag];
  16660. };
  16661. Tags.MatchesQuery = function (obj, tagsQuery) {
  16662. if (tagsQuery === undefined) {
  16663. return true;
  16664. }
  16665. if (tagsQuery === "") {
  16666. return Tags.HasTags(obj);
  16667. }
  16668. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16669. return Tags.HasTags(obj) && obj._tags[r];
  16670. });
  16671. };
  16672. return Tags;
  16673. })();
  16674. BABYLON.Tags = Tags;
  16675. })(BABYLON || (BABYLON = {}));
  16676. var BABYLON;
  16677. (function (BABYLON) {
  16678. (function (Internals) {
  16679. var AndOrNotEvaluator = (function () {
  16680. function AndOrNotEvaluator() {
  16681. }
  16682. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16683. if (!query.match(/\([^\(\)]*\)/g)) {
  16684. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16685. } else {
  16686. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16687. r = r.slice(1, r.length - 1);
  16688. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16689. });
  16690. }
  16691. if (query === "true") {
  16692. return true;
  16693. }
  16694. if (query === "false") {
  16695. return false;
  16696. }
  16697. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16698. };
  16699. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16700. evaluateCallback = evaluateCallback || (function (r) {
  16701. return r === "true" ? true : false;
  16702. });
  16703. var result;
  16704. var or = parenthesisContent.split("||");
  16705. for (var i in or) {
  16706. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16707. var and = ori.split("&&");
  16708. if (and.length > 1) {
  16709. for (var j = 0; j < and.length; ++j) {
  16710. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16711. if (andj !== "true" && andj !== "false") {
  16712. if (andj[0] === "!") {
  16713. result = !evaluateCallback(andj.substring(1));
  16714. } else {
  16715. result = evaluateCallback(andj);
  16716. }
  16717. } else {
  16718. result = andj === "true" ? true : false;
  16719. }
  16720. if (!result) {
  16721. ori = "false";
  16722. break;
  16723. }
  16724. }
  16725. }
  16726. if (result || ori === "true") {
  16727. result = true;
  16728. break;
  16729. }
  16730. if (ori !== "true" && ori !== "false") {
  16731. if (ori[0] === "!") {
  16732. result = !evaluateCallback(ori.substring(1));
  16733. } else {
  16734. result = evaluateCallback(ori);
  16735. }
  16736. } else {
  16737. result = ori === "true" ? true : false;
  16738. }
  16739. }
  16740. return result ? "true" : "false";
  16741. };
  16742. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16743. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16744. r = r.replace(/[\s]/g, function () {
  16745. return "";
  16746. });
  16747. return r.length % 2 ? "!" : "";
  16748. });
  16749. booleanString = booleanString.trim();
  16750. if (booleanString === "!true") {
  16751. booleanString = "false";
  16752. } else if (booleanString === "!false") {
  16753. booleanString = "true";
  16754. }
  16755. return booleanString;
  16756. };
  16757. return AndOrNotEvaluator;
  16758. })();
  16759. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16760. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16761. var Internals = BABYLON.Internals;
  16762. })(BABYLON || (BABYLON = {}));
  16763. var BABYLON;
  16764. (function (BABYLON) {
  16765. var PostProcessRenderPass = (function () {
  16766. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16767. this._enabled = true;
  16768. this._refCount = 0;
  16769. this._name = name;
  16770. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16771. this.setRenderList(renderList);
  16772. this._renderTexture.onBeforeRender = beforeRender;
  16773. this._renderTexture.onAfterRender = afterRender;
  16774. this._scene = scene;
  16775. }
  16776. PostProcessRenderPass.prototype._incRefCount = function () {
  16777. if (this._refCount === 0) {
  16778. this._scene.customRenderTargets.push(this._renderTexture);
  16779. }
  16780. return ++this._refCount;
  16781. };
  16782. PostProcessRenderPass.prototype._decRefCount = function () {
  16783. this._refCount--;
  16784. if (this._refCount <= 0) {
  16785. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16786. }
  16787. return this._refCount;
  16788. };
  16789. PostProcessRenderPass.prototype._update = function () {
  16790. this.setRenderList(this._renderList);
  16791. };
  16792. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16793. this._renderTexture.renderList = renderList;
  16794. };
  16795. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16796. return this._renderTexture;
  16797. };
  16798. return PostProcessRenderPass;
  16799. })();
  16800. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16801. })(BABYLON || (BABYLON = {}));
  16802. var BABYLON;
  16803. (function (BABYLON) {
  16804. var PostProcessRenderEffect = (function () {
  16805. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16806. this._engine = engine;
  16807. this._name = name;
  16808. this._postProcessType = postProcessType;
  16809. this._ratio = ratio || 1.0;
  16810. this._samplingMode = samplingMode || null;
  16811. this._singleInstance = singleInstance || true;
  16812. this._cameras = [];
  16813. this._postProcesses = [];
  16814. this._indicesForCamera = [];
  16815. this._renderPasses = [];
  16816. this._renderEffectAsPasses = [];
  16817. this.parameters = function (effect) {
  16818. };
  16819. }
  16820. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  16821. var postProcess;
  16822. var instance;
  16823. var args = [];
  16824. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  16825. for (var i = 0; i < parameters.length; i++) {
  16826. switch (parameters[i]) {
  16827. case "name":
  16828. args[i] = postProcessType.toString();
  16829. break;
  16830. case "ratio":
  16831. args[i] = ratio;
  16832. break;
  16833. case "camera":
  16834. args[i] = null;
  16835. break;
  16836. case "samplingMode":
  16837. args[i] = samplingMode;
  16838. break;
  16839. case "engine":
  16840. args[i] = engine;
  16841. break;
  16842. case "reusable":
  16843. args[i] = true;
  16844. break;
  16845. default:
  16846. args[i] = null;
  16847. break;
  16848. }
  16849. }
  16850. postProcess = function () {
  16851. };
  16852. postProcess.prototype = postProcessType.prototype;
  16853. instance = new postProcess();
  16854. postProcessType.apply(instance, args);
  16855. return instance;
  16856. };
  16857. PostProcessRenderEffect._GetParametersNames = function (func) {
  16858. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  16859. var functWithoutComments = func.toString().replace(commentsRegex, '');
  16860. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  16861. if (parameters === null)
  16862. parameters = [];
  16863. return parameters;
  16864. };
  16865. PostProcessRenderEffect.prototype._update = function () {
  16866. for (var renderPassName in this._renderPasses) {
  16867. this._renderPasses[renderPassName]._update();
  16868. }
  16869. };
  16870. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  16871. this._renderPasses[renderPass._name] = renderPass;
  16872. this._linkParameters();
  16873. };
  16874. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  16875. delete this._renderPasses[renderPass._name];
  16876. this._linkParameters();
  16877. };
  16878. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  16879. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  16880. this._linkParameters();
  16881. };
  16882. PostProcessRenderEffect.prototype.getPass = function (passName) {
  16883. for (var renderPassName in this._renderPasses) {
  16884. if (renderPassName === passName) {
  16885. return this._renderPasses[passName];
  16886. }
  16887. }
  16888. };
  16889. PostProcessRenderEffect.prototype.emptyPasses = function () {
  16890. this._renderPasses.length = 0;
  16891. this._linkParameters();
  16892. };
  16893. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  16894. var cameraKey;
  16895. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16896. for (var i = 0; i < _cam.length; i++) {
  16897. var camera = _cam[i];
  16898. var cameraName = camera.name;
  16899. if (this._singleInstance) {
  16900. cameraKey = 0;
  16901. } else {
  16902. cameraKey = cameraName;
  16903. }
  16904. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  16905. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  16906. if (this._indicesForCamera[cameraName] === null) {
  16907. this._indicesForCamera[cameraName] = [];
  16908. }
  16909. this._indicesForCamera[cameraName].push(index);
  16910. if (this._cameras.indexOf(camera) === -1) {
  16911. this._cameras[cameraName] = camera;
  16912. }
  16913. for (var passName in this._renderPasses) {
  16914. this._renderPasses[passName]._incRefCount();
  16915. }
  16916. }
  16917. this._linkParameters();
  16918. };
  16919. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  16920. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16921. for (var i = 0; i < _cam.length; i++) {
  16922. var camera = _cam[i];
  16923. var cameraName = camera.name;
  16924. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16925. var index = this._cameras.indexOf(cameraName);
  16926. this._indicesForCamera.splice(index, 1);
  16927. this._cameras.splice(index, 1);
  16928. for (var passName in this._renderPasses) {
  16929. this._renderPasses[passName]._decRefCount();
  16930. }
  16931. }
  16932. };
  16933. PostProcessRenderEffect.prototype._enable = function (cameras) {
  16934. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16935. for (var i = 0; i < _cam.length; i++) {
  16936. var camera = _cam[i];
  16937. var cameraName = camera.name;
  16938. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  16939. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  16940. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  16941. }
  16942. }
  16943. for (var passName in this._renderPasses) {
  16944. this._renderPasses[passName]._incRefCount();
  16945. }
  16946. }
  16947. };
  16948. PostProcessRenderEffect.prototype._disable = function (cameras) {
  16949. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16950. for (var i = 0; i < _cam.length; i++) {
  16951. var camera = _cam[i];
  16952. var cameraName = camera.Name;
  16953. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16954. for (var passName in this._renderPasses) {
  16955. this._renderPasses[passName]._decRefCount();
  16956. }
  16957. }
  16958. };
  16959. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  16960. if (this._singleInstance) {
  16961. return this._postProcesses[0];
  16962. } else {
  16963. return this._postProcesses[camera.name];
  16964. }
  16965. };
  16966. PostProcessRenderEffect.prototype._linkParameters = function () {
  16967. var _this = this;
  16968. for (var index in this._postProcesses) {
  16969. this._postProcesses[index].onApply = function (effect) {
  16970. _this.parameters(effect);
  16971. _this._linkTextures(effect);
  16972. };
  16973. }
  16974. };
  16975. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  16976. for (var renderPassName in this._renderPasses) {
  16977. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  16978. }
  16979. for (var renderEffectName in this._renderEffectAsPasses) {
  16980. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  16981. }
  16982. };
  16983. return PostProcessRenderEffect;
  16984. })();
  16985. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  16986. })(BABYLON || (BABYLON = {}));
  16987. var BABYLON;
  16988. (function (BABYLON) {
  16989. var PostProcessRenderPipeline = (function () {
  16990. function PostProcessRenderPipeline(engine, name) {
  16991. this._engine = engine;
  16992. this._name = name;
  16993. this._renderEffects = [];
  16994. this._renderEffectsForIsolatedPass = [];
  16995. this._cameras = [];
  16996. }
  16997. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  16998. this._renderEffects[renderEffect._name] = renderEffect;
  16999. };
  17000. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17001. var renderEffects = this._renderEffects[renderEffectName];
  17002. if (!renderEffects) {
  17003. return;
  17004. }
  17005. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17006. };
  17007. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17008. var renderEffects = this._renderEffects[renderEffectName];
  17009. if (!renderEffects) {
  17010. return;
  17011. }
  17012. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17013. };
  17014. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17015. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17016. var indicesToDelete = [];
  17017. for (var i = 0; i < _cam.length; i++) {
  17018. var camera = _cam[i];
  17019. var cameraName = camera.name;
  17020. if (this._cameras.indexOf(camera) === -1) {
  17021. this._cameras[cameraName] = camera;
  17022. } else if (unique) {
  17023. indicesToDelete.push(i);
  17024. }
  17025. }
  17026. for (var i = 0; i < indicesToDelete.length; i++) {
  17027. cameras.splice(indicesToDelete[i], 1);
  17028. }
  17029. for (var renderEffectName in this._renderEffects) {
  17030. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17031. }
  17032. };
  17033. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17034. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17035. for (var renderEffectName in this._renderEffects) {
  17036. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17037. }
  17038. for (var i = 0; i < _cam.length; i++) {
  17039. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17040. }
  17041. };
  17042. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17043. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17044. var pass = null;
  17045. for (var renderEffectName in this._renderEffects) {
  17046. pass = this._renderEffects[renderEffectName].getPass(passName);
  17047. if (pass != null) {
  17048. break;
  17049. }
  17050. }
  17051. if (pass === null) {
  17052. return;
  17053. }
  17054. for (var renderEffectName in this._renderEffects) {
  17055. this._renderEffects[renderEffectName]._disable(_cam);
  17056. }
  17057. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17058. for (var i = 0; i < _cam.length; i++) {
  17059. var camera = _cam[i];
  17060. var cameraName = camera.name;
  17061. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17062. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17063. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17064. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17065. }
  17066. };
  17067. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17068. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17069. for (var i = 0; i < _cam.length; i++) {
  17070. var camera = _cam[i];
  17071. var cameraName = camera.name;
  17072. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17073. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17074. }
  17075. for (var renderEffectName in this._renderEffects) {
  17076. this._renderEffects[renderEffectName]._enable(_cam);
  17077. }
  17078. };
  17079. PostProcessRenderPipeline.prototype._update = function () {
  17080. for (var renderEffectName in this._renderEffects) {
  17081. this._renderEffects[renderEffectName]._update();
  17082. }
  17083. for (var i = 0; i < this._cameras.length; i++) {
  17084. var cameraName = this._cameras[i].name;
  17085. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17086. this._renderEffectsForIsolatedPass[cameraName]._update();
  17087. }
  17088. }
  17089. };
  17090. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17091. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17092. return PostProcessRenderPipeline;
  17093. })();
  17094. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17095. })(BABYLON || (BABYLON = {}));
  17096. var BABYLON;
  17097. (function (BABYLON) {
  17098. var PostProcessRenderPipelineManager = (function () {
  17099. function PostProcessRenderPipelineManager() {
  17100. this._renderPipelines = [];
  17101. }
  17102. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17103. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17104. };
  17105. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17106. var renderPipeline = this._renderPipelines[renderPipelineName];
  17107. if (!renderPipeline) {
  17108. return;
  17109. }
  17110. renderPipeline.attachCameras(cameras, unique);
  17111. };
  17112. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17113. var renderPipeline = this._renderPipelines[renderPipelineName];
  17114. if (!renderPipeline) {
  17115. return;
  17116. }
  17117. renderPipeline.detachCameras(cameras);
  17118. };
  17119. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17120. var renderPipeline = this._renderPipelines[renderPipelineName];
  17121. if (!renderPipeline) {
  17122. return;
  17123. }
  17124. renderPipeline.enableEffect(renderEffectName, cameras);
  17125. };
  17126. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17127. var renderPipeline = this._renderPipelines[renderPipelineName];
  17128. if (!renderPipeline) {
  17129. return;
  17130. }
  17131. renderPipeline.disableEffect(renderEffectName, cameras);
  17132. };
  17133. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17134. var renderPipeline = this._renderPipelines[renderPipelineName];
  17135. if (!renderPipeline) {
  17136. return;
  17137. }
  17138. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17139. };
  17140. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17141. var renderPipeline = this._renderPipelines[renderPipelineName];
  17142. if (!renderPipeline) {
  17143. return;
  17144. }
  17145. renderPipeline.disableDisplayOnlyPass(cameras);
  17146. };
  17147. PostProcessRenderPipelineManager.prototype.update = function () {
  17148. for (var renderPipelineName in this._renderPipelines) {
  17149. this._renderPipelines[renderPipelineName]._update();
  17150. }
  17151. };
  17152. return PostProcessRenderPipelineManager;
  17153. })();
  17154. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17155. })(BABYLON || (BABYLON = {}));
  17156. var __extends = this.__extends || function (d, b) {
  17157. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17158. function __() { this.constructor = d; }
  17159. __.prototype = b.prototype;
  17160. d.prototype = new __();
  17161. };
  17162. var BABYLON;
  17163. (function (BABYLON) {
  17164. var DisplayPassPostProcess = (function (_super) {
  17165. __extends(DisplayPassPostProcess, _super);
  17166. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17167. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17168. }
  17169. return DisplayPassPostProcess;
  17170. })(BABYLON.PostProcess);
  17171. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17172. })(BABYLON || (BABYLON = {}));
  17173. var BABYLON;
  17174. (function (BABYLON) {
  17175. var BoundingBoxRenderer = (function () {
  17176. function BoundingBoxRenderer(scene) {
  17177. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17178. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17179. this.showBackLines = true;
  17180. this.renderList = new BABYLON.SmartArray(32);
  17181. this._scene = scene;
  17182. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17183. attributes: ["position"],
  17184. uniforms: ["worldViewProjection", "color"]
  17185. });
  17186. var engine = this._scene.getEngine();
  17187. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17188. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17189. 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]);
  17190. }
  17191. BoundingBoxRenderer.prototype.reset = function () {
  17192. this.renderList.reset();
  17193. };
  17194. BoundingBoxRenderer.prototype.render = function () {
  17195. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17196. return;
  17197. }
  17198. var engine = this._scene.getEngine();
  17199. engine.setDepthWrite(false);
  17200. this._colorShader._preBind();
  17201. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17202. var boundingBox = this.renderList.data[boundingBoxIndex];
  17203. var min = boundingBox.minimum;
  17204. var max = boundingBox.maximum;
  17205. var diff = max.subtract(min);
  17206. var median = min.add(diff.scale(0.5));
  17207. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17208. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17209. if (this.showBackLines) {
  17210. engine.setDepthFunctionToGreaterOrEqual();
  17211. this._colorShader.setColor4("color", this.backColor.toColor4());
  17212. this._colorShader.bind(worldMatrix);
  17213. engine.draw(false, 0, 24);
  17214. }
  17215. engine.setDepthFunctionToLess();
  17216. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17217. this._colorShader.bind(worldMatrix);
  17218. engine.draw(false, 0, 24);
  17219. }
  17220. this._colorShader.unbind();
  17221. engine.setDepthFunctionToLessOrEqual();
  17222. engine.setDepthWrite(true);
  17223. };
  17224. BoundingBoxRenderer.prototype.dispose = function () {
  17225. this._colorShader.dispose();
  17226. this._vb.dispose();
  17227. this._scene.getEngine()._releaseBuffer(this._ib);
  17228. };
  17229. return BoundingBoxRenderer;
  17230. })();
  17231. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17232. })(BABYLON || (BABYLON = {}));
  17233. /**
  17234. * Based on jsTGALoader - Javascript loader for TGA file
  17235. * By Vincent Thibault
  17236. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17237. */
  17238. var BABYLON;
  17239. (function (BABYLON) {
  17240. (function (Internals) {
  17241. var TGATools = (function () {
  17242. function TGATools() {
  17243. }
  17244. TGATools.GetTGAHeader = function (data) {
  17245. var offset = 0;
  17246. var header = {
  17247. id_length: data[offset++],
  17248. colormap_type: data[offset++],
  17249. image_type: data[offset++],
  17250. colormap_index: data[offset++] | data[offset++] << 8,
  17251. colormap_length: data[offset++] | data[offset++] << 8,
  17252. colormap_size: data[offset++],
  17253. origin: [
  17254. data[offset++] | data[offset++] << 8,
  17255. data[offset++] | data[offset++] << 8
  17256. ],
  17257. width: data[offset++] | data[offset++] << 8,
  17258. height: data[offset++] | data[offset++] << 8,
  17259. pixel_size: data[offset++],
  17260. flags: data[offset++]
  17261. };
  17262. return header;
  17263. };
  17264. TGATools.UploadContent = function (gl, data) {
  17265. if (data.length < 19) {
  17266. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17267. return;
  17268. }
  17269. var offset = 18;
  17270. var header = TGATools.GetTGAHeader(data);
  17271. if (header.id_length + offset > data.length) {
  17272. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17273. return;
  17274. }
  17275. offset += header.id_length;
  17276. var use_rle = false;
  17277. var use_pal = false;
  17278. var use_rgb = false;
  17279. var use_grey = false;
  17280. switch (header.image_type) {
  17281. case TGATools._TYPE_RLE_INDEXED:
  17282. use_rle = true;
  17283. case TGATools._TYPE_INDEXED:
  17284. use_pal = true;
  17285. break;
  17286. case TGATools._TYPE_RLE_RGB:
  17287. use_rle = true;
  17288. case TGATools._TYPE_RGB:
  17289. use_rgb = true;
  17290. break;
  17291. case TGATools._TYPE_RLE_GREY:
  17292. use_rle = true;
  17293. case TGATools._TYPE_GREY:
  17294. use_grey = true;
  17295. break;
  17296. }
  17297. var pixel_data;
  17298. var numAlphaBits = header.flags & 0xf;
  17299. var pixel_size = header.pixel_size >> 3;
  17300. var pixel_total = header.width * header.height * pixel_size;
  17301. var palettes;
  17302. if (use_pal) {
  17303. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17304. }
  17305. if (use_rle) {
  17306. pixel_data = new Uint8Array(pixel_total);
  17307. var c, count, i;
  17308. var localOffset = 0;
  17309. var pixels = new Uint8Array(pixel_size);
  17310. while (offset < pixel_total) {
  17311. c = data[offset++];
  17312. count = (c & 0x7f) + 1;
  17313. if (c & 0x80) {
  17314. for (i = 0; i < pixel_size; ++i) {
  17315. pixels[i] = data[offset++];
  17316. }
  17317. for (i = 0; i < count; ++i) {
  17318. pixel_data.set(pixels, localOffset + i * pixel_size);
  17319. }
  17320. localOffset += pixel_size * count;
  17321. } else {
  17322. count *= pixel_size;
  17323. for (i = 0; i < count; ++i) {
  17324. pixel_data[localOffset + i] = data[offset++];
  17325. }
  17326. localOffset += count;
  17327. }
  17328. }
  17329. } else {
  17330. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17331. }
  17332. var x_start, y_start, x_step, y_step, y_end, x_end;
  17333. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17334. default:
  17335. case TGATools._ORIGIN_UL:
  17336. x_start = 0;
  17337. x_step = 1;
  17338. x_end = header.width;
  17339. y_start = 0;
  17340. y_step = 1;
  17341. y_end = header.height;
  17342. break;
  17343. case TGATools._ORIGIN_BL:
  17344. x_start = 0;
  17345. x_step = 1;
  17346. x_end = header.width;
  17347. y_start = header.height - 1;
  17348. y_step = -1;
  17349. y_end = -1;
  17350. break;
  17351. case TGATools._ORIGIN_UR:
  17352. x_start = header.width - 1;
  17353. x_step = -1;
  17354. x_end = -1;
  17355. y_start = 0;
  17356. y_step = 1;
  17357. y_end = header.height;
  17358. break;
  17359. case TGATools._ORIGIN_BR:
  17360. x_start = header.width - 1;
  17361. x_step = -1;
  17362. x_end = -1;
  17363. y_start = header.height - 1;
  17364. y_step = -1;
  17365. y_end = -1;
  17366. break;
  17367. }
  17368. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17369. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17370. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17371. };
  17372. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17373. var image = pixel_data, colormap = palettes;
  17374. var width = header.width, height = header.height;
  17375. var color, i = 0, x, y;
  17376. var imageData = new Uint8Array(width * height * 4);
  17377. for (y = y_start; y !== y_end; y += y_step) {
  17378. for (x = x_start; x !== x_end; x += x_step, i++) {
  17379. color = image[i];
  17380. imageData[(x + width * y) * 4 + 3] = 255;
  17381. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17382. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17383. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17384. }
  17385. }
  17386. return imageData;
  17387. };
  17388. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17389. var image = pixel_data;
  17390. var width = header.width, height = header.height;
  17391. var color, i = 0, x, y;
  17392. var imageData = new Uint8Array(width * height * 4);
  17393. for (y = y_start; y !== y_end; y += y_step) {
  17394. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17395. color = image[i + 0] + (image[i + 1] << 8);
  17396. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17397. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17398. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17399. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17400. }
  17401. }
  17402. return imageData;
  17403. };
  17404. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17405. var image = pixel_data;
  17406. var width = header.width, height = header.height;
  17407. var i = 0, x, y;
  17408. var imageData = new Uint8Array(width * height * 4);
  17409. for (y = y_start; y !== y_end; y += y_step) {
  17410. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17411. imageData[(x + width * y) * 4 + 3] = 255;
  17412. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17413. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17414. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17415. }
  17416. }
  17417. return imageData;
  17418. };
  17419. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17420. var image = pixel_data;
  17421. var width = header.width, height = header.height;
  17422. var i = 0, x, y;
  17423. var imageData = new Uint8Array(width * height * 4);
  17424. for (y = y_start; y !== y_end; y += y_step) {
  17425. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17426. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17427. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17428. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17429. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17430. }
  17431. }
  17432. return imageData;
  17433. };
  17434. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17435. var image = pixel_data;
  17436. var width = header.width, height = header.height;
  17437. var color, i = 0, x, y;
  17438. var imageData = new Uint8Array(width * height * 4);
  17439. for (y = y_start; y !== y_end; y += y_step) {
  17440. for (x = x_start; x !== x_end; x += x_step, i++) {
  17441. color = image[i];
  17442. imageData[(x + width * y) * 4 + 0] = color;
  17443. imageData[(x + width * y) * 4 + 1] = color;
  17444. imageData[(x + width * y) * 4 + 2] = color;
  17445. imageData[(x + width * y) * 4 + 3] = 255;
  17446. }
  17447. }
  17448. return imageData;
  17449. };
  17450. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17451. var image = pixel_data;
  17452. var width = header.width, height = header.height;
  17453. var i = 0, x, y;
  17454. var imageData = new Uint8Array(width * height * 4);
  17455. for (y = y_start; y !== y_end; y += y_step) {
  17456. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17457. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17458. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17459. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17460. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17461. }
  17462. }
  17463. return imageData;
  17464. };
  17465. TGATools._TYPE_NO_DATA = 0;
  17466. TGATools._TYPE_INDEXED = 1;
  17467. TGATools._TYPE_RGB = 2;
  17468. TGATools._TYPE_GREY = 3;
  17469. TGATools._TYPE_RLE_INDEXED = 9;
  17470. TGATools._TYPE_RLE_RGB = 10;
  17471. TGATools._TYPE_RLE_GREY = 11;
  17472. TGATools._ORIGIN_MASK = 0x30;
  17473. TGATools._ORIGIN_SHIFT = 0x04;
  17474. TGATools._ORIGIN_BL = 0x00;
  17475. TGATools._ORIGIN_BR = 0x01;
  17476. TGATools._ORIGIN_UL = 0x02;
  17477. TGATools._ORIGIN_UR = 0x03;
  17478. return TGATools;
  17479. })();
  17480. Internals.TGATools = TGATools;
  17481. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17482. var Internals = BABYLON.Internals;
  17483. })(BABYLON || (BABYLON = {}));
  17484. var BABYLON;
  17485. (function (BABYLON) {
  17486. (function (Internals) {
  17487. var DDS_MAGIC = 0x20534444;
  17488. 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;
  17489. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17490. 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;
  17491. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17492. function FourCCToInt32(value) {
  17493. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17494. }
  17495. function Int32ToFourCC(value) {
  17496. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17497. }
  17498. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17499. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17500. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17501. var headerLengthInt = 31;
  17502. var off_magic = 0;
  17503. var off_size = 1;
  17504. var off_flags = 2;
  17505. var off_height = 3;
  17506. var off_width = 4;
  17507. var off_mipmapCount = 7;
  17508. var off_pfFlags = 20;
  17509. var off_pfFourCC = 21;
  17510. var off_RGBbpp = 22;
  17511. var off_RMask = 23;
  17512. var off_GMask = 24;
  17513. var off_BMask = 25;
  17514. var off_AMask = 26;
  17515. var off_caps1 = 27;
  17516. var off_caps2 = 28;
  17517. ;
  17518. var DDSTools = (function () {
  17519. function DDSTools() {
  17520. }
  17521. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17522. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17523. var mipmapCount = 1;
  17524. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17525. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17526. }
  17527. return {
  17528. width: header[off_width],
  17529. height: header[off_height],
  17530. mipmapCount: mipmapCount,
  17531. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17532. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17533. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17534. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17535. };
  17536. };
  17537. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17538. var byteArray = new Uint8Array(dataLength);
  17539. var srcData = new Uint8Array(arrayBuffer);
  17540. var index = 0;
  17541. for (var y = height - 1; y >= 0; y--) {
  17542. for (var x = 0; x < width; x++) {
  17543. var srcPos = dataOffset + (x + y * width) * 4;
  17544. byteArray[index + 2] = srcData[srcPos];
  17545. byteArray[index + 1] = srcData[srcPos + 1];
  17546. byteArray[index] = srcData[srcPos + 2];
  17547. byteArray[index + 3] = srcData[srcPos + 3];
  17548. index += 4;
  17549. }
  17550. }
  17551. return byteArray;
  17552. };
  17553. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17554. var byteArray = new Uint8Array(dataLength);
  17555. var srcData = new Uint8Array(arrayBuffer);
  17556. var index = 0;
  17557. for (var y = height - 1; y >= 0; y--) {
  17558. for (var x = 0; x < width; x++) {
  17559. var srcPos = dataOffset + (x + y * width) * 3;
  17560. byteArray[index + 2] = srcData[srcPos];
  17561. byteArray[index + 1] = srcData[srcPos + 1];
  17562. byteArray[index] = srcData[srcPos + 2];
  17563. index += 3;
  17564. }
  17565. }
  17566. return byteArray;
  17567. };
  17568. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17569. var byteArray = new Uint8Array(dataLength);
  17570. var srcData = new Uint8Array(arrayBuffer);
  17571. var index = 0;
  17572. for (var y = height - 1; y >= 0; y--) {
  17573. for (var x = 0; x < width; x++) {
  17574. var srcPos = dataOffset + (x + y * width);
  17575. byteArray[index] = srcData[srcPos];
  17576. index++;
  17577. }
  17578. }
  17579. return byteArray;
  17580. };
  17581. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17582. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17583. if (header[off_magic] != DDS_MAGIC) {
  17584. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17585. return;
  17586. }
  17587. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17588. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17589. return;
  17590. }
  17591. if (info.isFourCC) {
  17592. fourCC = header[off_pfFourCC];
  17593. switch (fourCC) {
  17594. case FOURCC_DXT1:
  17595. blockBytes = 8;
  17596. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17597. break;
  17598. case FOURCC_DXT3:
  17599. blockBytes = 16;
  17600. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17601. break;
  17602. case FOURCC_DXT5:
  17603. blockBytes = 16;
  17604. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17605. break;
  17606. default:
  17607. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17608. return;
  17609. }
  17610. }
  17611. mipmapCount = 1;
  17612. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17613. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17614. }
  17615. var bpp = header[off_RGBbpp];
  17616. for (var face = 0; face < faces; face++) {
  17617. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17618. width = header[off_width];
  17619. height = header[off_height];
  17620. dataOffset = header[off_size] + 4;
  17621. for (i = 0; i < mipmapCount; ++i) {
  17622. if (info.isRGB) {
  17623. if (bpp == 24) {
  17624. dataLength = width * height * 3;
  17625. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17626. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17627. } else {
  17628. dataLength = width * height * 4;
  17629. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17630. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17631. }
  17632. } else if (info.isLuminance) {
  17633. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17634. var unpaddedRowSize = width;
  17635. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17636. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17637. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17638. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17639. } else {
  17640. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17641. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17642. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17643. }
  17644. dataOffset += dataLength;
  17645. width *= 0.5;
  17646. height *= 0.5;
  17647. width = Math.max(1.0, width);
  17648. height = Math.max(1.0, height);
  17649. }
  17650. }
  17651. };
  17652. return DDSTools;
  17653. })();
  17654. Internals.DDSTools = DDSTools;
  17655. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17656. var Internals = BABYLON.Internals;
  17657. })(BABYLON || (BABYLON = {}));
  17658. var BABYLON;
  17659. (function (BABYLON) {
  17660. var SmartArray = (function () {
  17661. function SmartArray(capacity) {
  17662. this.length = 0;
  17663. this._duplicateId = 0;
  17664. this.data = new Array(capacity);
  17665. this._id = SmartArray._GlobalId++;
  17666. }
  17667. SmartArray.prototype.push = function (value) {
  17668. this.data[this.length++] = value;
  17669. if (this.length > this.data.length) {
  17670. this.data.length *= 2;
  17671. }
  17672. if (!value.__smartArrayFlags) {
  17673. value.__smartArrayFlags = {};
  17674. }
  17675. value.__smartArrayFlags[this._id] = this._duplicateId;
  17676. };
  17677. SmartArray.prototype.pushNoDuplicate = function (value) {
  17678. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17679. return;
  17680. }
  17681. this.push(value);
  17682. };
  17683. SmartArray.prototype.sort = function (compareFn) {
  17684. this.data.sort(compareFn);
  17685. };
  17686. SmartArray.prototype.reset = function () {
  17687. this.length = 0;
  17688. this._duplicateId++;
  17689. };
  17690. SmartArray.prototype.concat = function (array) {
  17691. if (array.length === 0) {
  17692. return;
  17693. }
  17694. if (this.length + array.length > this.data.length) {
  17695. this.data.length = (this.length + array.length) * 2;
  17696. }
  17697. for (var index = 0; index < array.length; index++) {
  17698. this.data[this.length++] = (array.data || array)[index];
  17699. }
  17700. };
  17701. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17702. if (array.length === 0) {
  17703. return;
  17704. }
  17705. if (this.length + array.length > this.data.length) {
  17706. this.data.length = (this.length + array.length) * 2;
  17707. }
  17708. for (var index = 0; index < array.length; index++) {
  17709. var item = (array.data || array)[index];
  17710. this.pushNoDuplicate(item);
  17711. }
  17712. };
  17713. SmartArray.prototype.indexOf = function (value) {
  17714. var position = this.data.indexOf(value);
  17715. if (position >= this.length) {
  17716. return -1;
  17717. }
  17718. return position;
  17719. };
  17720. SmartArray._GlobalId = 0;
  17721. return SmartArray;
  17722. })();
  17723. BABYLON.SmartArray = SmartArray;
  17724. })(BABYLON || (BABYLON = {}));
  17725. var BABYLON;
  17726. (function (BABYLON) {
  17727. var CannonJSPlugin = (function () {
  17728. function CannonJSPlugin() {
  17729. this._registeredMeshes = [];
  17730. this._physicsMaterials = [];
  17731. this.updateBodyPosition = function (mesh) {
  17732. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17733. var registeredMesh = this._registeredMeshes[index];
  17734. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17735. var body = registeredMesh.body.body;
  17736. var center = mesh.getBoundingInfo().boundingBox.center;
  17737. body.position.set(center.x, center.z, center.y);
  17738. body.quaternion.x = mesh.rotationQuaternion.x;
  17739. body.quaternion.z = mesh.rotationQuaternion.y;
  17740. body.quaternion.y = mesh.rotationQuaternion.z;
  17741. body.quaternion.w = -mesh.rotationQuaternion.w;
  17742. return;
  17743. }
  17744. }
  17745. };
  17746. }
  17747. CannonJSPlugin.prototype.initialize = function (iterations) {
  17748. if (typeof iterations === "undefined") { iterations = 10; }
  17749. this._world = new CANNON.World();
  17750. this._world.broadphase = new CANNON.NaiveBroadphase();
  17751. this._world.solver.iterations = iterations;
  17752. };
  17753. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17754. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17755. };
  17756. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17757. this._world.step(delta);
  17758. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17759. var registeredMesh = this._registeredMeshes[index];
  17760. if (registeredMesh.isChild) {
  17761. continue;
  17762. }
  17763. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17764. var deltaPos = registeredMesh.delta;
  17765. if (deltaPos) {
  17766. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17767. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17768. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17769. } else {
  17770. registeredMesh.mesh.position.x = bodyX;
  17771. registeredMesh.mesh.position.y = bodyZ;
  17772. registeredMesh.mesh.position.z = bodyY;
  17773. }
  17774. if (!registeredMesh.mesh.rotationQuaternion) {
  17775. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17776. }
  17777. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17778. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17779. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17780. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17781. }
  17782. };
  17783. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17784. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17785. };
  17786. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17787. this.unregisterMesh(mesh);
  17788. mesh.computeWorldMatrix(true);
  17789. switch (impostor) {
  17790. case BABYLON.PhysicsEngine.SphereImpostor:
  17791. var bbox = mesh.getBoundingInfo().boundingBox;
  17792. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17793. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17794. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17795. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17796. case BABYLON.PhysicsEngine.BoxImpostor:
  17797. bbox = mesh.getBoundingInfo().boundingBox;
  17798. var min = bbox.minimumWorld;
  17799. var max = bbox.maximumWorld;
  17800. var box = max.subtract(min).scale(0.5);
  17801. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17802. case BABYLON.PhysicsEngine.PlaneImpostor:
  17803. return this._createPlane(mesh, options);
  17804. case BABYLON.PhysicsEngine.MeshImpostor:
  17805. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17806. var rawFaces = mesh.getIndices();
  17807. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17808. }
  17809. return null;
  17810. };
  17811. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17812. var shape = new CANNON.Sphere(radius);
  17813. if (!options) {
  17814. return shape;
  17815. }
  17816. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17817. };
  17818. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  17819. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  17820. if (!options) {
  17821. return shape;
  17822. }
  17823. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17824. };
  17825. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  17826. var shape = new CANNON.Plane();
  17827. if (!options) {
  17828. return shape;
  17829. }
  17830. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17831. };
  17832. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  17833. var verts = [], faces = [];
  17834. mesh.computeWorldMatrix(true);
  17835. for (var i = 0; i < rawVerts.length; i += 3) {
  17836. var transformed = BABYLON.Vector3.Zero();
  17837. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  17838. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  17839. }
  17840. for (var j = 0; j < rawFaces.length; j += 3) {
  17841. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  17842. }
  17843. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  17844. if (!options) {
  17845. return shape;
  17846. }
  17847. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17848. };
  17849. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  17850. var index;
  17851. var mat;
  17852. for (index = 0; index < this._physicsMaterials.length; index++) {
  17853. mat = this._physicsMaterials[index];
  17854. if (mat.friction === friction && mat.restitution === restitution) {
  17855. return mat;
  17856. }
  17857. }
  17858. var currentMat = new CANNON.Material();
  17859. currentMat.friction = friction;
  17860. currentMat.restitution = restitution;
  17861. this._physicsMaterials.push(currentMat);
  17862. for (index = 0; index < this._physicsMaterials.length; index++) {
  17863. mat = this._physicsMaterials[index];
  17864. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  17865. contactMaterial.contactEquationStiffness = 1e10;
  17866. contactMaterial.contactEquationRegularizationTime = 10;
  17867. this._world.addContactMaterial(contactMaterial);
  17868. }
  17869. return currentMat;
  17870. };
  17871. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  17872. var initialRotation = null;
  17873. if (mesh.rotationQuaternion) {
  17874. initialRotation = mesh.rotationQuaternion.clone();
  17875. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17876. }
  17877. var bbox = mesh.getBoundingInfo().boundingBox;
  17878. var deltaPosition = mesh.position.subtract(bbox.center);
  17879. var material = this._addMaterial(friction, restitution);
  17880. var body = new CANNON.RigidBody(mass, shape, material);
  17881. if (initialRotation) {
  17882. body.quaternion.x = initialRotation.x;
  17883. body.quaternion.z = initialRotation.y;
  17884. body.quaternion.y = initialRotation.z;
  17885. body.quaternion.w = -initialRotation.w;
  17886. }
  17887. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  17888. this._world.add(body);
  17889. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  17890. return body;
  17891. };
  17892. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17893. var compoundShape = new CANNON.Compound();
  17894. for (var index = 0; index < parts.length; index++) {
  17895. var mesh = parts[index].mesh;
  17896. var shape = this.registerMesh(mesh, parts[index].impostor);
  17897. if (index == 0) {
  17898. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  17899. } else {
  17900. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  17901. }
  17902. }
  17903. var initialMesh = parts[0].mesh;
  17904. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  17905. body.parts = parts;
  17906. return body;
  17907. };
  17908. CannonJSPlugin.prototype._unbindBody = function (body) {
  17909. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17910. var registeredMesh = this._registeredMeshes[index];
  17911. if (registeredMesh.body === body) {
  17912. registeredMesh.body = null;
  17913. registeredMesh.delta = 0;
  17914. }
  17915. }
  17916. };
  17917. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  17918. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17919. var registeredMesh = this._registeredMeshes[index];
  17920. if (registeredMesh.mesh === mesh) {
  17921. if (registeredMesh.body) {
  17922. this._world.remove(registeredMesh.body);
  17923. this._unbindBody(registeredMesh.body);
  17924. }
  17925. this._registeredMeshes.splice(index, 1);
  17926. return;
  17927. }
  17928. }
  17929. };
  17930. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17931. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  17932. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  17933. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17934. var registeredMesh = this._registeredMeshes[index];
  17935. if (registeredMesh.mesh === mesh) {
  17936. registeredMesh.body.applyImpulse(impulse, worldPoint);
  17937. return;
  17938. }
  17939. }
  17940. };
  17941. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  17942. var body1 = null, body2 = null;
  17943. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17944. var registeredMesh = this._registeredMeshes[index];
  17945. if (registeredMesh.mesh === mesh1) {
  17946. body1 = registeredMesh.body;
  17947. } else if (registeredMesh.mesh === mesh2) {
  17948. body2 = registeredMesh.body;
  17949. }
  17950. }
  17951. if (!body1 || !body2) {
  17952. return false;
  17953. }
  17954. 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));
  17955. this._world.addConstraint(constraint);
  17956. return true;
  17957. };
  17958. CannonJSPlugin.prototype.dispose = function () {
  17959. while (this._registeredMeshes.length) {
  17960. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17961. }
  17962. };
  17963. CannonJSPlugin.prototype.isSupported = function () {
  17964. return window.CANNON !== undefined;
  17965. };
  17966. return CannonJSPlugin;
  17967. })();
  17968. BABYLON.CannonJSPlugin = CannonJSPlugin;
  17969. })(BABYLON || (BABYLON = {}));
  17970. var __extends = this.__extends || function (d, b) {
  17971. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17972. function __() { this.constructor = d; }
  17973. __.prototype = b.prototype;
  17974. d.prototype = new __();
  17975. };
  17976. var BABYLON;
  17977. (function (BABYLON) {
  17978. var Condition = (function () {
  17979. function Condition(actionManager) {
  17980. this._actionManager = actionManager;
  17981. }
  17982. Condition.prototype.isValid = function () {
  17983. return true;
  17984. };
  17985. Condition.prototype._getProperty = function (propertyPath) {
  17986. return this._actionManager._getProperty(propertyPath);
  17987. };
  17988. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  17989. return this._actionManager._getEffectiveTarget(target, propertyPath);
  17990. };
  17991. return Condition;
  17992. })();
  17993. BABYLON.Condition = Condition;
  17994. var ValueCondition = (function (_super) {
  17995. __extends(ValueCondition, _super);
  17996. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  17997. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  17998. _super.call(this, actionManager);
  17999. this.propertyPath = propertyPath;
  18000. this.value = value;
  18001. this.operator = operator;
  18002. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18003. this._property = this._getProperty(this.propertyPath);
  18004. }
  18005. Object.defineProperty(ValueCondition, "IsEqual", {
  18006. get: function () {
  18007. return ValueCondition._IsEqual;
  18008. },
  18009. enumerable: true,
  18010. configurable: true
  18011. });
  18012. Object.defineProperty(ValueCondition, "IsDifferent", {
  18013. get: function () {
  18014. return ValueCondition._IsDifferent;
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. Object.defineProperty(ValueCondition, "IsGreater", {
  18020. get: function () {
  18021. return ValueCondition._IsGreater;
  18022. },
  18023. enumerable: true,
  18024. configurable: true
  18025. });
  18026. Object.defineProperty(ValueCondition, "IsLesser", {
  18027. get: function () {
  18028. return ValueCondition._IsLesser;
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. ValueCondition.prototype.isValid = function () {
  18034. switch (this.operator) {
  18035. case ValueCondition.IsGreater:
  18036. return this._target[this._property] > this.value;
  18037. case ValueCondition.IsLesser:
  18038. return this._target[this._property] < this.value;
  18039. case ValueCondition.IsEqual:
  18040. case ValueCondition.IsDifferent:
  18041. var check;
  18042. if (this.value.equals) {
  18043. check = this.value.equals(this._target[this._property]);
  18044. } else {
  18045. check = this.value === this._target[this._property];
  18046. }
  18047. return this.operator === ValueCondition.IsEqual ? check : !check;
  18048. }
  18049. return false;
  18050. };
  18051. ValueCondition._IsEqual = 0;
  18052. ValueCondition._IsDifferent = 1;
  18053. ValueCondition._IsGreater = 2;
  18054. ValueCondition._IsLesser = 3;
  18055. return ValueCondition;
  18056. })(Condition);
  18057. BABYLON.ValueCondition = ValueCondition;
  18058. var PredicateCondition = (function (_super) {
  18059. __extends(PredicateCondition, _super);
  18060. function PredicateCondition(actionManager, predicate) {
  18061. _super.call(this, actionManager);
  18062. this.predicate = predicate;
  18063. }
  18064. PredicateCondition.prototype.isValid = function () {
  18065. return this.predicate();
  18066. };
  18067. return PredicateCondition;
  18068. })(Condition);
  18069. BABYLON.PredicateCondition = PredicateCondition;
  18070. var StateCondition = (function (_super) {
  18071. __extends(StateCondition, _super);
  18072. function StateCondition(actionManager, target, value) {
  18073. _super.call(this, actionManager);
  18074. this.value = value;
  18075. this._target = target;
  18076. }
  18077. StateCondition.prototype.isValid = function () {
  18078. return this._target.state === this.value;
  18079. };
  18080. return StateCondition;
  18081. })(Condition);
  18082. BABYLON.StateCondition = StateCondition;
  18083. })(BABYLON || (BABYLON = {}));
  18084. var BABYLON;
  18085. (function (BABYLON) {
  18086. var Action = (function () {
  18087. function Action(triggerOptions, condition) {
  18088. this.triggerOptions = triggerOptions;
  18089. if (triggerOptions.parameter) {
  18090. this.trigger = triggerOptions.trigger;
  18091. this._triggerParameter = triggerOptions.parameter;
  18092. } else {
  18093. this.trigger = triggerOptions;
  18094. }
  18095. this._nextActiveAction = this;
  18096. this._condition = condition;
  18097. }
  18098. Action.prototype._prepare = function () {
  18099. };
  18100. Action.prototype.getTriggerParameter = function () {
  18101. return this._triggerParameter;
  18102. };
  18103. Action.prototype._executeCurrent = function (evt) {
  18104. if (this._condition) {
  18105. var currentRenderId = this._actionManager.getScene().getRenderId();
  18106. if (this._condition._evaluationId === currentRenderId) {
  18107. if (!this._condition._currentResult) {
  18108. return;
  18109. }
  18110. } else {
  18111. this._condition._evaluationId = currentRenderId;
  18112. if (!this._condition.isValid()) {
  18113. this._condition._currentResult = false;
  18114. return;
  18115. }
  18116. this._condition._currentResult = true;
  18117. }
  18118. }
  18119. this._nextActiveAction.execute(evt);
  18120. if (this._nextActiveAction._child) {
  18121. this._nextActiveAction = this._nextActiveAction._child;
  18122. } else {
  18123. this._nextActiveAction = this;
  18124. }
  18125. };
  18126. Action.prototype.execute = function (evt) {
  18127. };
  18128. Action.prototype.then = function (action) {
  18129. this._child = action;
  18130. action._actionManager = this._actionManager;
  18131. action._prepare();
  18132. return action;
  18133. };
  18134. Action.prototype._getProperty = function (propertyPath) {
  18135. return this._actionManager._getProperty(propertyPath);
  18136. };
  18137. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18138. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18139. };
  18140. return Action;
  18141. })();
  18142. BABYLON.Action = Action;
  18143. })(BABYLON || (BABYLON = {}));
  18144. var BABYLON;
  18145. (function (BABYLON) {
  18146. var ActionEvent = (function () {
  18147. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18148. this.source = source;
  18149. this.pointerX = pointerX;
  18150. this.pointerY = pointerY;
  18151. this.meshUnderPointer = meshUnderPointer;
  18152. this.sourceEvent = sourceEvent;
  18153. }
  18154. ActionEvent.CreateNew = function (source) {
  18155. var scene = source.getScene();
  18156. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18157. };
  18158. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18159. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18160. };
  18161. return ActionEvent;
  18162. })();
  18163. BABYLON.ActionEvent = ActionEvent;
  18164. var ActionManager = (function () {
  18165. function ActionManager(scene) {
  18166. this.actions = new Array();
  18167. this._scene = scene;
  18168. scene._actionManagers.push(this);
  18169. }
  18170. Object.defineProperty(ActionManager, "NothingTrigger", {
  18171. get: function () {
  18172. return ActionManager._NothingTrigger;
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18178. get: function () {
  18179. return ActionManager._OnPickTrigger;
  18180. },
  18181. enumerable: true,
  18182. configurable: true
  18183. });
  18184. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18185. get: function () {
  18186. return ActionManager._OnLeftPickTrigger;
  18187. },
  18188. enumerable: true,
  18189. configurable: true
  18190. });
  18191. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18192. get: function () {
  18193. return ActionManager._OnRightPickTrigger;
  18194. },
  18195. enumerable: true,
  18196. configurable: true
  18197. });
  18198. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18199. get: function () {
  18200. return ActionManager._OnCenterPickTrigger;
  18201. },
  18202. enumerable: true,
  18203. configurable: true
  18204. });
  18205. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18206. get: function () {
  18207. return ActionManager._OnPointerOverTrigger;
  18208. },
  18209. enumerable: true,
  18210. configurable: true
  18211. });
  18212. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18213. get: function () {
  18214. return ActionManager._OnPointerOutTrigger;
  18215. },
  18216. enumerable: true,
  18217. configurable: true
  18218. });
  18219. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18220. get: function () {
  18221. return ActionManager._OnEveryFrameTrigger;
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18227. get: function () {
  18228. return ActionManager._OnIntersectionEnterTrigger;
  18229. },
  18230. enumerable: true,
  18231. configurable: true
  18232. });
  18233. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18234. get: function () {
  18235. return ActionManager._OnIntersectionExitTrigger;
  18236. },
  18237. enumerable: true,
  18238. configurable: true
  18239. });
  18240. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18241. get: function () {
  18242. return ActionManager._OnKeyDownTrigger;
  18243. },
  18244. enumerable: true,
  18245. configurable: true
  18246. });
  18247. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18248. get: function () {
  18249. return ActionManager._OnKeyUpTrigger;
  18250. },
  18251. enumerable: true,
  18252. configurable: true
  18253. });
  18254. ActionManager.prototype.dispose = function () {
  18255. var index = this._scene._actionManagers.indexOf(this);
  18256. if (index > -1) {
  18257. this._scene._actionManagers.splice(index, 1);
  18258. }
  18259. };
  18260. ActionManager.prototype.getScene = function () {
  18261. return this._scene;
  18262. };
  18263. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18264. for (var index = 0; index < this.actions.length; index++) {
  18265. var action = this.actions[index];
  18266. if (triggers.indexOf(action.trigger) > -1) {
  18267. return true;
  18268. }
  18269. }
  18270. return false;
  18271. };
  18272. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18273. get: function () {
  18274. for (var index = 0; index < this.actions.length; index++) {
  18275. var action = this.actions[index];
  18276. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18277. return true;
  18278. }
  18279. }
  18280. return false;
  18281. },
  18282. enumerable: true,
  18283. configurable: true
  18284. });
  18285. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18286. get: function () {
  18287. for (var index = 0; index < this.actions.length; index++) {
  18288. var action = this.actions[index];
  18289. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18290. return true;
  18291. }
  18292. }
  18293. return false;
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. ActionManager.prototype.registerAction = function (action) {
  18299. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18300. if (this.getScene().actionManager !== this) {
  18301. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18302. return null;
  18303. }
  18304. }
  18305. this.actions.push(action);
  18306. action._actionManager = this;
  18307. action._prepare();
  18308. return action;
  18309. };
  18310. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18311. for (var index = 0; index < this.actions.length; index++) {
  18312. var action = this.actions[index];
  18313. if (action.trigger === trigger) {
  18314. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18315. var parameter = action.getTriggerParameter();
  18316. if (parameter) {
  18317. if (evt.sourceEvent.key !== parameter) {
  18318. continue;
  18319. }
  18320. }
  18321. }
  18322. action._executeCurrent(evt);
  18323. }
  18324. }
  18325. };
  18326. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18327. var properties = propertyPath.split(".");
  18328. for (var index = 0; index < properties.length - 1; index++) {
  18329. target = target[properties[index]];
  18330. }
  18331. return target;
  18332. };
  18333. ActionManager.prototype._getProperty = function (propertyPath) {
  18334. var properties = propertyPath.split(".");
  18335. return properties[properties.length - 1];
  18336. };
  18337. ActionManager._NothingTrigger = 0;
  18338. ActionManager._OnPickTrigger = 1;
  18339. ActionManager._OnLeftPickTrigger = 2;
  18340. ActionManager._OnRightPickTrigger = 3;
  18341. ActionManager._OnCenterPickTrigger = 4;
  18342. ActionManager._OnPointerOverTrigger = 5;
  18343. ActionManager._OnPointerOutTrigger = 6;
  18344. ActionManager._OnEveryFrameTrigger = 7;
  18345. ActionManager._OnIntersectionEnterTrigger = 8;
  18346. ActionManager._OnIntersectionExitTrigger = 9;
  18347. ActionManager._OnKeyDownTrigger = 10;
  18348. ActionManager._OnKeyUpTrigger = 11;
  18349. return ActionManager;
  18350. })();
  18351. BABYLON.ActionManager = ActionManager;
  18352. })(BABYLON || (BABYLON = {}));
  18353. var __extends = this.__extends || function (d, b) {
  18354. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18355. function __() { this.constructor = d; }
  18356. __.prototype = b.prototype;
  18357. d.prototype = new __();
  18358. };
  18359. var BABYLON;
  18360. (function (BABYLON) {
  18361. var InterpolateValueAction = (function (_super) {
  18362. __extends(InterpolateValueAction, _super);
  18363. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18364. if (typeof duration === "undefined") { duration = 1000; }
  18365. _super.call(this, triggerOptions, condition);
  18366. this.propertyPath = propertyPath;
  18367. this.value = value;
  18368. this.duration = duration;
  18369. this.stopOtherAnimations = stopOtherAnimations;
  18370. this._target = target;
  18371. }
  18372. InterpolateValueAction.prototype._prepare = function () {
  18373. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18374. this._property = this._getProperty(this.propertyPath);
  18375. };
  18376. InterpolateValueAction.prototype.execute = function () {
  18377. var scene = this._actionManager.getScene();
  18378. var keys = [
  18379. {
  18380. frame: 0,
  18381. value: this._target[this._property]
  18382. }, {
  18383. frame: 100,
  18384. value: this.value
  18385. }
  18386. ];
  18387. var dataType;
  18388. if (typeof this.value === "number") {
  18389. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18390. } else if (this.value instanceof BABYLON.Color3) {
  18391. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18392. } else if (this.value instanceof BABYLON.Vector3) {
  18393. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18394. } else if (this.value instanceof BABYLON.Matrix) {
  18395. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18396. } else if (this.value instanceof BABYLON.Quaternion) {
  18397. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18398. } else {
  18399. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18400. return;
  18401. }
  18402. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18403. animation.setKeys(keys);
  18404. if (this.stopOtherAnimations) {
  18405. scene.stopAnimation(this._target);
  18406. }
  18407. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18408. };
  18409. return InterpolateValueAction;
  18410. })(BABYLON.Action);
  18411. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18412. })(BABYLON || (BABYLON = {}));
  18413. var __extends = this.__extends || function (d, b) {
  18414. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18415. function __() { this.constructor = d; }
  18416. __.prototype = b.prototype;
  18417. d.prototype = new __();
  18418. };
  18419. var BABYLON;
  18420. (function (BABYLON) {
  18421. var SwitchBooleanAction = (function (_super) {
  18422. __extends(SwitchBooleanAction, _super);
  18423. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18424. _super.call(this, triggerOptions, condition);
  18425. this.propertyPath = propertyPath;
  18426. this._target = target;
  18427. }
  18428. SwitchBooleanAction.prototype._prepare = function () {
  18429. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18430. this._property = this._getProperty(this.propertyPath);
  18431. };
  18432. SwitchBooleanAction.prototype.execute = function () {
  18433. this._target[this._property] = !this._target[this._property];
  18434. };
  18435. return SwitchBooleanAction;
  18436. })(BABYLON.Action);
  18437. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18438. var SetStateAction = (function (_super) {
  18439. __extends(SetStateAction, _super);
  18440. function SetStateAction(triggerOptions, target, value, condition) {
  18441. _super.call(this, triggerOptions, condition);
  18442. this.value = value;
  18443. this._target = target;
  18444. }
  18445. SetStateAction.prototype.execute = function () {
  18446. this._target.state = this.value;
  18447. };
  18448. return SetStateAction;
  18449. })(BABYLON.Action);
  18450. BABYLON.SetStateAction = SetStateAction;
  18451. var SetValueAction = (function (_super) {
  18452. __extends(SetValueAction, _super);
  18453. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18454. _super.call(this, triggerOptions, condition);
  18455. this.propertyPath = propertyPath;
  18456. this.value = value;
  18457. this._target = target;
  18458. }
  18459. SetValueAction.prototype._prepare = function () {
  18460. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18461. this._property = this._getProperty(this.propertyPath);
  18462. };
  18463. SetValueAction.prototype.execute = function () {
  18464. this._target[this._property] = this.value;
  18465. };
  18466. return SetValueAction;
  18467. })(BABYLON.Action);
  18468. BABYLON.SetValueAction = SetValueAction;
  18469. var IncrementValueAction = (function (_super) {
  18470. __extends(IncrementValueAction, _super);
  18471. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18472. _super.call(this, triggerOptions, condition);
  18473. this.propertyPath = propertyPath;
  18474. this.value = value;
  18475. this._target = target;
  18476. }
  18477. IncrementValueAction.prototype._prepare = function () {
  18478. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18479. this._property = this._getProperty(this.propertyPath);
  18480. if (typeof this._target[this._property] !== "number") {
  18481. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18482. }
  18483. };
  18484. IncrementValueAction.prototype.execute = function () {
  18485. this._target[this._property] += this.value;
  18486. };
  18487. return IncrementValueAction;
  18488. })(BABYLON.Action);
  18489. BABYLON.IncrementValueAction = IncrementValueAction;
  18490. var PlayAnimationAction = (function (_super) {
  18491. __extends(PlayAnimationAction, _super);
  18492. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18493. _super.call(this, triggerOptions, condition);
  18494. this.from = from;
  18495. this.to = to;
  18496. this.loop = loop;
  18497. this._target = target;
  18498. }
  18499. PlayAnimationAction.prototype._prepare = function () {
  18500. };
  18501. PlayAnimationAction.prototype.execute = function () {
  18502. var scene = this._actionManager.getScene();
  18503. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18504. };
  18505. return PlayAnimationAction;
  18506. })(BABYLON.Action);
  18507. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18508. var StopAnimationAction = (function (_super) {
  18509. __extends(StopAnimationAction, _super);
  18510. function StopAnimationAction(triggerOptions, target, condition) {
  18511. _super.call(this, triggerOptions, condition);
  18512. this._target = target;
  18513. }
  18514. StopAnimationAction.prototype._prepare = function () {
  18515. };
  18516. StopAnimationAction.prototype.execute = function () {
  18517. var scene = this._actionManager.getScene();
  18518. scene.stopAnimation(this._target);
  18519. };
  18520. return StopAnimationAction;
  18521. })(BABYLON.Action);
  18522. BABYLON.StopAnimationAction = StopAnimationAction;
  18523. var DoNothingAction = (function (_super) {
  18524. __extends(DoNothingAction, _super);
  18525. function DoNothingAction(triggerOptions, condition) {
  18526. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18527. _super.call(this, triggerOptions, condition);
  18528. }
  18529. DoNothingAction.prototype.execute = function () {
  18530. };
  18531. return DoNothingAction;
  18532. })(BABYLON.Action);
  18533. BABYLON.DoNothingAction = DoNothingAction;
  18534. var CombineAction = (function (_super) {
  18535. __extends(CombineAction, _super);
  18536. function CombineAction(triggerOptions, children, condition) {
  18537. _super.call(this, triggerOptions, condition);
  18538. this.children = children;
  18539. }
  18540. CombineAction.prototype._prepare = function () {
  18541. for (var index = 0; index < this.children.length; index++) {
  18542. this.children[index]._actionManager = this._actionManager;
  18543. this.children[index]._prepare();
  18544. }
  18545. };
  18546. CombineAction.prototype.execute = function (evt) {
  18547. for (var index = 0; index < this.children.length; index++) {
  18548. this.children[index].execute(evt);
  18549. }
  18550. };
  18551. return CombineAction;
  18552. })(BABYLON.Action);
  18553. BABYLON.CombineAction = CombineAction;
  18554. var ExecuteCodeAction = (function (_super) {
  18555. __extends(ExecuteCodeAction, _super);
  18556. function ExecuteCodeAction(triggerOptions, func, condition) {
  18557. _super.call(this, triggerOptions, condition);
  18558. this.func = func;
  18559. }
  18560. ExecuteCodeAction.prototype.execute = function (evt) {
  18561. this.func(evt);
  18562. };
  18563. return ExecuteCodeAction;
  18564. })(BABYLON.Action);
  18565. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18566. var SetParentAction = (function (_super) {
  18567. __extends(SetParentAction, _super);
  18568. function SetParentAction(triggerOptions, target, parent, condition) {
  18569. _super.call(this, triggerOptions, condition);
  18570. this._target = target;
  18571. this._parent = parent;
  18572. }
  18573. SetParentAction.prototype._prepare = function () {
  18574. };
  18575. SetParentAction.prototype.execute = function () {
  18576. if (this._target.parent === this._parent) {
  18577. return;
  18578. }
  18579. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18580. invertParentWorldMatrix.invert();
  18581. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18582. this._target.parent = this._parent;
  18583. };
  18584. return SetParentAction;
  18585. })(BABYLON.Action);
  18586. BABYLON.SetParentAction = SetParentAction;
  18587. })(BABYLON || (BABYLON = {}));
  18588. var __extends = this.__extends || function (d, b) {
  18589. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18590. function __() { this.constructor = d; }
  18591. __.prototype = b.prototype;
  18592. d.prototype = new __();
  18593. };
  18594. var BABYLON;
  18595. (function (BABYLON) {
  18596. var Geometry = (function () {
  18597. function Geometry(id, scene, vertexData, updatable, mesh) {
  18598. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18599. this._totalVertices = 0;
  18600. this._indices = [];
  18601. this.id = id;
  18602. this._engine = scene.getEngine();
  18603. this._meshes = [];
  18604. this._scene = scene;
  18605. if (vertexData) {
  18606. this.setAllVerticesData(vertexData, updatable);
  18607. } else {
  18608. this._totalVertices = 0;
  18609. this._indices = [];
  18610. }
  18611. if (mesh) {
  18612. this.applyToMesh(mesh);
  18613. }
  18614. }
  18615. Geometry.prototype.getScene = function () {
  18616. return this._scene;
  18617. };
  18618. Geometry.prototype.getEngine = function () {
  18619. return this._engine;
  18620. };
  18621. Geometry.prototype.isReady = function () {
  18622. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18623. };
  18624. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18625. vertexData.applyToGeometry(this, updatable);
  18626. };
  18627. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18628. this._vertexBuffers = this._vertexBuffers || {};
  18629. if (this._vertexBuffers[kind]) {
  18630. this._vertexBuffers[kind].dispose();
  18631. }
  18632. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18633. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18634. var stride = this._vertexBuffers[kind].getStrideSize();
  18635. this._totalVertices = data.length / stride;
  18636. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18637. var meshes = this._meshes;
  18638. var numOfMeshes = meshes.length;
  18639. for (var index = 0; index < numOfMeshes; index++) {
  18640. var mesh = meshes[index];
  18641. mesh._resetPointsArrayCache();
  18642. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18643. mesh._createGlobalSubMesh();
  18644. mesh.computeWorldMatrix(true);
  18645. }
  18646. }
  18647. };
  18648. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18649. var vertexBuffer = this.getVertexBuffer(kind);
  18650. if (!vertexBuffer) {
  18651. return;
  18652. }
  18653. vertexBuffer.update(data);
  18654. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18655. var extend;
  18656. if (updateExtends) {
  18657. var stride = vertexBuffer.getStrideSize();
  18658. this._totalVertices = data.length / stride;
  18659. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18660. }
  18661. var meshes = this._meshes;
  18662. var numOfMeshes = meshes.length;
  18663. for (var index = 0; index < numOfMeshes; index++) {
  18664. var mesh = meshes[index];
  18665. mesh._resetPointsArrayCache();
  18666. if (updateExtends) {
  18667. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18668. }
  18669. }
  18670. }
  18671. };
  18672. Geometry.prototype.getTotalVertices = function () {
  18673. if (!this.isReady()) {
  18674. return 0;
  18675. }
  18676. return this._totalVertices;
  18677. };
  18678. Geometry.prototype.getVerticesData = function (kind) {
  18679. var vertexBuffer = this.getVertexBuffer(kind);
  18680. if (!vertexBuffer) {
  18681. return null;
  18682. }
  18683. return vertexBuffer.getData();
  18684. };
  18685. Geometry.prototype.getVertexBuffer = function (kind) {
  18686. if (!this.isReady()) {
  18687. return null;
  18688. }
  18689. return this._vertexBuffers[kind];
  18690. };
  18691. Geometry.prototype.getVertexBuffers = function () {
  18692. if (!this.isReady()) {
  18693. return null;
  18694. }
  18695. return this._vertexBuffers;
  18696. };
  18697. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18698. if (!this._vertexBuffers) {
  18699. if (this._delayInfo) {
  18700. return this._delayInfo.indexOf(kind) !== -1;
  18701. }
  18702. return false;
  18703. }
  18704. return this._vertexBuffers[kind] !== undefined;
  18705. };
  18706. Geometry.prototype.getVerticesDataKinds = function () {
  18707. var result = [];
  18708. if (!this._vertexBuffers && this._delayInfo) {
  18709. for (var kind in this._delayInfo) {
  18710. result.push(kind);
  18711. }
  18712. } else {
  18713. for (kind in this._vertexBuffers) {
  18714. result.push(kind);
  18715. }
  18716. }
  18717. return result;
  18718. };
  18719. Geometry.prototype.setIndices = function (indices) {
  18720. if (this._indexBuffer) {
  18721. this._engine._releaseBuffer(this._indexBuffer);
  18722. }
  18723. this._indices = indices;
  18724. if (this._meshes.length !== 0 && this._indices) {
  18725. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18726. }
  18727. var meshes = this._meshes;
  18728. var numOfMeshes = meshes.length;
  18729. for (var index = 0; index < numOfMeshes; index++) {
  18730. meshes[index]._createGlobalSubMesh();
  18731. }
  18732. };
  18733. Geometry.prototype.getTotalIndices = function () {
  18734. if (!this.isReady()) {
  18735. return 0;
  18736. }
  18737. return this._indices.length;
  18738. };
  18739. Geometry.prototype.getIndices = function () {
  18740. if (!this.isReady()) {
  18741. return null;
  18742. }
  18743. return this._indices;
  18744. };
  18745. Geometry.prototype.getIndexBuffer = function () {
  18746. if (!this.isReady()) {
  18747. return null;
  18748. }
  18749. return this._indexBuffer;
  18750. };
  18751. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18752. var meshes = this._meshes;
  18753. var index = meshes.indexOf(mesh);
  18754. if (index === -1) {
  18755. return;
  18756. }
  18757. for (var kind in this._vertexBuffers) {
  18758. this._vertexBuffers[kind].dispose();
  18759. }
  18760. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18761. this._indexBuffer = null;
  18762. }
  18763. meshes.splice(index, 1);
  18764. mesh._geometry = null;
  18765. if (meshes.length == 0 && shouldDispose) {
  18766. this.dispose();
  18767. }
  18768. };
  18769. Geometry.prototype.applyToMesh = function (mesh) {
  18770. if (mesh._geometry === this) {
  18771. return;
  18772. }
  18773. var previousGeometry = mesh._geometry;
  18774. if (previousGeometry) {
  18775. previousGeometry.releaseForMesh(mesh);
  18776. }
  18777. var meshes = this._meshes;
  18778. mesh._geometry = this;
  18779. this._scene.pushGeometry(this);
  18780. meshes.push(mesh);
  18781. if (this.isReady()) {
  18782. this._applyToMesh(mesh);
  18783. } else {
  18784. mesh._boundingInfo = this._boundingInfo;
  18785. }
  18786. };
  18787. Geometry.prototype._applyToMesh = function (mesh) {
  18788. var numOfMeshes = this._meshes.length;
  18789. for (var kind in this._vertexBuffers) {
  18790. if (numOfMeshes === 1) {
  18791. this._vertexBuffers[kind].create();
  18792. }
  18793. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18794. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18795. mesh._resetPointsArrayCache();
  18796. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18797. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18798. mesh._createGlobalSubMesh();
  18799. }
  18800. }
  18801. if (numOfMeshes === 1 && this._indices) {
  18802. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18803. }
  18804. if (this._indexBuffer) {
  18805. this._indexBuffer.references = numOfMeshes;
  18806. }
  18807. };
  18808. Geometry.prototype.load = function (scene, onLoaded) {
  18809. var _this = this;
  18810. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18811. return;
  18812. }
  18813. if (this.isReady()) {
  18814. if (onLoaded) {
  18815. onLoaded();
  18816. }
  18817. return;
  18818. }
  18819. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18820. scene._addPendingData(this);
  18821. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18822. _this._delayLoadingFunction(JSON.parse(data), _this);
  18823. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18824. _this._delayInfo = [];
  18825. scene._removePendingData(_this);
  18826. var meshes = _this._meshes;
  18827. var numOfMeshes = meshes.length;
  18828. for (var index = 0; index < numOfMeshes; index++) {
  18829. _this._applyToMesh(meshes[index]);
  18830. }
  18831. if (onLoaded) {
  18832. onLoaded();
  18833. }
  18834. }, function () {
  18835. }, scene.database);
  18836. };
  18837. Geometry.prototype.dispose = function () {
  18838. var meshes = this._meshes;
  18839. var numOfMeshes = meshes.length;
  18840. for (var index = 0; index < numOfMeshes; index++) {
  18841. this.releaseForMesh(meshes[index]);
  18842. }
  18843. this._meshes = [];
  18844. for (var kind in this._vertexBuffers) {
  18845. this._vertexBuffers[kind].dispose();
  18846. }
  18847. this._vertexBuffers = [];
  18848. this._totalVertices = 0;
  18849. if (this._indexBuffer) {
  18850. this._engine._releaseBuffer(this._indexBuffer);
  18851. }
  18852. this._indexBuffer = null;
  18853. this._indices = [];
  18854. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18855. this.delayLoadingFile = null;
  18856. this._delayLoadingFunction = null;
  18857. this._delayInfo = [];
  18858. this._boundingInfo = null;
  18859. var geometries = this._scene.getGeometries();
  18860. index = geometries.indexOf(this);
  18861. if (index > -1) {
  18862. geometries.splice(index, 1);
  18863. }
  18864. };
  18865. Geometry.prototype.copy = function (id) {
  18866. var vertexData = new BABYLON.VertexData();
  18867. vertexData.indices = [];
  18868. var indices = this.getIndices();
  18869. for (var index = 0; index < indices.length; index++) {
  18870. vertexData.indices.push(indices[index]);
  18871. }
  18872. var updatable = false;
  18873. var stopChecking = false;
  18874. for (var kind in this._vertexBuffers) {
  18875. vertexData.set(this.getVerticesData(kind), kind);
  18876. if (!stopChecking) {
  18877. updatable = this.getVertexBuffer(kind).isUpdatable();
  18878. stopChecking = !updatable;
  18879. }
  18880. }
  18881. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  18882. geometry.delayLoadState = this.delayLoadState;
  18883. geometry.delayLoadingFile = this.delayLoadingFile;
  18884. geometry._delayLoadingFunction = this._delayLoadingFunction;
  18885. for (kind in this._delayInfo) {
  18886. geometry._delayInfo = geometry._delayInfo || [];
  18887. geometry._delayInfo.push(kind);
  18888. }
  18889. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  18890. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18891. return geometry;
  18892. };
  18893. Geometry.ExtractFromMesh = function (mesh, id) {
  18894. var geometry = mesh._geometry;
  18895. if (!geometry) {
  18896. return null;
  18897. }
  18898. return geometry.copy(id);
  18899. };
  18900. Geometry.RandomId = function () {
  18901. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  18902. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  18903. return v.toString(16);
  18904. });
  18905. };
  18906. return Geometry;
  18907. })();
  18908. BABYLON.Geometry = Geometry;
  18909. (function (Geometry) {
  18910. (function (Primitives) {
  18911. var _Primitive = (function (_super) {
  18912. __extends(_Primitive, _super);
  18913. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  18914. this._beingRegenerated = true;
  18915. this._canBeRegenerated = canBeRegenerated;
  18916. _super.call(this, id, scene, vertexData, false, mesh);
  18917. this._beingRegenerated = false;
  18918. }
  18919. _Primitive.prototype.canBeRegenerated = function () {
  18920. return this._canBeRegenerated;
  18921. };
  18922. _Primitive.prototype.regenerate = function () {
  18923. if (!this._canBeRegenerated) {
  18924. return;
  18925. }
  18926. this._beingRegenerated = true;
  18927. this.setAllVerticesData(this._regenerateVertexData(), false);
  18928. this._beingRegenerated = false;
  18929. };
  18930. _Primitive.prototype.asNewGeometry = function (id) {
  18931. return _super.prototype.copy.call(this, id);
  18932. };
  18933. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  18934. if (!this._beingRegenerated) {
  18935. return;
  18936. }
  18937. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  18938. };
  18939. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  18940. if (!this._beingRegenerated) {
  18941. return;
  18942. }
  18943. _super.prototype.setVerticesData.call(this, kind, data, false);
  18944. };
  18945. _Primitive.prototype._regenerateVertexData = function () {
  18946. throw new Error("Abstract method");
  18947. };
  18948. _Primitive.prototype.copy = function (id) {
  18949. throw new Error("Must be overriden in sub-classes.");
  18950. };
  18951. return _Primitive;
  18952. })(Geometry);
  18953. Primitives._Primitive = _Primitive;
  18954. var Box = (function (_super) {
  18955. __extends(Box, _super);
  18956. function Box(id, scene, size, canBeRegenerated, mesh) {
  18957. this.size = size;
  18958. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18959. }
  18960. Box.prototype._regenerateVertexData = function () {
  18961. return BABYLON.VertexData.CreateBox(this.size);
  18962. };
  18963. Box.prototype.copy = function (id) {
  18964. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  18965. };
  18966. return Box;
  18967. })(_Primitive);
  18968. Primitives.Box = Box;
  18969. var Sphere = (function (_super) {
  18970. __extends(Sphere, _super);
  18971. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  18972. this.segments = segments;
  18973. this.diameter = diameter;
  18974. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18975. }
  18976. Sphere.prototype._regenerateVertexData = function () {
  18977. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  18978. };
  18979. Sphere.prototype.copy = function (id) {
  18980. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  18981. };
  18982. return Sphere;
  18983. })(_Primitive);
  18984. Primitives.Sphere = Sphere;
  18985. var Cylinder = (function (_super) {
  18986. __extends(Cylinder, _super);
  18987. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  18988. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  18989. this.height = height;
  18990. this.diameterTop = diameterTop;
  18991. this.diameterBottom = diameterBottom;
  18992. this.tessellation = tessellation;
  18993. this.subdivisions = subdivisions;
  18994. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18995. }
  18996. Cylinder.prototype._regenerateVertexData = function () {
  18997. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  18998. };
  18999. Cylinder.prototype.copy = function (id) {
  19000. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19001. };
  19002. return Cylinder;
  19003. })(_Primitive);
  19004. Primitives.Cylinder = Cylinder;
  19005. var Torus = (function (_super) {
  19006. __extends(Torus, _super);
  19007. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19008. this.diameter = diameter;
  19009. this.thickness = thickness;
  19010. this.tessellation = tessellation;
  19011. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19012. }
  19013. Torus.prototype._regenerateVertexData = function () {
  19014. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19015. };
  19016. Torus.prototype.copy = function (id) {
  19017. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19018. };
  19019. return Torus;
  19020. })(_Primitive);
  19021. Primitives.Torus = Torus;
  19022. var Ground = (function (_super) {
  19023. __extends(Ground, _super);
  19024. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19025. this.width = width;
  19026. this.height = height;
  19027. this.subdivisions = subdivisions;
  19028. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19029. }
  19030. Ground.prototype._regenerateVertexData = function () {
  19031. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19032. };
  19033. Ground.prototype.copy = function (id) {
  19034. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19035. };
  19036. return Ground;
  19037. })(_Primitive);
  19038. Primitives.Ground = Ground;
  19039. var TiledGround = (function (_super) {
  19040. __extends(TiledGround, _super);
  19041. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19042. this.xmin = xmin;
  19043. this.zmin = zmin;
  19044. this.xmax = xmax;
  19045. this.zmax = zmax;
  19046. this.subdivisions = subdivisions;
  19047. this.precision = precision;
  19048. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19049. }
  19050. TiledGround.prototype._regenerateVertexData = function () {
  19051. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19052. };
  19053. TiledGround.prototype.copy = function (id) {
  19054. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19055. };
  19056. return TiledGround;
  19057. })(_Primitive);
  19058. Primitives.TiledGround = TiledGround;
  19059. var Plane = (function (_super) {
  19060. __extends(Plane, _super);
  19061. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19062. this.size = size;
  19063. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19064. }
  19065. Plane.prototype._regenerateVertexData = function () {
  19066. return BABYLON.VertexData.CreatePlane(this.size);
  19067. };
  19068. Plane.prototype.copy = function (id) {
  19069. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19070. };
  19071. return Plane;
  19072. })(_Primitive);
  19073. Primitives.Plane = Plane;
  19074. var TorusKnot = (function (_super) {
  19075. __extends(TorusKnot, _super);
  19076. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19077. this.radius = radius;
  19078. this.tube = tube;
  19079. this.radialSegments = radialSegments;
  19080. this.tubularSegments = tubularSegments;
  19081. this.p = p;
  19082. this.q = q;
  19083. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19084. }
  19085. TorusKnot.prototype._regenerateVertexData = function () {
  19086. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19087. };
  19088. TorusKnot.prototype.copy = function (id) {
  19089. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19090. };
  19091. return TorusKnot;
  19092. })(_Primitive);
  19093. Primitives.TorusKnot = TorusKnot;
  19094. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19095. var Primitives = Geometry.Primitives;
  19096. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19097. var Geometry = BABYLON.Geometry;
  19098. })(BABYLON || (BABYLON = {}));
  19099. var __extends = this.__extends || function (d, b) {
  19100. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19101. function __() { this.constructor = d; }
  19102. __.prototype = b.prototype;
  19103. d.prototype = new __();
  19104. };
  19105. var BABYLON;
  19106. (function (BABYLON) {
  19107. var Gamepads = (function () {
  19108. function Gamepads(ongamedpadconnected) {
  19109. var _this = this;
  19110. this.babylonGamepads = [];
  19111. this.oneGamepadConnected = false;
  19112. this.isMonitoring = false;
  19113. this.gamepadEventSupported = 'GamepadEvent' in window;
  19114. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19115. 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=";
  19116. this._callbackGamepadConnected = ongamedpadconnected;
  19117. if (this.gamepadSupportAvailable) {
  19118. if (this.gamepadEventSupported) {
  19119. window.addEventListener('gamepadconnected', function (evt) {
  19120. _this._onGamepadConnected(evt);
  19121. }, false);
  19122. window.addEventListener('gamepaddisconnected', function (evt) {
  19123. _this._onGamepadDisconnected(evt);
  19124. }, false);
  19125. } else {
  19126. this._startMonitoringGamepads();
  19127. }
  19128. if (!this.oneGamepadConnected) {
  19129. this._insertGamepadDOMInstructions();
  19130. }
  19131. } else {
  19132. this._insertGamepadDOMNotSupported();
  19133. }
  19134. }
  19135. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19136. Gamepads.gamepadDOMInfo = document.createElement("div");
  19137. var buttonAImage = document.createElement("img");
  19138. buttonAImage.src = this.buttonADataURL;
  19139. var spanMessage = document.createElement("span");
  19140. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19141. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19142. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19143. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19144. Gamepads.gamepadDOMInfo.style.width = "100%";
  19145. Gamepads.gamepadDOMInfo.style.height = "48px";
  19146. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19147. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19148. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19149. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19150. buttonAImage.style.position = "relative";
  19151. buttonAImage.style.bottom = "8px";
  19152. spanMessage.style.position = "relative";
  19153. spanMessage.style.fontSize = "32px";
  19154. spanMessage.style.bottom = "32px";
  19155. spanMessage.style.color = "green";
  19156. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19157. };
  19158. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19159. Gamepads.gamepadDOMInfo = document.createElement("div");
  19160. var spanMessage = document.createElement("span");
  19161. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19162. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19163. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19164. Gamepads.gamepadDOMInfo.style.width = "100%";
  19165. Gamepads.gamepadDOMInfo.style.height = "40px";
  19166. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19167. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19168. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19169. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19170. spanMessage.style.position = "relative";
  19171. spanMessage.style.fontSize = "32px";
  19172. spanMessage.style.color = "red";
  19173. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19174. };
  19175. Gamepads.prototype.dispose = function () {
  19176. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19177. };
  19178. Gamepads.prototype._onGamepadConnected = function (evt) {
  19179. var newGamepad = this._addNewGamepad(evt.gamepad);
  19180. if (this._callbackGamepadConnected)
  19181. this._callbackGamepadConnected(newGamepad);
  19182. this._startMonitoringGamepads();
  19183. };
  19184. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19185. if (!this.oneGamepadConnected) {
  19186. this.oneGamepadConnected = true;
  19187. if (Gamepads.gamepadDOMInfo) {
  19188. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19189. Gamepads.gamepadDOMInfo = null;
  19190. }
  19191. }
  19192. var newGamepad;
  19193. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19194. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19195. } else {
  19196. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19197. }
  19198. this.babylonGamepads.push(newGamepad);
  19199. return newGamepad;
  19200. };
  19201. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19202. for (var i in this.babylonGamepads) {
  19203. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19204. this.babylonGamepads.splice(i, 1);
  19205. break;
  19206. }
  19207. }
  19208. if (this.babylonGamepads.length == 0) {
  19209. this._stopMonitoringGamepads();
  19210. }
  19211. };
  19212. Gamepads.prototype._startMonitoringGamepads = function () {
  19213. if (!this.isMonitoring) {
  19214. this.isMonitoring = true;
  19215. this._checkGamepadsStatus();
  19216. }
  19217. };
  19218. Gamepads.prototype._stopMonitoringGamepads = function () {
  19219. this.isMonitoring = false;
  19220. };
  19221. Gamepads.prototype._checkGamepadsStatus = function () {
  19222. var _this = this;
  19223. this._updateGamepadObjects();
  19224. for (var i in this.babylonGamepads) {
  19225. this.babylonGamepads[i].update();
  19226. }
  19227. if (this.isMonitoring) {
  19228. if (window.requestAnimationFrame) {
  19229. window.requestAnimationFrame(function () {
  19230. _this._checkGamepadsStatus();
  19231. });
  19232. } else if (window.mozRequestAnimationFrame) {
  19233. window.mozRequestAnimationFrame(function () {
  19234. _this._checkGamepadsStatus();
  19235. });
  19236. } else if (window.webkitRequestAnimationFrame) {
  19237. window.webkitRequestAnimationFrame(function () {
  19238. _this._checkGamepadsStatus();
  19239. });
  19240. }
  19241. }
  19242. };
  19243. Gamepads.prototype._updateGamepadObjects = function () {
  19244. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19245. for (var i = 0; i < gamepads.length; i++) {
  19246. if (gamepads[i]) {
  19247. if (!(gamepads[i].index in this.babylonGamepads)) {
  19248. var newGamepad = this._addNewGamepad(gamepads[i]);
  19249. if (this._callbackGamepadConnected) {
  19250. this._callbackGamepadConnected(newGamepad);
  19251. }
  19252. } else {
  19253. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19254. }
  19255. }
  19256. }
  19257. };
  19258. return Gamepads;
  19259. })();
  19260. BABYLON.Gamepads = Gamepads;
  19261. var StickValues = (function () {
  19262. function StickValues(x, y) {
  19263. this.x = x;
  19264. this.y = y;
  19265. }
  19266. return StickValues;
  19267. })();
  19268. BABYLON.StickValues = StickValues;
  19269. var Gamepad = (function () {
  19270. function Gamepad(id, index, browserGamepad) {
  19271. this.id = id;
  19272. this.index = index;
  19273. this.browserGamepad = browserGamepad;
  19274. if (this.browserGamepad.axes.length >= 2) {
  19275. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19276. }
  19277. if (this.browserGamepad.axes.length >= 4) {
  19278. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19279. }
  19280. }
  19281. Gamepad.prototype.onleftstickchanged = function (callback) {
  19282. this._onleftstickchanged = callback;
  19283. };
  19284. Gamepad.prototype.onrightstickchanged = function (callback) {
  19285. this._onrightstickchanged = callback;
  19286. };
  19287. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19288. get: function () {
  19289. return this._leftStick;
  19290. },
  19291. set: function (newValues) {
  19292. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19293. this._onleftstickchanged(newValues);
  19294. }
  19295. this._leftStick = newValues;
  19296. },
  19297. enumerable: true,
  19298. configurable: true
  19299. });
  19300. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19301. get: function () {
  19302. return this._rightStick;
  19303. },
  19304. set: function (newValues) {
  19305. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19306. this._onrightstickchanged(newValues);
  19307. }
  19308. this._rightStick = newValues;
  19309. },
  19310. enumerable: true,
  19311. configurable: true
  19312. });
  19313. Gamepad.prototype.update = function () {
  19314. if (this._leftStick) {
  19315. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19316. }
  19317. if (this._rightStick) {
  19318. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19319. }
  19320. };
  19321. return Gamepad;
  19322. })();
  19323. BABYLON.Gamepad = Gamepad;
  19324. var GenericPad = (function (_super) {
  19325. __extends(GenericPad, _super);
  19326. function GenericPad(id, index, gamepad) {
  19327. _super.call(this, id, index, gamepad);
  19328. this.id = id;
  19329. this.index = index;
  19330. this.gamepad = gamepad;
  19331. this._buttons = new Array(gamepad.buttons.length);
  19332. }
  19333. GenericPad.prototype.onbuttondown = function (callback) {
  19334. this._onbuttondown = callback;
  19335. };
  19336. GenericPad.prototype.onbuttonup = function (callback) {
  19337. this._onbuttonup = callback;
  19338. };
  19339. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19340. if (newValue !== currentValue) {
  19341. if (this._onbuttondown && newValue === 1) {
  19342. this._onbuttondown(buttonIndex);
  19343. }
  19344. if (this._onbuttonup && newValue === 0) {
  19345. this._onbuttonup(buttonIndex);
  19346. }
  19347. }
  19348. return newValue;
  19349. };
  19350. GenericPad.prototype.update = function () {
  19351. _super.prototype.update.call(this);
  19352. for (var index = 0; index < this._buttons.length; index++) {
  19353. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19354. }
  19355. };
  19356. return GenericPad;
  19357. })(Gamepad);
  19358. BABYLON.GenericPad = GenericPad;
  19359. (function (Xbox360Button) {
  19360. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19361. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19362. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19363. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19364. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19365. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19366. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19367. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19368. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19369. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19370. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19371. var Xbox360Button = BABYLON.Xbox360Button;
  19372. (function (Xbox360Dpad) {
  19373. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19374. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19375. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19376. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19377. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19378. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19379. var Xbox360Pad = (function (_super) {
  19380. __extends(Xbox360Pad, _super);
  19381. function Xbox360Pad() {
  19382. _super.apply(this, arguments);
  19383. this._leftTrigger = 0;
  19384. this._rightTrigger = 0;
  19385. this._buttonA = 0;
  19386. this._buttonB = 0;
  19387. this._buttonX = 0;
  19388. this._buttonY = 0;
  19389. this._buttonBack = 0;
  19390. this._buttonStart = 0;
  19391. this._buttonLB = 0;
  19392. this._buttonRB = 0;
  19393. this._buttonLeftStick = 0;
  19394. this._buttonRightStick = 0;
  19395. this._dPadUp = 0;
  19396. this._dPadDown = 0;
  19397. this._dPadLeft = 0;
  19398. this._dPadRight = 0;
  19399. }
  19400. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19401. this._onlefttriggerchanged = callback;
  19402. };
  19403. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19404. this._onrighttriggerchanged = callback;
  19405. };
  19406. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19407. get: function () {
  19408. return this._leftTrigger;
  19409. },
  19410. set: function (newValue) {
  19411. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19412. this._onlefttriggerchanged(newValue);
  19413. }
  19414. this._leftTrigger = newValue;
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19420. get: function () {
  19421. return this._rightTrigger;
  19422. },
  19423. set: function (newValue) {
  19424. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19425. this._onrighttriggerchanged(newValue);
  19426. }
  19427. this._rightTrigger = newValue;
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19433. this._onbuttondown = callback;
  19434. };
  19435. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19436. this._onbuttonup = callback;
  19437. };
  19438. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19439. this._ondpaddown = callback;
  19440. };
  19441. Xbox360Pad.prototype.ondpadup = function (callback) {
  19442. this._ondpadup = callback;
  19443. };
  19444. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19445. if (newValue !== currentValue) {
  19446. if (this._onbuttondown && newValue === 1) {
  19447. this._onbuttondown(buttonType);
  19448. }
  19449. if (this._onbuttonup && newValue === 0) {
  19450. this._onbuttonup(buttonType);
  19451. }
  19452. }
  19453. return newValue;
  19454. };
  19455. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19456. if (newValue !== currentValue) {
  19457. if (this._ondpaddown && newValue === 1) {
  19458. this._ondpaddown(buttonType);
  19459. }
  19460. if (this._ondpadup && newValue === 0) {
  19461. this._ondpadup(buttonType);
  19462. }
  19463. }
  19464. return newValue;
  19465. };
  19466. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19467. get: function () {
  19468. return this._buttonA;
  19469. },
  19470. set: function (value) {
  19471. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19477. get: function () {
  19478. return this._buttonB;
  19479. },
  19480. set: function (value) {
  19481. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19487. get: function () {
  19488. return this._buttonX;
  19489. },
  19490. set: function (value) {
  19491. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19497. get: function () {
  19498. return this._buttonY;
  19499. },
  19500. set: function (value) {
  19501. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19507. get: function () {
  19508. return this._buttonStart;
  19509. },
  19510. set: function (value) {
  19511. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19517. get: function () {
  19518. return this._buttonBack;
  19519. },
  19520. set: function (value) {
  19521. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19527. get: function () {
  19528. return this._buttonLB;
  19529. },
  19530. set: function (value) {
  19531. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19537. get: function () {
  19538. return this._buttonRB;
  19539. },
  19540. set: function (value) {
  19541. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19547. get: function () {
  19548. return this._buttonLeftStick;
  19549. },
  19550. set: function (value) {
  19551. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19557. get: function () {
  19558. return this._buttonRightStick;
  19559. },
  19560. set: function (value) {
  19561. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19567. get: function () {
  19568. return this._dPadUp;
  19569. },
  19570. set: function (value) {
  19571. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19577. get: function () {
  19578. return this._dPadDown;
  19579. },
  19580. set: function (value) {
  19581. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19587. get: function () {
  19588. return this._dPadLeft;
  19589. },
  19590. set: function (value) {
  19591. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19592. },
  19593. enumerable: true,
  19594. configurable: true
  19595. });
  19596. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19597. get: function () {
  19598. return this._dPadRight;
  19599. },
  19600. set: function (value) {
  19601. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19602. },
  19603. enumerable: true,
  19604. configurable: true
  19605. });
  19606. Xbox360Pad.prototype.update = function () {
  19607. _super.prototype.update.call(this);
  19608. this.buttonA = this.browserGamepad.buttons[0].value;
  19609. this.buttonB = this.browserGamepad.buttons[1].value;
  19610. this.buttonX = this.browserGamepad.buttons[2].value;
  19611. this.buttonY = this.browserGamepad.buttons[3].value;
  19612. this.buttonLB = this.browserGamepad.buttons[4].value;
  19613. this.buttonRB = this.browserGamepad.buttons[5].value;
  19614. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19615. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19616. this.buttonBack = this.browserGamepad.buttons[8].value;
  19617. this.buttonStart = this.browserGamepad.buttons[9].value;
  19618. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19619. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19620. this.dPadUp = this.browserGamepad.buttons[12].value;
  19621. this.dPadDown = this.browserGamepad.buttons[13].value;
  19622. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19623. this.dPadRight = this.browserGamepad.buttons[15].value;
  19624. };
  19625. return Xbox360Pad;
  19626. })(Gamepad);
  19627. BABYLON.Xbox360Pad = Xbox360Pad;
  19628. })(BABYLON || (BABYLON = {}));
  19629. var __extends = this.__extends || function (d, b) {
  19630. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19631. function __() { this.constructor = d; }
  19632. __.prototype = b.prototype;
  19633. d.prototype = new __();
  19634. };
  19635. var BABYLON;
  19636. (function (BABYLON) {
  19637. var GamepadCamera = (function (_super) {
  19638. __extends(GamepadCamera, _super);
  19639. function GamepadCamera(name, position, scene) {
  19640. var _this = this;
  19641. _super.call(this, name, position, scene);
  19642. this.angularSensibility = 200;
  19643. this.moveSensibility = 75;
  19644. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19645. _this._onNewGameConnected(gamepad);
  19646. });
  19647. }
  19648. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19649. if (gamepad.index === 0) {
  19650. this._gamepad = gamepad;
  19651. }
  19652. };
  19653. GamepadCamera.prototype._checkInputs = function () {
  19654. if (!this._gamepad) {
  19655. return;
  19656. }
  19657. var LSValues = this._gamepad.leftStick;
  19658. var normalizedLX = LSValues.x / this.moveSensibility;
  19659. var normalizedLY = LSValues.y / this.moveSensibility;
  19660. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19661. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19662. var RSValues = this._gamepad.rightStick;
  19663. var normalizedRX = RSValues.x / this.angularSensibility;
  19664. var normalizedRY = RSValues.y / this.angularSensibility;
  19665. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19666. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19667. ;
  19668. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19669. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19670. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19671. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19672. };
  19673. GamepadCamera.prototype.dispose = function () {
  19674. this._gamepads.dispose();
  19675. _super.prototype.dispose.call(this);
  19676. };
  19677. return GamepadCamera;
  19678. })(BABYLON.FreeCamera);
  19679. BABYLON.GamepadCamera = GamepadCamera;
  19680. })(BABYLON || (BABYLON = {}));
  19681. var __extends = this.__extends || function (d, b) {
  19682. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19683. function __() { this.constructor = d; }
  19684. __.prototype = b.prototype;
  19685. d.prototype = new __();
  19686. };
  19687. var BABYLON;
  19688. (function (BABYLON) {
  19689. var LinesMesh = (function (_super) {
  19690. __extends(LinesMesh, _super);
  19691. function LinesMesh(name, scene, updatable) {
  19692. if (typeof updatable === "undefined") { updatable = false; }
  19693. _super.call(this, name, scene);
  19694. this.color = new BABYLON.Color3(1, 1, 1);
  19695. this.alpha = 1;
  19696. this._indices = new Array();
  19697. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19698. attributes: ["position"],
  19699. uniforms: ["worldViewProjection", "color"],
  19700. needAlphaBlending: true
  19701. });
  19702. }
  19703. Object.defineProperty(LinesMesh.prototype, "material", {
  19704. get: function () {
  19705. return this._colorShader;
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19711. get: function () {
  19712. return false;
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19718. get: function () {
  19719. return false;
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19725. var engine = this.getScene().getEngine();
  19726. var indexToBind = this._geometry.getIndexBuffer();
  19727. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19728. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19729. };
  19730. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19731. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19732. return;
  19733. }
  19734. var engine = this.getScene().getEngine();
  19735. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19736. };
  19737. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19738. return null;
  19739. };
  19740. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19741. this._colorShader.dispose();
  19742. _super.prototype.dispose.call(this, doNotRecurse);
  19743. };
  19744. return LinesMesh;
  19745. })(BABYLON.Mesh);
  19746. BABYLON.LinesMesh = LinesMesh;
  19747. })(BABYLON || (BABYLON = {}));
  19748. var BABYLON;
  19749. (function (BABYLON) {
  19750. var OutlineRenderer = (function () {
  19751. function OutlineRenderer(scene) {
  19752. this._scene = scene;
  19753. }
  19754. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19755. var scene = this._scene;
  19756. var engine = this._scene.getEngine();
  19757. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19758. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19759. return;
  19760. }
  19761. var mesh = subMesh.getRenderingMesh();
  19762. var material = subMesh.getMaterial();
  19763. engine.enableEffect(this._effect);
  19764. this._effect.setFloat("offset", mesh.outlineWidth);
  19765. this._effect.setColor3("color", mesh.outlineColor);
  19766. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19767. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19768. if (useBones) {
  19769. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19770. }
  19771. mesh._bind(subMesh, this._effect, false);
  19772. if (material && material.needAlphaTesting()) {
  19773. var alphaTexture = material.getAlphaTestTexture();
  19774. this._effect.setTexture("diffuseSampler", alphaTexture);
  19775. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19776. }
  19777. if (hardwareInstancedRendering) {
  19778. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19779. } else {
  19780. if (batch.renderSelf[subMesh._id]) {
  19781. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19782. mesh._draw(subMesh, true);
  19783. }
  19784. if (batch.visibleInstances[subMesh._id]) {
  19785. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19786. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19787. this._effect.setMatrix("world", instance.getWorldMatrix());
  19788. mesh._draw(subMesh, true);
  19789. }
  19790. }
  19791. }
  19792. };
  19793. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19794. var defines = [];
  19795. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19796. var mesh = subMesh.getMesh();
  19797. var material = subMesh.getMaterial();
  19798. if (material && material.needAlphaTesting()) {
  19799. defines.push("#define ALPHATEST");
  19800. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19801. attribs.push(BABYLON.VertexBuffer.UVKind);
  19802. defines.push("#define UV1");
  19803. }
  19804. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19805. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19806. defines.push("#define UV2");
  19807. }
  19808. }
  19809. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19812. defines.push("#define BONES");
  19813. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19814. }
  19815. if (useInstances) {
  19816. defines.push("#define INSTANCES");
  19817. attribs.push("world0");
  19818. attribs.push("world1");
  19819. attribs.push("world2");
  19820. attribs.push("world3");
  19821. }
  19822. var join = defines.join("\n");
  19823. if (this._cachedDefines != join) {
  19824. this._cachedDefines = join;
  19825. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  19826. }
  19827. return this._effect.isReady();
  19828. };
  19829. return OutlineRenderer;
  19830. })();
  19831. BABYLON.OutlineRenderer = OutlineRenderer;
  19832. })(BABYLON || (BABYLON = {}));
  19833. var BABYLON;
  19834. (function (BABYLON) {
  19835. var MeshAssetTask = (function () {
  19836. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  19837. this.name = name;
  19838. this.meshesNames = meshesNames;
  19839. this.rootUrl = rootUrl;
  19840. this.sceneFilename = sceneFilename;
  19841. this.isCompleted = false;
  19842. }
  19843. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19844. var _this = this;
  19845. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  19846. _this.loadedMeshes = meshes;
  19847. _this.loadedParticleSystems = particleSystems;
  19848. _this.loadedSkeletons = skeletons;
  19849. _this.isCompleted = true;
  19850. if (_this.onSuccess) {
  19851. _this.onSuccess(_this);
  19852. }
  19853. onSuccess();
  19854. }, null, function () {
  19855. if (_this.onError) {
  19856. _this.onError(_this);
  19857. }
  19858. onError();
  19859. });
  19860. };
  19861. return MeshAssetTask;
  19862. })();
  19863. BABYLON.MeshAssetTask = MeshAssetTask;
  19864. var TextFileAssetTask = (function () {
  19865. function TextFileAssetTask(name, url) {
  19866. this.name = name;
  19867. this.url = url;
  19868. this.isCompleted = false;
  19869. }
  19870. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19871. var _this = this;
  19872. BABYLON.Tools.LoadFile(this.url, function (data) {
  19873. _this.text = data;
  19874. _this.isCompleted = true;
  19875. if (_this.onSuccess) {
  19876. _this.onSuccess(_this);
  19877. }
  19878. onSuccess();
  19879. }, null, scene.database, false, function () {
  19880. if (_this.onError) {
  19881. _this.onError(_this);
  19882. }
  19883. onError();
  19884. });
  19885. };
  19886. return TextFileAssetTask;
  19887. })();
  19888. BABYLON.TextFileAssetTask = TextFileAssetTask;
  19889. var BinaryFileAssetTask = (function () {
  19890. function BinaryFileAssetTask(name, url) {
  19891. this.name = name;
  19892. this.url = url;
  19893. this.isCompleted = false;
  19894. }
  19895. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19896. var _this = this;
  19897. BABYLON.Tools.LoadFile(this.url, function (data) {
  19898. _this.data = data;
  19899. _this.isCompleted = true;
  19900. if (_this.onSuccess) {
  19901. _this.onSuccess(_this);
  19902. }
  19903. onSuccess();
  19904. }, null, scene.database, true, function () {
  19905. if (_this.onError) {
  19906. _this.onError(_this);
  19907. }
  19908. onError();
  19909. });
  19910. };
  19911. return BinaryFileAssetTask;
  19912. })();
  19913. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  19914. var AssetsManager = (function () {
  19915. function AssetsManager(scene) {
  19916. this._tasks = new Array();
  19917. this._waitingTasksCount = 0;
  19918. this.useDefaultLoadingScreen = true;
  19919. this._scene = scene;
  19920. }
  19921. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  19922. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  19923. this._tasks.push(task);
  19924. return task;
  19925. };
  19926. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  19927. var task = new TextFileAssetTask(taskName, url);
  19928. this._tasks.push(task);
  19929. return task;
  19930. };
  19931. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  19932. var task = new BinaryFileAssetTask(taskName, url);
  19933. this._tasks.push(task);
  19934. return task;
  19935. };
  19936. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  19937. this._waitingTasksCount--;
  19938. if (this._waitingTasksCount === 0) {
  19939. if (this.onFinish) {
  19940. this.onFinish(this._tasks);
  19941. }
  19942. this._scene.getEngine().hideLoadingUI();
  19943. }
  19944. };
  19945. AssetsManager.prototype._runTask = function (task) {
  19946. var _this = this;
  19947. task.run(this._scene, function () {
  19948. if (_this.onTaskSuccess) {
  19949. _this.onTaskSuccess(task);
  19950. }
  19951. _this._decreaseWaitingTasksCount();
  19952. }, function () {
  19953. if (_this.onTaskError) {
  19954. _this.onTaskError(task);
  19955. }
  19956. _this._decreaseWaitingTasksCount();
  19957. });
  19958. };
  19959. AssetsManager.prototype.reset = function () {
  19960. this._tasks = new Array();
  19961. return this;
  19962. };
  19963. AssetsManager.prototype.load = function () {
  19964. this._waitingTasksCount = this._tasks.length;
  19965. if (this._waitingTasksCount === 0) {
  19966. if (this.onFinish) {
  19967. this.onFinish(this._tasks);
  19968. }
  19969. return this;
  19970. }
  19971. if (this.useDefaultLoadingScreen) {
  19972. this._scene.getEngine().displayLoadingUI();
  19973. }
  19974. for (var index = 0; index < this._tasks.length; index++) {
  19975. var task = this._tasks[index];
  19976. this._runTask(task);
  19977. }
  19978. return this;
  19979. };
  19980. return AssetsManager;
  19981. })();
  19982. BABYLON.AssetsManager = AssetsManager;
  19983. })(BABYLON || (BABYLON = {}));