babylon.1.14-beta-debug.js 1007 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410
  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. }, null, null, true);
  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. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3505. var deg = 360;
  3506. var onTransitionEnd = function () {
  3507. deg += 360;
  3508. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3509. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3510. };
  3511. imgBack.addEventListener("transitionend", onTransitionEnd);
  3512. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3513. this._loadingDiv.appendChild(imgBack);
  3514. var imgFront = new Image();
  3515. 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=";
  3516. imgFront.style.position = "absolute";
  3517. imgFront.style.left = "50%";
  3518. imgFront.style.top = "50%";
  3519. imgFront.style.marginLeft = "-50px";
  3520. imgFront.style.marginTop = "-50px";
  3521. this._loadingDiv.appendChild(imgFront);
  3522. this._resizeLoadingUI = function () {
  3523. var canvasRect = _this.getRenderingCanvasClientRect();
  3524. _this._loadingDiv.style.position = "absolute";
  3525. _this._loadingDiv.style.left = canvasRect.left + "px";
  3526. _this._loadingDiv.style.top = canvasRect.top + "px";
  3527. _this._loadingDiv.style.width = canvasRect.width + "px";
  3528. _this._loadingDiv.style.height = canvasRect.height + "px";
  3529. };
  3530. this._resizeLoadingUI();
  3531. window.addEventListener("resize", this._resizeLoadingUI);
  3532. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3533. document.body.appendChild(this._loadingDiv);
  3534. setTimeout(function () {
  3535. _this._loadingDiv.style.opacity = "1";
  3536. imgBack.style.transform = "rotateZ(360deg)";
  3537. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3538. }, 0);
  3539. };
  3540. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3541. set: function (text) {
  3542. if (!this._loadingDiv) {
  3543. return;
  3544. }
  3545. this._loadingTextDiv.innerHTML = text;
  3546. },
  3547. enumerable: true,
  3548. configurable: true
  3549. });
  3550. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3551. get: function () {
  3552. return this._loadingDivBackgroundColor;
  3553. },
  3554. set: function (color) {
  3555. this._loadingDivBackgroundColor = color;
  3556. if (!this._loadingDiv) {
  3557. return;
  3558. }
  3559. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3560. },
  3561. enumerable: true,
  3562. configurable: true
  3563. });
  3564. Engine.prototype.hideLoadingUI = function () {
  3565. var _this = this;
  3566. if (!this._loadingDiv) {
  3567. return;
  3568. }
  3569. var onTransitionEnd = function () {
  3570. if (!_this._loadingDiv) {
  3571. return;
  3572. }
  3573. document.body.removeChild(_this._loadingDiv);
  3574. window.removeEventListener("resize", _this._resizeLoadingUI);
  3575. _this._loadingDiv = null;
  3576. };
  3577. this._loadingDiv.style.opacity = "0";
  3578. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3579. };
  3580. Engine.isSupported = function () {
  3581. try {
  3582. var tempcanvas = document.createElement("canvas");
  3583. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3584. return gl != null && !!window.WebGLRenderingContext;
  3585. } catch (e) {
  3586. return false;
  3587. }
  3588. };
  3589. Engine._ALPHA_DISABLE = 0;
  3590. Engine._ALPHA_ADD = 1;
  3591. Engine._ALPHA_COMBINE = 2;
  3592. Engine._DELAYLOADSTATE_NONE = 0;
  3593. Engine._DELAYLOADSTATE_LOADED = 1;
  3594. Engine._DELAYLOADSTATE_LOADING = 2;
  3595. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3596. Engine.Epsilon = 0.001;
  3597. Engine.CollisionsEpsilon = 0.001;
  3598. Engine.ShadersRepository = "Babylon/Shaders/";
  3599. return Engine;
  3600. })();
  3601. BABYLON.Engine = Engine;
  3602. })(BABYLON || (BABYLON = {}));
  3603. var BABYLON;
  3604. (function (BABYLON) {
  3605. var Node = (function () {
  3606. function Node(name, scene) {
  3607. this.state = "";
  3608. this.animations = new Array();
  3609. this._childrenFlag = -1;
  3610. this._isEnabled = true;
  3611. this._isReady = true;
  3612. this._currentRenderId = -1;
  3613. this.name = name;
  3614. this.id = name;
  3615. this._scene = scene;
  3616. this._initCache();
  3617. }
  3618. Node.prototype.getScene = function () {
  3619. return this._scene;
  3620. };
  3621. Node.prototype.getEngine = function () {
  3622. return this._scene.getEngine();
  3623. };
  3624. Node.prototype.getWorldMatrix = function () {
  3625. return BABYLON.Matrix.Identity();
  3626. };
  3627. Node.prototype._initCache = function () {
  3628. this._cache = {};
  3629. this._cache.parent = undefined;
  3630. };
  3631. Node.prototype.updateCache = function (force) {
  3632. if (!force && this.isSynchronized())
  3633. return;
  3634. this._cache.parent = this.parent;
  3635. this._updateCache();
  3636. };
  3637. Node.prototype._updateCache = function (ignoreParentClass) {
  3638. };
  3639. Node.prototype._isSynchronized = function () {
  3640. return true;
  3641. };
  3642. Node.prototype.isSynchronizedWithParent = function () {
  3643. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3644. };
  3645. Node.prototype.isSynchronized = function (updateCache) {
  3646. var check = this.hasNewParent();
  3647. check = check || !this.isSynchronizedWithParent();
  3648. check = check || !this._isSynchronized();
  3649. if (updateCache)
  3650. this.updateCache(true);
  3651. return !check;
  3652. };
  3653. Node.prototype.hasNewParent = function (update) {
  3654. if (this._cache.parent === this.parent)
  3655. return false;
  3656. if (update)
  3657. this._cache.parent = this.parent;
  3658. return true;
  3659. };
  3660. Node.prototype.isReady = function () {
  3661. return this._isReady;
  3662. };
  3663. Node.prototype.isEnabled = function () {
  3664. if (!this._isEnabled) {
  3665. return false;
  3666. }
  3667. if (this.parent) {
  3668. return this.parent.isEnabled();
  3669. }
  3670. return true;
  3671. };
  3672. Node.prototype.setEnabled = function (value) {
  3673. this._isEnabled = value;
  3674. };
  3675. Node.prototype.isDescendantOf = function (ancestor) {
  3676. if (this.parent) {
  3677. if (this.parent === ancestor) {
  3678. return true;
  3679. }
  3680. return this.parent.isDescendantOf(ancestor);
  3681. }
  3682. return false;
  3683. };
  3684. Node.prototype._getDescendants = function (list, results) {
  3685. for (var index = 0; index < list.length; index++) {
  3686. var item = list[index];
  3687. if (item.isDescendantOf(this)) {
  3688. results.push(item);
  3689. }
  3690. }
  3691. };
  3692. Node.prototype.getDescendants = function () {
  3693. var results = [];
  3694. this._getDescendants(this._scene.meshes, results);
  3695. this._getDescendants(this._scene.lights, results);
  3696. this._getDescendants(this._scene.cameras, results);
  3697. return results;
  3698. };
  3699. Node.prototype._setReady = function (state) {
  3700. if (state == this._isReady) {
  3701. return;
  3702. }
  3703. if (!state) {
  3704. this._isReady = false;
  3705. return;
  3706. }
  3707. this._isReady = true;
  3708. if (this.onReady) {
  3709. this.onReady(this);
  3710. }
  3711. };
  3712. return Node;
  3713. })();
  3714. BABYLON.Node = Node;
  3715. })(BABYLON || (BABYLON = {}));
  3716. var BABYLON;
  3717. (function (BABYLON) {
  3718. var BoundingSphere = (function () {
  3719. function BoundingSphere(minimum, maximum) {
  3720. this.minimum = minimum;
  3721. this.maximum = maximum;
  3722. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3723. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3724. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3725. this.radius = distance * 0.5;
  3726. this.centerWorld = BABYLON.Vector3.Zero();
  3727. this._update(BABYLON.Matrix.Identity());
  3728. }
  3729. BoundingSphere.prototype._update = function (world) {
  3730. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3731. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3732. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3733. };
  3734. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3735. for (var i = 0; i < 6; i++) {
  3736. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3737. return false;
  3738. }
  3739. return true;
  3740. };
  3741. BoundingSphere.prototype.intersectsPoint = function (point) {
  3742. var x = this.centerWorld.x - point.x;
  3743. var y = this.centerWorld.y - point.y;
  3744. var z = this.centerWorld.z - point.z;
  3745. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3746. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3747. return false;
  3748. return true;
  3749. };
  3750. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3751. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3752. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3753. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3755. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3756. return false;
  3757. return true;
  3758. };
  3759. return BoundingSphere;
  3760. })();
  3761. BABYLON.BoundingSphere = BoundingSphere;
  3762. })(BABYLON || (BABYLON = {}));
  3763. var BABYLON;
  3764. (function (BABYLON) {
  3765. var BoundingBox = (function () {
  3766. function BoundingBox(minimum, maximum) {
  3767. this.minimum = minimum;
  3768. this.maximum = maximum;
  3769. this.vectors = new Array();
  3770. this.vectorsWorld = new Array();
  3771. this.vectors.push(this.minimum.clone());
  3772. this.vectors.push(this.maximum.clone());
  3773. this.vectors.push(this.minimum.clone());
  3774. this.vectors[2].x = this.maximum.x;
  3775. this.vectors.push(this.minimum.clone());
  3776. this.vectors[3].y = this.maximum.y;
  3777. this.vectors.push(this.minimum.clone());
  3778. this.vectors[4].z = this.maximum.z;
  3779. this.vectors.push(this.maximum.clone());
  3780. this.vectors[5].z = this.minimum.z;
  3781. this.vectors.push(this.maximum.clone());
  3782. this.vectors[6].x = this.minimum.x;
  3783. this.vectors.push(this.maximum.clone());
  3784. this.vectors[7].y = this.minimum.y;
  3785. this.center = this.maximum.add(this.minimum).scale(0.5);
  3786. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3787. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3788. for (var index = 0; index < this.vectors.length; index++) {
  3789. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3790. }
  3791. this.minimumWorld = BABYLON.Vector3.Zero();
  3792. this.maximumWorld = BABYLON.Vector3.Zero();
  3793. this._update(BABYLON.Matrix.Identity());
  3794. }
  3795. BoundingBox.prototype.getWorldMatrix = function () {
  3796. return this._worldMatrix;
  3797. };
  3798. BoundingBox.prototype._update = function (world) {
  3799. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3800. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3801. for (var index = 0; index < this.vectors.length; index++) {
  3802. var v = this.vectorsWorld[index];
  3803. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3804. if (v.x < this.minimumWorld.x)
  3805. this.minimumWorld.x = v.x;
  3806. if (v.y < this.minimumWorld.y)
  3807. this.minimumWorld.y = v.y;
  3808. if (v.z < this.minimumWorld.z)
  3809. this.minimumWorld.z = v.z;
  3810. if (v.x > this.maximumWorld.x)
  3811. this.maximumWorld.x = v.x;
  3812. if (v.y > this.maximumWorld.y)
  3813. this.maximumWorld.y = v.y;
  3814. if (v.z > this.maximumWorld.z)
  3815. this.maximumWorld.z = v.z;
  3816. }
  3817. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3818. this.center.scaleInPlace(0.5);
  3819. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3820. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3821. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3822. this._worldMatrix = world;
  3823. };
  3824. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3825. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3826. };
  3827. BoundingBox.prototype.intersectsPoint = function (point) {
  3828. var delta = BABYLON.Engine.Epsilon;
  3829. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3830. return false;
  3831. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3832. return false;
  3833. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3834. return false;
  3835. return true;
  3836. };
  3837. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3838. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3839. };
  3840. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3841. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3842. return false;
  3843. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3844. return false;
  3845. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3846. return false;
  3847. return true;
  3848. };
  3849. BoundingBox.Intersects = function (box0, box1) {
  3850. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3851. return false;
  3852. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3853. return false;
  3854. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3855. return false;
  3856. return true;
  3857. };
  3858. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3859. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3860. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3861. return (num <= (sphereRadius * sphereRadius));
  3862. };
  3863. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3864. for (var p = 0; p < 6; p++) {
  3865. var inCount = 8;
  3866. for (var i = 0; i < 8; i++) {
  3867. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3868. --inCount;
  3869. } else {
  3870. break;
  3871. }
  3872. }
  3873. if (inCount == 0)
  3874. return false;
  3875. }
  3876. return true;
  3877. };
  3878. return BoundingBox;
  3879. })();
  3880. BABYLON.BoundingBox = BoundingBox;
  3881. })(BABYLON || (BABYLON = {}));
  3882. var BABYLON;
  3883. (function (BABYLON) {
  3884. var computeBoxExtents = function (axis, box) {
  3885. var p = BABYLON.Vector3.Dot(box.center, axis);
  3886. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3887. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3888. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3889. var r = r0 + r1 + r2;
  3890. return {
  3891. min: p - r,
  3892. max: p + r
  3893. };
  3894. };
  3895. var extentsOverlap = function (min0, max0, min1, max1) {
  3896. return !(min0 > max1 || min1 > max0);
  3897. };
  3898. var axisOverlap = function (axis, box0, box1) {
  3899. var result0 = computeBoxExtents(axis, box0);
  3900. var result1 = computeBoxExtents(axis, box1);
  3901. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3902. };
  3903. var BoundingInfo = (function () {
  3904. function BoundingInfo(minimum, maximum) {
  3905. this.minimum = minimum;
  3906. this.maximum = maximum;
  3907. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3908. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3909. }
  3910. BoundingInfo.prototype._update = function (world) {
  3911. this.boundingBox._update(world);
  3912. this.boundingSphere._update(world);
  3913. };
  3914. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3915. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3916. return false;
  3917. return this.boundingBox.isInFrustum(frustumPlanes);
  3918. };
  3919. BoundingInfo.prototype._checkCollision = function (collider) {
  3920. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3921. };
  3922. BoundingInfo.prototype.intersectsPoint = function (point) {
  3923. if (!this.boundingSphere.centerWorld) {
  3924. return false;
  3925. }
  3926. if (!this.boundingSphere.intersectsPoint(point)) {
  3927. return false;
  3928. }
  3929. if (!this.boundingBox.intersectsPoint(point)) {
  3930. return false;
  3931. }
  3932. return true;
  3933. };
  3934. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3935. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3936. return false;
  3937. }
  3938. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3939. return false;
  3940. }
  3941. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3942. return false;
  3943. }
  3944. if (!precise) {
  3945. return true;
  3946. }
  3947. var box0 = this.boundingBox;
  3948. var box1 = boundingInfo.boundingBox;
  3949. if (!axisOverlap(box0.directions[0], box0, box1))
  3950. return false;
  3951. if (!axisOverlap(box0.directions[1], box0, box1))
  3952. return false;
  3953. if (!axisOverlap(box0.directions[2], box0, box1))
  3954. return false;
  3955. if (!axisOverlap(box1.directions[0], box0, box1))
  3956. return false;
  3957. if (!axisOverlap(box1.directions[1], box0, box1))
  3958. return false;
  3959. if (!axisOverlap(box1.directions[2], box0, box1))
  3960. return false;
  3961. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3962. return false;
  3963. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3964. return false;
  3965. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3966. return false;
  3967. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3968. return false;
  3969. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3970. return false;
  3971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3972. return false;
  3973. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3974. return false;
  3975. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  3976. return false;
  3977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  3978. return false;
  3979. return true;
  3980. };
  3981. return BoundingInfo;
  3982. })();
  3983. BABYLON.BoundingInfo = BoundingInfo;
  3984. })(BABYLON || (BABYLON = {}));
  3985. var __extends = this.__extends || function (d, b) {
  3986. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3987. function __() { this.constructor = d; }
  3988. __.prototype = b.prototype;
  3989. d.prototype = new __();
  3990. };
  3991. var BABYLON;
  3992. (function (BABYLON) {
  3993. var Light = (function (_super) {
  3994. __extends(Light, _super);
  3995. function Light(name, scene) {
  3996. _super.call(this, name, scene);
  3997. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  3998. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  3999. this.intensity = 1.0;
  4000. this.range = Number.MAX_VALUE;
  4001. this.includedOnlyMeshes = new Array();
  4002. this.excludedMeshes = new Array();
  4003. this._excludedMeshesIds = new Array();
  4004. this._includedOnlyMeshesIds = new Array();
  4005. scene.lights.push(this);
  4006. }
  4007. Light.prototype.getShadowGenerator = function () {
  4008. return this._shadowGenerator;
  4009. };
  4010. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4011. };
  4012. Light.prototype._getWorldMatrix = function () {
  4013. return BABYLON.Matrix.Identity();
  4014. };
  4015. Light.prototype.canAffectMesh = function (mesh) {
  4016. if (!mesh) {
  4017. return true;
  4018. }
  4019. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4020. return false;
  4021. }
  4022. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4023. return false;
  4024. }
  4025. return true;
  4026. };
  4027. Light.prototype.getWorldMatrix = function () {
  4028. this._currentRenderId = this.getScene().getRenderId();
  4029. var worldMatrix = this._getWorldMatrix();
  4030. if (this.parent && this.parent.getWorldMatrix) {
  4031. if (!this._parentedWorldMatrix) {
  4032. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4033. }
  4034. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4035. return this._parentedWorldMatrix;
  4036. }
  4037. return worldMatrix;
  4038. };
  4039. Light.prototype.dispose = function () {
  4040. if (this._shadowGenerator) {
  4041. this._shadowGenerator.dispose();
  4042. this._shadowGenerator = null;
  4043. }
  4044. var index = this.getScene().lights.indexOf(this);
  4045. this.getScene().lights.splice(index, 1);
  4046. };
  4047. return Light;
  4048. })(BABYLON.Node);
  4049. BABYLON.Light = Light;
  4050. })(BABYLON || (BABYLON = {}));
  4051. var __extends = this.__extends || function (d, b) {
  4052. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4053. function __() { this.constructor = d; }
  4054. __.prototype = b.prototype;
  4055. d.prototype = new __();
  4056. };
  4057. var BABYLON;
  4058. (function (BABYLON) {
  4059. var PointLight = (function (_super) {
  4060. __extends(PointLight, _super);
  4061. function PointLight(name, position, scene) {
  4062. _super.call(this, name, scene);
  4063. this.position = position;
  4064. }
  4065. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4066. if (this.parent && this.parent.getWorldMatrix) {
  4067. if (!this._transformedPosition) {
  4068. this._transformedPosition = BABYLON.Vector3.Zero();
  4069. }
  4070. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4071. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4072. return;
  4073. }
  4074. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4075. };
  4076. PointLight.prototype.getShadowGenerator = function () {
  4077. return null;
  4078. };
  4079. PointLight.prototype._getWorldMatrix = function () {
  4080. if (!this._worldMatrix) {
  4081. this._worldMatrix = BABYLON.Matrix.Identity();
  4082. }
  4083. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4084. return this._worldMatrix;
  4085. };
  4086. return PointLight;
  4087. })(BABYLON.Light);
  4088. BABYLON.PointLight = PointLight;
  4089. })(BABYLON || (BABYLON = {}));
  4090. var __extends = this.__extends || function (d, b) {
  4091. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4092. function __() { this.constructor = d; }
  4093. __.prototype = b.prototype;
  4094. d.prototype = new __();
  4095. };
  4096. var BABYLON;
  4097. (function (BABYLON) {
  4098. var SpotLight = (function (_super) {
  4099. __extends(SpotLight, _super);
  4100. function SpotLight(name, position, direction, angle, exponent, scene) {
  4101. _super.call(this, name, scene);
  4102. this.position = position;
  4103. this.direction = direction;
  4104. this.angle = angle;
  4105. this.exponent = exponent;
  4106. }
  4107. SpotLight.prototype.setDirectionToTarget = function (target) {
  4108. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4109. return this.direction;
  4110. };
  4111. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4112. var normalizeDirection;
  4113. if (this.parent && this.parent.getWorldMatrix) {
  4114. if (!this._transformedDirection) {
  4115. this._transformedDirection = BABYLON.Vector3.Zero();
  4116. }
  4117. if (!this._transformedPosition) {
  4118. this._transformedPosition = BABYLON.Vector3.Zero();
  4119. }
  4120. var parentWorldMatrix = this.parent.getWorldMatrix();
  4121. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4122. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4123. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4124. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4125. } else {
  4126. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4127. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4128. }
  4129. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4130. };
  4131. SpotLight.prototype._getWorldMatrix = function () {
  4132. if (!this._worldMatrix) {
  4133. this._worldMatrix = BABYLON.Matrix.Identity();
  4134. }
  4135. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4136. return this._worldMatrix;
  4137. };
  4138. return SpotLight;
  4139. })(BABYLON.Light);
  4140. BABYLON.SpotLight = SpotLight;
  4141. })(BABYLON || (BABYLON = {}));
  4142. var __extends = this.__extends || function (d, b) {
  4143. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4144. function __() { this.constructor = d; }
  4145. __.prototype = b.prototype;
  4146. d.prototype = new __();
  4147. };
  4148. var BABYLON;
  4149. (function (BABYLON) {
  4150. var DirectionalLight = (function (_super) {
  4151. __extends(DirectionalLight, _super);
  4152. function DirectionalLight(name, direction, scene) {
  4153. _super.call(this, name, scene);
  4154. this.direction = direction;
  4155. this.position = direction.scale(-1);
  4156. }
  4157. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4158. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4159. return this.direction;
  4160. };
  4161. DirectionalLight.prototype._computeTransformedPosition = function () {
  4162. if (this.parent && this.parent.getWorldMatrix) {
  4163. if (!this._transformedPosition) {
  4164. this._transformedPosition = BABYLON.Vector3.Zero();
  4165. }
  4166. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4167. return true;
  4168. }
  4169. return false;
  4170. };
  4171. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4172. if (this.parent && this.parent.getWorldMatrix) {
  4173. if (!this._transformedDirection) {
  4174. this._transformedDirection = BABYLON.Vector3.Zero();
  4175. }
  4176. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4177. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4178. return;
  4179. }
  4180. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4181. };
  4182. DirectionalLight.prototype._getWorldMatrix = function () {
  4183. if (!this._worldMatrix) {
  4184. this._worldMatrix = BABYLON.Matrix.Identity();
  4185. }
  4186. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4187. return this._worldMatrix;
  4188. };
  4189. return DirectionalLight;
  4190. })(BABYLON.Light);
  4191. BABYLON.DirectionalLight = DirectionalLight;
  4192. })(BABYLON || (BABYLON = {}));
  4193. var BABYLON;
  4194. (function (BABYLON) {
  4195. var ShadowGenerator = (function () {
  4196. function ShadowGenerator(mapSize, light) {
  4197. var _this = this;
  4198. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4199. this._darkness = 0;
  4200. this._transparencyShadow = false;
  4201. this._viewMatrix = BABYLON.Matrix.Zero();
  4202. this._projectionMatrix = BABYLON.Matrix.Zero();
  4203. this._transformMatrix = BABYLON.Matrix.Zero();
  4204. this._worldViewProjection = BABYLON.Matrix.Zero();
  4205. this._light = light;
  4206. this._scene = light.getScene();
  4207. light._shadowGenerator = this;
  4208. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4209. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4210. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4211. this._shadowMap.renderParticles = false;
  4212. var renderSubMesh = function (subMesh) {
  4213. var mesh = subMesh.getRenderingMesh();
  4214. var scene = _this._scene;
  4215. var engine = scene.getEngine();
  4216. engine.setState(subMesh.getMaterial().backFaceCulling);
  4217. var batch = mesh._getInstancesRenderList(subMesh._id);
  4218. if (batch.mustReturn) {
  4219. return;
  4220. }
  4221. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4222. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4223. engine.enableEffect(_this._effect);
  4224. mesh._bind(subMesh, _this._effect, false);
  4225. var material = subMesh.getMaterial();
  4226. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4227. if (material && material.needAlphaTesting()) {
  4228. var alphaTexture = material.getAlphaTestTexture();
  4229. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4230. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4231. }
  4232. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4233. if (useBones) {
  4234. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4235. }
  4236. if (hardwareInstancedRendering) {
  4237. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4238. } else {
  4239. if (batch.renderSelf[subMesh._id]) {
  4240. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4241. mesh._draw(subMesh, true);
  4242. }
  4243. if (batch.visibleInstances[subMesh._id]) {
  4244. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4245. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4246. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4247. mesh._draw(subMesh, true);
  4248. }
  4249. }
  4250. }
  4251. } else {
  4252. _this._shadowMap.resetRefreshCounter();
  4253. }
  4254. };
  4255. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4256. var index;
  4257. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4258. renderSubMesh(opaqueSubMeshes.data[index]);
  4259. }
  4260. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4261. renderSubMesh(alphaTestSubMeshes.data[index]);
  4262. }
  4263. if (_this._transparencyShadow) {
  4264. for (index = 0; index < transparentSubMeshes.length; index++) {
  4265. renderSubMesh(transparentSubMeshes.data[index]);
  4266. }
  4267. }
  4268. };
  4269. }
  4270. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4271. get: function () {
  4272. return ShadowGenerator._FILTER_NONE;
  4273. },
  4274. enumerable: true,
  4275. configurable: true
  4276. });
  4277. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4278. get: function () {
  4279. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4280. },
  4281. enumerable: true,
  4282. configurable: true
  4283. });
  4284. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4285. get: function () {
  4286. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4287. },
  4288. enumerable: true,
  4289. configurable: true
  4290. });
  4291. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4292. get: function () {
  4293. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4294. },
  4295. set: function (value) {
  4296. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4297. },
  4298. enumerable: true,
  4299. configurable: true
  4300. });
  4301. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4302. get: function () {
  4303. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4304. },
  4305. set: function (value) {
  4306. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4307. },
  4308. enumerable: true,
  4309. configurable: true
  4310. });
  4311. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4312. var defines = [];
  4313. if (this.useVarianceShadowMap) {
  4314. defines.push("#define VSM");
  4315. }
  4316. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4317. var mesh = subMesh.getMesh();
  4318. var material = subMesh.getMaterial();
  4319. if (material && material.needAlphaTesting()) {
  4320. defines.push("#define ALPHATEST");
  4321. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4322. attribs.push(BABYLON.VertexBuffer.UVKind);
  4323. defines.push("#define UV1");
  4324. }
  4325. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4326. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4327. defines.push("#define UV2");
  4328. }
  4329. }
  4330. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4331. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4332. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4333. defines.push("#define BONES");
  4334. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4335. }
  4336. if (useInstances) {
  4337. defines.push("#define INSTANCES");
  4338. attribs.push("world0");
  4339. attribs.push("world1");
  4340. attribs.push("world2");
  4341. attribs.push("world3");
  4342. }
  4343. var join = defines.join("\n");
  4344. if (this._cachedDefines != join) {
  4345. this._cachedDefines = join;
  4346. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4347. }
  4348. return this._effect.isReady();
  4349. };
  4350. ShadowGenerator.prototype.getShadowMap = function () {
  4351. return this._shadowMap;
  4352. };
  4353. ShadowGenerator.prototype.getLight = function () {
  4354. return this._light;
  4355. };
  4356. ShadowGenerator.prototype.getTransformMatrix = function () {
  4357. var lightPosition = this._light.position;
  4358. var lightDirection = this._light.direction;
  4359. if (this._light._computeTransformedPosition()) {
  4360. lightPosition = this._light._transformedPosition;
  4361. }
  4362. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4363. this._cachedPosition = lightPosition.clone();
  4364. this._cachedDirection = lightDirection.clone();
  4365. var activeCamera = this._scene.activeCamera;
  4366. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4367. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4368. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4369. }
  4370. return this._transformMatrix;
  4371. };
  4372. ShadowGenerator.prototype.getDarkness = function () {
  4373. return this._darkness;
  4374. };
  4375. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4376. if (darkness >= 1.0)
  4377. this._darkness = 1.0;
  4378. else if (darkness <= 0.0)
  4379. this._darkness = 0.0;
  4380. else
  4381. this._darkness = darkness;
  4382. };
  4383. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4384. this._transparencyShadow = hasShadow;
  4385. };
  4386. ShadowGenerator.prototype.dispose = function () {
  4387. this._shadowMap.dispose();
  4388. };
  4389. ShadowGenerator._FILTER_NONE = 0;
  4390. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4391. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4392. return ShadowGenerator;
  4393. })();
  4394. BABYLON.ShadowGenerator = ShadowGenerator;
  4395. })(BABYLON || (BABYLON = {}));
  4396. var __extends = this.__extends || function (d, b) {
  4397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4398. function __() { this.constructor = d; }
  4399. __.prototype = b.prototype;
  4400. d.prototype = new __();
  4401. };
  4402. var BABYLON;
  4403. (function (BABYLON) {
  4404. var HemisphericLight = (function (_super) {
  4405. __extends(HemisphericLight, _super);
  4406. function HemisphericLight(name, direction, scene) {
  4407. _super.call(this, name, scene);
  4408. this.direction = direction;
  4409. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4410. }
  4411. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4412. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4413. return this.direction;
  4414. };
  4415. HemisphericLight.prototype.getShadowGenerator = function () {
  4416. return null;
  4417. };
  4418. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4419. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4420. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4421. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4422. };
  4423. HemisphericLight.prototype._getWorldMatrix = function () {
  4424. if (!this._worldMatrix) {
  4425. this._worldMatrix = BABYLON.Matrix.Identity();
  4426. }
  4427. return this._worldMatrix;
  4428. };
  4429. return HemisphericLight;
  4430. })(BABYLON.Light);
  4431. BABYLON.HemisphericLight = HemisphericLight;
  4432. })(BABYLON || (BABYLON = {}));
  4433. var BABYLON;
  4434. (function (BABYLON) {
  4435. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4436. if (boxMin.x > sphereCenter.x + sphereRadius)
  4437. return false;
  4438. if (sphereCenter.x - sphereRadius > boxMax.x)
  4439. return false;
  4440. if (boxMin.y > sphereCenter.y + sphereRadius)
  4441. return false;
  4442. if (sphereCenter.y - sphereRadius > boxMax.y)
  4443. return false;
  4444. if (boxMin.z > sphereCenter.z + sphereRadius)
  4445. return false;
  4446. if (sphereCenter.z - sphereRadius > boxMax.z)
  4447. return false;
  4448. return true;
  4449. };
  4450. var getLowestRoot = function (a, b, c, maxR) {
  4451. var determinant = b * b - 4.0 * a * c;
  4452. var result = { root: 0, found: false };
  4453. if (determinant < 0)
  4454. return result;
  4455. var sqrtD = Math.sqrt(determinant);
  4456. var r1 = (-b - sqrtD) / (2.0 * a);
  4457. var r2 = (-b + sqrtD) / (2.0 * a);
  4458. if (r1 > r2) {
  4459. var temp = r2;
  4460. r2 = r1;
  4461. r1 = temp;
  4462. }
  4463. if (r1 > 0 && r1 < maxR) {
  4464. result.root = r1;
  4465. result.found = true;
  4466. return result;
  4467. }
  4468. if (r2 > 0 && r2 < maxR) {
  4469. result.root = r2;
  4470. result.found = true;
  4471. return result;
  4472. }
  4473. return result;
  4474. };
  4475. var Collider = (function () {
  4476. function Collider() {
  4477. this.radius = new BABYLON.Vector3(1, 1, 1);
  4478. this.retry = 0;
  4479. this.basePointWorld = BABYLON.Vector3.Zero();
  4480. this.velocityWorld = BABYLON.Vector3.Zero();
  4481. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4482. this._collisionPoint = BABYLON.Vector3.Zero();
  4483. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4484. this._tempVector = BABYLON.Vector3.Zero();
  4485. this._tempVector2 = BABYLON.Vector3.Zero();
  4486. this._tempVector3 = BABYLON.Vector3.Zero();
  4487. this._tempVector4 = BABYLON.Vector3.Zero();
  4488. this._edge = BABYLON.Vector3.Zero();
  4489. this._baseToVertex = BABYLON.Vector3.Zero();
  4490. this._destinationPoint = BABYLON.Vector3.Zero();
  4491. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4492. this._displacementVector = BABYLON.Vector3.Zero();
  4493. }
  4494. Collider.prototype._initialize = function (source, dir, e) {
  4495. this.velocity = dir;
  4496. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4497. this.basePoint = source;
  4498. source.multiplyToRef(this.radius, this.basePointWorld);
  4499. dir.multiplyToRef(this.radius, this.velocityWorld);
  4500. this.velocityWorldLength = this.velocityWorld.length();
  4501. this.epsilon = e;
  4502. this.collisionFound = false;
  4503. };
  4504. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4505. pa.subtractToRef(point, this._tempVector);
  4506. pb.subtractToRef(point, this._tempVector2);
  4507. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4508. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4509. if (d < 0)
  4510. return false;
  4511. pc.subtractToRef(point, this._tempVector3);
  4512. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4513. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4514. if (d < 0)
  4515. return false;
  4516. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4517. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4518. return d >= 0;
  4519. };
  4520. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4521. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4522. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4523. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4524. return false;
  4525. }
  4526. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4527. return false;
  4528. return true;
  4529. };
  4530. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4531. var t0;
  4532. var embeddedInPlane = false;
  4533. if (!subMesh._trianglePlanes) {
  4534. subMesh._trianglePlanes = [];
  4535. }
  4536. if (!subMesh._trianglePlanes[faceIndex]) {
  4537. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4538. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4539. }
  4540. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4541. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4542. return;
  4543. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4544. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4545. if (normalDotVelocity == 0) {
  4546. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4547. return;
  4548. embeddedInPlane = true;
  4549. t0 = 0;
  4550. } else {
  4551. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4552. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4553. if (t0 > t1) {
  4554. var temp = t1;
  4555. t1 = t0;
  4556. t0 = temp;
  4557. }
  4558. if (t0 > 1.0 || t1 < 0.0)
  4559. return;
  4560. if (t0 < 0)
  4561. t0 = 0;
  4562. if (t0 > 1.0)
  4563. t0 = 1.0;
  4564. }
  4565. this._collisionPoint.copyFromFloats(0, 0, 0);
  4566. var found = false;
  4567. var t = 1.0;
  4568. if (!embeddedInPlane) {
  4569. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4570. this.velocity.scaleToRef(t0, this._tempVector);
  4571. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4572. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4573. found = true;
  4574. t = t0;
  4575. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4576. }
  4577. }
  4578. if (!found) {
  4579. var velocitySquaredLength = this.velocity.lengthSquared();
  4580. var a = velocitySquaredLength;
  4581. this.basePoint.subtractToRef(p1, this._tempVector);
  4582. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4583. var c = this._tempVector.lengthSquared() - 1.0;
  4584. var lowestRoot = getLowestRoot(a, b, c, t);
  4585. if (lowestRoot.found) {
  4586. t = lowestRoot.root;
  4587. found = true;
  4588. this._collisionPoint.copyFrom(p1);
  4589. }
  4590. this.basePoint.subtractToRef(p2, this._tempVector);
  4591. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4592. c = this._tempVector.lengthSquared() - 1.0;
  4593. lowestRoot = getLowestRoot(a, b, c, t);
  4594. if (lowestRoot.found) {
  4595. t = lowestRoot.root;
  4596. found = true;
  4597. this._collisionPoint.copyFrom(p2);
  4598. }
  4599. this.basePoint.subtractToRef(p3, this._tempVector);
  4600. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4601. c = this._tempVector.lengthSquared() - 1.0;
  4602. lowestRoot = getLowestRoot(a, b, c, t);
  4603. if (lowestRoot.found) {
  4604. t = lowestRoot.root;
  4605. found = true;
  4606. this._collisionPoint.copyFrom(p3);
  4607. }
  4608. p2.subtractToRef(p1, this._edge);
  4609. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4610. var edgeSquaredLength = this._edge.lengthSquared();
  4611. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4612. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4613. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4614. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4615. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4616. lowestRoot = getLowestRoot(a, b, c, t);
  4617. if (lowestRoot.found) {
  4618. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4619. if (f >= 0.0 && f <= 1.0) {
  4620. t = lowestRoot.root;
  4621. found = true;
  4622. this._edge.scaleInPlace(f);
  4623. p1.addToRef(this._edge, this._collisionPoint);
  4624. }
  4625. }
  4626. p3.subtractToRef(p2, this._edge);
  4627. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4628. edgeSquaredLength = this._edge.lengthSquared();
  4629. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4630. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4631. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4632. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4633. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4634. lowestRoot = getLowestRoot(a, b, c, t);
  4635. if (lowestRoot.found) {
  4636. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4637. if (f >= 0.0 && f <= 1.0) {
  4638. t = lowestRoot.root;
  4639. found = true;
  4640. this._edge.scaleInPlace(f);
  4641. p2.addToRef(this._edge, this._collisionPoint);
  4642. }
  4643. }
  4644. p1.subtractToRef(p3, this._edge);
  4645. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4646. edgeSquaredLength = this._edge.lengthSquared();
  4647. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4648. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4649. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4650. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4651. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4652. lowestRoot = getLowestRoot(a, b, c, t);
  4653. if (lowestRoot.found) {
  4654. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4655. if (f >= 0.0 && f <= 1.0) {
  4656. t = lowestRoot.root;
  4657. found = true;
  4658. this._edge.scaleInPlace(f);
  4659. p3.addToRef(this._edge, this._collisionPoint);
  4660. }
  4661. }
  4662. }
  4663. if (found) {
  4664. var distToCollision = t * this.velocity.length();
  4665. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4666. if (!this.intersectionPoint) {
  4667. this.intersectionPoint = this._collisionPoint.clone();
  4668. } else {
  4669. this.intersectionPoint.copyFrom(this._collisionPoint);
  4670. }
  4671. this.nearestDistance = distToCollision;
  4672. this.collisionFound = true;
  4673. this.collidedMesh = subMesh.getMesh();
  4674. }
  4675. }
  4676. };
  4677. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4678. for (var i = indexStart; i < indexEnd; i += 3) {
  4679. var p1 = pts[indices[i] - decal];
  4680. var p2 = pts[indices[i + 1] - decal];
  4681. var p3 = pts[indices[i + 2] - decal];
  4682. this._testTriangle(i, subMesh, p3, p2, p1);
  4683. }
  4684. };
  4685. Collider.prototype._getResponse = function (pos, vel) {
  4686. pos.addToRef(vel, this._destinationPoint);
  4687. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4688. this.basePoint.addToRef(vel, pos);
  4689. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4690. this._slidePlaneNormal.normalize();
  4691. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4692. pos.addInPlace(this._displacementVector);
  4693. this.intersectionPoint.addInPlace(this._displacementVector);
  4694. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4695. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4696. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4697. };
  4698. return Collider;
  4699. })();
  4700. BABYLON.Collider = Collider;
  4701. })(BABYLON || (BABYLON = {}));
  4702. var __extends = this.__extends || function (d, b) {
  4703. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4704. function __() { this.constructor = d; }
  4705. __.prototype = b.prototype;
  4706. d.prototype = new __();
  4707. };
  4708. var BABYLON;
  4709. (function (BABYLON) {
  4710. var Camera = (function (_super) {
  4711. __extends(Camera, _super);
  4712. function Camera(name, position, scene) {
  4713. _super.call(this, name, scene);
  4714. this.position = position;
  4715. this.upVector = BABYLON.Vector3.Up();
  4716. this.orthoLeft = null;
  4717. this.orthoRight = null;
  4718. this.orthoBottom = null;
  4719. this.orthoTop = null;
  4720. this.fov = 0.8;
  4721. this.minZ = 1.0;
  4722. this.maxZ = 10000.0;
  4723. this.inertia = 0.9;
  4724. this.mode = Camera.PERSPECTIVE_CAMERA;
  4725. this.isIntermediate = false;
  4726. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4727. this.subCameras = [];
  4728. this.layerMask = 0xFFFFFFFF;
  4729. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4730. this._projectionMatrix = new BABYLON.Matrix();
  4731. this._postProcesses = new Array();
  4732. this._postProcessesTakenIndices = [];
  4733. scene.cameras.push(this);
  4734. if (!scene.activeCamera) {
  4735. scene.activeCamera = this;
  4736. }
  4737. }
  4738. Camera.prototype._initCache = function () {
  4739. _super.prototype._initCache.call(this);
  4740. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4741. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4742. this._cache.mode = undefined;
  4743. this._cache.minZ = undefined;
  4744. this._cache.maxZ = undefined;
  4745. this._cache.fov = undefined;
  4746. this._cache.aspectRatio = undefined;
  4747. this._cache.orthoLeft = undefined;
  4748. this._cache.orthoRight = undefined;
  4749. this._cache.orthoBottom = undefined;
  4750. this._cache.orthoTop = undefined;
  4751. this._cache.renderWidth = undefined;
  4752. this._cache.renderHeight = undefined;
  4753. };
  4754. Camera.prototype._updateCache = function (ignoreParentClass) {
  4755. if (!ignoreParentClass) {
  4756. _super.prototype._updateCache.call(this);
  4757. }
  4758. var engine = this.getEngine();
  4759. this._cache.position.copyFrom(this.position);
  4760. this._cache.upVector.copyFrom(this.upVector);
  4761. this._cache.mode = this.mode;
  4762. this._cache.minZ = this.minZ;
  4763. this._cache.maxZ = this.maxZ;
  4764. this._cache.fov = this.fov;
  4765. this._cache.aspectRatio = engine.getAspectRatio(this);
  4766. this._cache.orthoLeft = this.orthoLeft;
  4767. this._cache.orthoRight = this.orthoRight;
  4768. this._cache.orthoBottom = this.orthoBottom;
  4769. this._cache.orthoTop = this.orthoTop;
  4770. this._cache.renderWidth = engine.getRenderWidth();
  4771. this._cache.renderHeight = engine.getRenderHeight();
  4772. };
  4773. Camera.prototype._updateFromScene = function () {
  4774. this.updateCache();
  4775. this._update();
  4776. };
  4777. Camera.prototype._isSynchronized = function () {
  4778. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4779. };
  4780. Camera.prototype._isSynchronizedViewMatrix = function () {
  4781. if (!_super.prototype._isSynchronized.call(this))
  4782. return false;
  4783. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4784. };
  4785. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4786. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4787. if (!check) {
  4788. return false;
  4789. }
  4790. var engine = this.getEngine();
  4791. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4792. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4793. } else {
  4794. 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();
  4795. }
  4796. return check;
  4797. };
  4798. Camera.prototype.attachControl = function (element) {
  4799. };
  4800. Camera.prototype.detachControl = function (element) {
  4801. };
  4802. Camera.prototype._update = function () {
  4803. };
  4804. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4805. if (typeof insertAt === "undefined") { insertAt = null; }
  4806. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4807. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4808. return 0;
  4809. }
  4810. if (insertAt == null || insertAt < 0) {
  4811. this._postProcesses.push(postProcess);
  4812. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4813. return this._postProcesses.length - 1;
  4814. }
  4815. var add = 0;
  4816. if (this._postProcesses[insertAt]) {
  4817. var start = this._postProcesses.length - 1;
  4818. for (var i = start; i >= insertAt + 1; --i) {
  4819. this._postProcesses[i + 1] = this._postProcesses[i];
  4820. }
  4821. add = 1;
  4822. }
  4823. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4824. if (this._postProcessesTakenIndices[i] < insertAt) {
  4825. continue;
  4826. }
  4827. start = this._postProcessesTakenIndices.length - 1;
  4828. for (var j = start; j >= i; --j) {
  4829. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4830. }
  4831. this._postProcessesTakenIndices[i] = insertAt;
  4832. break;
  4833. }
  4834. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4835. this._postProcessesTakenIndices.push(insertAt);
  4836. }
  4837. var result = insertAt + add;
  4838. this._postProcesses[result] = postProcess;
  4839. return result;
  4840. };
  4841. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4842. if (typeof atIndices === "undefined") { atIndices = null; }
  4843. var result = [];
  4844. if (!atIndices) {
  4845. var length = this._postProcesses.length;
  4846. for (var i = 0; i < length; i++) {
  4847. if (this._postProcesses[i] !== postProcess) {
  4848. continue;
  4849. }
  4850. delete this._postProcesses[i];
  4851. var index = this._postProcessesTakenIndices.indexOf(i);
  4852. this._postProcessesTakenIndices.splice(index, 1);
  4853. }
  4854. } else {
  4855. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4856. for (i = 0; i < atIndices.length; i++) {
  4857. var foundPostProcess = this._postProcesses[atIndices[i]];
  4858. if (foundPostProcess !== postProcess) {
  4859. result.push(i);
  4860. continue;
  4861. }
  4862. delete this._postProcesses[atIndices[i]];
  4863. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4864. this._postProcessesTakenIndices.splice(index, 1);
  4865. }
  4866. }
  4867. return result;
  4868. };
  4869. Camera.prototype.getWorldMatrix = function () {
  4870. if (!this._worldMatrix) {
  4871. this._worldMatrix = BABYLON.Matrix.Identity();
  4872. }
  4873. var viewMatrix = this.getViewMatrix();
  4874. viewMatrix.invertToRef(this._worldMatrix);
  4875. return this._worldMatrix;
  4876. };
  4877. Camera.prototype._getViewMatrix = function () {
  4878. return BABYLON.Matrix.Identity();
  4879. };
  4880. Camera.prototype.getViewMatrix = function () {
  4881. this._computedViewMatrix = this._computeViewMatrix();
  4882. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4883. return this._computedViewMatrix;
  4884. }
  4885. if (!this._worldMatrix) {
  4886. this._worldMatrix = BABYLON.Matrix.Identity();
  4887. }
  4888. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4889. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4890. this._computedViewMatrix.invert();
  4891. this._currentRenderId = this.getScene().getRenderId();
  4892. return this._computedViewMatrix;
  4893. };
  4894. Camera.prototype._computeViewMatrix = function (force) {
  4895. if (!force && this._isSynchronizedViewMatrix()) {
  4896. return this._computedViewMatrix;
  4897. }
  4898. this._computedViewMatrix = this._getViewMatrix();
  4899. if (!this.parent || !this.parent.getWorldMatrix) {
  4900. this._currentRenderId = this.getScene().getRenderId();
  4901. }
  4902. return this._computedViewMatrix;
  4903. };
  4904. Camera.prototype.getProjectionMatrix = function (force) {
  4905. if (!force && this._isSynchronizedProjectionMatrix()) {
  4906. return this._projectionMatrix;
  4907. }
  4908. var engine = this.getEngine();
  4909. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4910. if (this.minZ <= 0) {
  4911. this.minZ = 0.1;
  4912. }
  4913. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4914. return this._projectionMatrix;
  4915. }
  4916. var halfWidth = engine.getRenderWidth() / 2.0;
  4917. var halfHeight = engine.getRenderHeight() / 2.0;
  4918. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4919. return this._projectionMatrix;
  4920. };
  4921. Camera.prototype.dispose = function () {
  4922. var index = this.getScene().cameras.indexOf(this);
  4923. this.getScene().cameras.splice(index, 1);
  4924. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4925. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4926. }
  4927. };
  4928. Camera.PERSPECTIVE_CAMERA = 0;
  4929. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4930. return Camera;
  4931. })(BABYLON.Node);
  4932. BABYLON.Camera = Camera;
  4933. })(BABYLON || (BABYLON = {}));
  4934. var __extends = this.__extends || function (d, b) {
  4935. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4936. function __() { this.constructor = d; }
  4937. __.prototype = b.prototype;
  4938. d.prototype = new __();
  4939. };
  4940. var BABYLON;
  4941. (function (BABYLON) {
  4942. var TargetCamera = (function (_super) {
  4943. __extends(TargetCamera, _super);
  4944. function TargetCamera(name, position, scene) {
  4945. _super.call(this, name, position, scene);
  4946. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4947. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4948. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4949. this.speed = 2.0;
  4950. this.noRotationConstraint = false;
  4951. this.lockedTarget = null;
  4952. this._currentTarget = BABYLON.Vector3.Zero();
  4953. this._viewMatrix = BABYLON.Matrix.Zero();
  4954. this._camMatrix = BABYLON.Matrix.Zero();
  4955. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4956. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4957. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4958. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4959. this._lookAtTemp = BABYLON.Matrix.Zero();
  4960. this._tempMatrix = BABYLON.Matrix.Zero();
  4961. }
  4962. TargetCamera.prototype._getLockedTargetPosition = function () {
  4963. if (!this.lockedTarget) {
  4964. return null;
  4965. }
  4966. return this.lockedTarget.position || this.lockedTarget;
  4967. };
  4968. TargetCamera.prototype._initCache = function () {
  4969. _super.prototype._initCache.call(this);
  4970. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4971. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4972. };
  4973. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4974. if (!ignoreParentClass) {
  4975. _super.prototype._updateCache.call(this);
  4976. }
  4977. var lockedTargetPosition = this._getLockedTargetPosition();
  4978. if (!lockedTargetPosition) {
  4979. this._cache.lockedTarget = null;
  4980. } else {
  4981. if (!this._cache.lockedTarget) {
  4982. this._cache.lockedTarget = lockedTargetPosition.clone();
  4983. } else {
  4984. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  4985. }
  4986. }
  4987. this._cache.rotation.copyFrom(this.rotation);
  4988. };
  4989. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  4990. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  4991. return false;
  4992. }
  4993. var lockedTargetPosition = this._getLockedTargetPosition();
  4994. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  4995. };
  4996. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  4997. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  4998. };
  4999. TargetCamera.prototype.setTarget = function (target) {
  5000. this.upVector.normalize();
  5001. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5002. this._camMatrix.invert();
  5003. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5004. var vDir = target.subtract(this.position);
  5005. if (vDir.x >= 0.0) {
  5006. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5007. } else {
  5008. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5009. }
  5010. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5011. if (isNaN(this.rotation.x)) {
  5012. this.rotation.x = 0;
  5013. }
  5014. if (isNaN(this.rotation.y)) {
  5015. this.rotation.y = 0;
  5016. }
  5017. if (isNaN(this.rotation.z)) {
  5018. this.rotation.z = 0;
  5019. }
  5020. };
  5021. TargetCamera.prototype.getTarget = function () {
  5022. return this._currentTarget;
  5023. };
  5024. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5025. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5026. };
  5027. TargetCamera.prototype._updatePosition = function () {
  5028. this.position.addInPlace(this.cameraDirection);
  5029. };
  5030. TargetCamera.prototype._update = function () {
  5031. var needToMove = this._decideIfNeedsToMove();
  5032. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5033. if (needToMove) {
  5034. this._updatePosition();
  5035. }
  5036. if (needToRotate) {
  5037. this.rotation.x += this.cameraRotation.x;
  5038. this.rotation.y += this.cameraRotation.y;
  5039. if (!this.noRotationConstraint) {
  5040. var limit = (Math.PI / 2) * 0.95;
  5041. if (this.rotation.x > limit)
  5042. this.rotation.x = limit;
  5043. if (this.rotation.x < -limit)
  5044. this.rotation.x = -limit;
  5045. }
  5046. }
  5047. if (needToMove) {
  5048. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5049. this.cameraDirection.x = 0;
  5050. }
  5051. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5052. this.cameraDirection.y = 0;
  5053. }
  5054. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5055. this.cameraDirection.z = 0;
  5056. }
  5057. this.cameraDirection.scaleInPlace(this.inertia);
  5058. }
  5059. if (needToRotate) {
  5060. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5061. this.cameraRotation.x = 0;
  5062. }
  5063. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5064. this.cameraRotation.y = 0;
  5065. }
  5066. this.cameraRotation.scaleInPlace(this.inertia);
  5067. }
  5068. };
  5069. TargetCamera.prototype._getViewMatrix = function () {
  5070. if (!this.lockedTarget) {
  5071. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5072. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5073. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5074. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5075. this._lookAtTemp.invert();
  5076. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5077. } else {
  5078. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5079. }
  5080. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5081. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5082. } else {
  5083. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5084. }
  5085. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5086. return this._viewMatrix;
  5087. };
  5088. return TargetCamera;
  5089. })(BABYLON.Camera);
  5090. BABYLON.TargetCamera = TargetCamera;
  5091. })(BABYLON || (BABYLON = {}));
  5092. var __extends = this.__extends || function (d, b) {
  5093. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5094. function __() { this.constructor = d; }
  5095. __.prototype = b.prototype;
  5096. d.prototype = new __();
  5097. };
  5098. var BABYLON;
  5099. (function (BABYLON) {
  5100. var FollowCamera = (function (_super) {
  5101. __extends(FollowCamera, _super);
  5102. function FollowCamera(name, position, scene) {
  5103. _super.call(this, name, position, scene);
  5104. this.radius = 12;
  5105. this.rotationOffset = 0;
  5106. this.heightOffset = 4;
  5107. this.cameraAcceleration = 0.05;
  5108. this.maxCameraSpeed = 20;
  5109. }
  5110. FollowCamera.prototype.getRadians = function (degrees) {
  5111. return degrees * Math.PI / 180;
  5112. };
  5113. FollowCamera.prototype.follow = function (cameraTarget) {
  5114. if (!cameraTarget)
  5115. return;
  5116. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5117. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5118. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5119. var dx = targetX - this.position.x;
  5120. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5121. var dz = (targetZ) - this.position.z;
  5122. var vx = dx * this.cameraAcceleration * 2;
  5123. var vy = dy * this.cameraAcceleration;
  5124. var vz = dz * this.cameraAcceleration * 2;
  5125. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5126. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5127. }
  5128. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5129. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5130. }
  5131. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5132. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5133. }
  5134. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5135. this.setTarget(cameraTarget.position);
  5136. };
  5137. FollowCamera.prototype._update = function () {
  5138. _super.prototype._update.call(this);
  5139. this.follow(this.target);
  5140. };
  5141. return FollowCamera;
  5142. })(BABYLON.TargetCamera);
  5143. BABYLON.FollowCamera = FollowCamera;
  5144. })(BABYLON || (BABYLON = {}));
  5145. var __extends = this.__extends || function (d, b) {
  5146. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5147. function __() { this.constructor = d; }
  5148. __.prototype = b.prototype;
  5149. d.prototype = new __();
  5150. };
  5151. var BABYLON;
  5152. (function (BABYLON) {
  5153. var FreeCamera = (function (_super) {
  5154. __extends(FreeCamera, _super);
  5155. function FreeCamera(name, position, scene) {
  5156. _super.call(this, name, position, scene);
  5157. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5158. this.keysUp = [38];
  5159. this.keysDown = [40];
  5160. this.keysLeft = [37];
  5161. this.keysRight = [39];
  5162. this.checkCollisions = false;
  5163. this.applyGravity = false;
  5164. this.angularSensibility = 2000.0;
  5165. this._keys = [];
  5166. this._collider = new BABYLON.Collider();
  5167. this._needMoveForGravity = true;
  5168. this._oldPosition = BABYLON.Vector3.Zero();
  5169. this._diffPosition = BABYLON.Vector3.Zero();
  5170. this._newPosition = BABYLON.Vector3.Zero();
  5171. }
  5172. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5173. var _this = this;
  5174. var previousPosition;
  5175. var engine = this.getEngine();
  5176. if (this._attachedElement) {
  5177. return;
  5178. }
  5179. this._attachedElement = element;
  5180. if (this._onMouseDown === undefined) {
  5181. this._onMouseDown = function (evt) {
  5182. previousPosition = {
  5183. x: evt.clientX,
  5184. y: evt.clientY
  5185. };
  5186. if (!noPreventDefault) {
  5187. evt.preventDefault();
  5188. }
  5189. };
  5190. this._onMouseUp = function (evt) {
  5191. previousPosition = null;
  5192. if (!noPreventDefault) {
  5193. evt.preventDefault();
  5194. }
  5195. };
  5196. this._onMouseOut = function (evt) {
  5197. previousPosition = null;
  5198. _this._keys = [];
  5199. if (!noPreventDefault) {
  5200. evt.preventDefault();
  5201. }
  5202. };
  5203. this._onMouseMove = function (evt) {
  5204. if (!previousPosition && !engine.isPointerLock) {
  5205. return;
  5206. }
  5207. var offsetX;
  5208. var offsetY;
  5209. if (!engine.isPointerLock) {
  5210. offsetX = evt.clientX - previousPosition.x;
  5211. offsetY = evt.clientY - previousPosition.y;
  5212. } else {
  5213. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5214. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5215. }
  5216. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5217. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5218. previousPosition = {
  5219. x: evt.clientX,
  5220. y: evt.clientY
  5221. };
  5222. if (!noPreventDefault) {
  5223. evt.preventDefault();
  5224. }
  5225. };
  5226. this._onKeyDown = function (evt) {
  5227. 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) {
  5228. var index = _this._keys.indexOf(evt.keyCode);
  5229. if (index === -1) {
  5230. _this._keys.push(evt.keyCode);
  5231. }
  5232. if (!noPreventDefault) {
  5233. evt.preventDefault();
  5234. }
  5235. }
  5236. };
  5237. this._onKeyUp = function (evt) {
  5238. 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) {
  5239. var index = _this._keys.indexOf(evt.keyCode);
  5240. if (index >= 0) {
  5241. _this._keys.splice(index, 1);
  5242. }
  5243. if (!noPreventDefault) {
  5244. evt.preventDefault();
  5245. }
  5246. }
  5247. };
  5248. this._onLostFocus = function () {
  5249. _this._keys = [];
  5250. };
  5251. this._reset = function () {
  5252. _this._keys = [];
  5253. previousPosition = null;
  5254. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5255. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5256. };
  5257. }
  5258. element.addEventListener("mousedown", this._onMouseDown, false);
  5259. element.addEventListener("mouseup", this._onMouseUp, false);
  5260. element.addEventListener("mouseout", this._onMouseOut, false);
  5261. element.addEventListener("mousemove", this._onMouseMove, false);
  5262. BABYLON.Tools.RegisterTopRootEvents([
  5263. { name: "keydown", handler: this._onKeyDown },
  5264. { name: "keyup", handler: this._onKeyUp },
  5265. { name: "blur", handler: this._onLostFocus }
  5266. ]);
  5267. };
  5268. FreeCamera.prototype.detachControl = function (element) {
  5269. if (this._attachedElement != element) {
  5270. return;
  5271. }
  5272. element.removeEventListener("mousedown", this._onMouseDown);
  5273. element.removeEventListener("mouseup", this._onMouseUp);
  5274. element.removeEventListener("mouseout", this._onMouseOut);
  5275. element.removeEventListener("mousemove", this._onMouseMove);
  5276. BABYLON.Tools.UnregisterTopRootEvents([
  5277. { name: "keydown", handler: this._onKeyDown },
  5278. { name: "keyup", handler: this._onKeyUp },
  5279. { name: "blur", handler: this._onLostFocus }
  5280. ]);
  5281. this._attachedElement = null;
  5282. if (this._reset) {
  5283. this._reset();
  5284. }
  5285. };
  5286. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5287. var globalPosition;
  5288. if (this.parent) {
  5289. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5290. } else {
  5291. globalPosition = this.position;
  5292. }
  5293. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5294. this._collider.radius = this.ellipsoid;
  5295. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5296. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5297. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5298. this.position.addInPlace(this._diffPosition);
  5299. if (this.onCollide) {
  5300. this.onCollide(this._collider.collidedMesh);
  5301. }
  5302. }
  5303. };
  5304. FreeCamera.prototype._checkInputs = function () {
  5305. if (!this._localDirection) {
  5306. this._localDirection = BABYLON.Vector3.Zero();
  5307. this._transformedDirection = BABYLON.Vector3.Zero();
  5308. }
  5309. for (var index = 0; index < this._keys.length; index++) {
  5310. var keyCode = this._keys[index];
  5311. var speed = this._computeLocalCameraSpeed();
  5312. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5313. this._localDirection.copyFromFloats(-speed, 0, 0);
  5314. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5315. this._localDirection.copyFromFloats(0, 0, speed);
  5316. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5317. this._localDirection.copyFromFloats(speed, 0, 0);
  5318. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5319. this._localDirection.copyFromFloats(0, 0, -speed);
  5320. }
  5321. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5322. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5323. this.cameraDirection.addInPlace(this._transformedDirection);
  5324. }
  5325. };
  5326. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5327. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5328. };
  5329. FreeCamera.prototype._updatePosition = function () {
  5330. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5331. this._collideWithWorld(this.cameraDirection);
  5332. if (this.applyGravity) {
  5333. var oldPosition = this.position;
  5334. this._collideWithWorld(this.getScene().gravity);
  5335. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5336. }
  5337. } else {
  5338. this.position.addInPlace(this.cameraDirection);
  5339. }
  5340. };
  5341. FreeCamera.prototype._update = function () {
  5342. this._checkInputs();
  5343. _super.prototype._update.call(this);
  5344. };
  5345. return FreeCamera;
  5346. })(BABYLON.TargetCamera);
  5347. BABYLON.FreeCamera = FreeCamera;
  5348. })(BABYLON || (BABYLON = {}));
  5349. var __extends = this.__extends || function (d, b) {
  5350. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5351. function __() { this.constructor = d; }
  5352. __.prototype = b.prototype;
  5353. d.prototype = new __();
  5354. };
  5355. var BABYLON;
  5356. (function (BABYLON) {
  5357. var TouchCamera = (function (_super) {
  5358. __extends(TouchCamera, _super);
  5359. function TouchCamera(name, position, scene) {
  5360. _super.call(this, name, position, scene);
  5361. this._offsetX = null;
  5362. this._offsetY = null;
  5363. this._pointerCount = 0;
  5364. this._pointerPressed = [];
  5365. this.angularSensibility = 200000.0;
  5366. this.moveSensibility = 500.0;
  5367. }
  5368. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5369. var _this = this;
  5370. var previousPosition;
  5371. if (this._attachedCanvas) {
  5372. return;
  5373. }
  5374. this._attachedCanvas = canvas;
  5375. if (this._onPointerDown === undefined) {
  5376. this._onPointerDown = function (evt) {
  5377. if (!noPreventDefault) {
  5378. evt.preventDefault();
  5379. }
  5380. _this._pointerPressed.push(evt.pointerId);
  5381. if (_this._pointerPressed.length !== 1) {
  5382. return;
  5383. }
  5384. previousPosition = {
  5385. x: evt.clientX,
  5386. y: evt.clientY
  5387. };
  5388. };
  5389. this._onPointerUp = function (evt) {
  5390. if (!noPreventDefault) {
  5391. evt.preventDefault();
  5392. }
  5393. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5394. if (index === -1) {
  5395. return;
  5396. }
  5397. _this._pointerPressed.splice(index, 1);
  5398. if (index != 0) {
  5399. return;
  5400. }
  5401. previousPosition = null;
  5402. _this._offsetX = null;
  5403. _this._offsetY = null;
  5404. };
  5405. this._onPointerMove = function (evt) {
  5406. if (!noPreventDefault) {
  5407. evt.preventDefault();
  5408. }
  5409. if (!previousPosition) {
  5410. return;
  5411. }
  5412. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5413. if (index != 0) {
  5414. return;
  5415. }
  5416. _this._offsetX = evt.clientX - previousPosition.x;
  5417. _this._offsetY = -(evt.clientY - previousPosition.y);
  5418. };
  5419. this._onLostFocus = function () {
  5420. _this._offsetX = null;
  5421. _this._offsetY = null;
  5422. };
  5423. }
  5424. canvas.addEventListener("pointerdown", this._onPointerDown);
  5425. canvas.addEventListener("pointerup", this._onPointerUp);
  5426. canvas.addEventListener("pointerout", this._onPointerUp);
  5427. canvas.addEventListener("pointermove", this._onPointerMove);
  5428. BABYLON.Tools.RegisterTopRootEvents([
  5429. { name: "blur", handler: this._onLostFocus }
  5430. ]);
  5431. };
  5432. TouchCamera.prototype.detachControl = function (canvas) {
  5433. if (this._attachedCanvas != canvas) {
  5434. return;
  5435. }
  5436. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5437. canvas.removeEventListener("pointerup", this._onPointerUp);
  5438. canvas.removeEventListener("pointerout", this._onPointerUp);
  5439. canvas.removeEventListener("pointermove", this._onPointerMove);
  5440. BABYLON.Tools.UnregisterTopRootEvents([
  5441. { name: "blur", handler: this._onLostFocus }
  5442. ]);
  5443. this._attachedCanvas = null;
  5444. };
  5445. TouchCamera.prototype._checkInputs = function () {
  5446. if (!this._offsetX) {
  5447. return;
  5448. }
  5449. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5450. if (this._pointerPressed.length > 1) {
  5451. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5452. } else {
  5453. var speed = this._computeLocalCameraSpeed();
  5454. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5455. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5456. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5457. }
  5458. };
  5459. return TouchCamera;
  5460. })(BABYLON.FreeCamera);
  5461. BABYLON.TouchCamera = TouchCamera;
  5462. })(BABYLON || (BABYLON = {}));
  5463. var __extends = this.__extends || function (d, b) {
  5464. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5465. function __() { this.constructor = d; }
  5466. __.prototype = b.prototype;
  5467. d.prototype = new __();
  5468. };
  5469. var BABYLON;
  5470. (function (BABYLON) {
  5471. var DeviceOrientationCamera = (function (_super) {
  5472. __extends(DeviceOrientationCamera, _super);
  5473. function DeviceOrientationCamera(name, position, scene) {
  5474. var _this = this;
  5475. _super.call(this, name, position, scene);
  5476. this._offsetX = null;
  5477. this._offsetY = null;
  5478. this._orientationGamma = 0;
  5479. this._orientationBeta = 0;
  5480. this._initialOrientationGamma = 0;
  5481. this._initialOrientationBeta = 0;
  5482. this.angularSensibility = 10000.0;
  5483. this.moveSensibility = 50.0;
  5484. window.addEventListener("resize", function () {
  5485. _this._initialOrientationGamma = null;
  5486. }, false);
  5487. }
  5488. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5489. var _this = this;
  5490. if (this._attachedCanvas) {
  5491. return;
  5492. }
  5493. this._attachedCanvas = canvas;
  5494. if (!this._orientationChanged) {
  5495. this._orientationChanged = function (evt) {
  5496. if (!_this._initialOrientationGamma) {
  5497. _this._initialOrientationGamma = evt.gamma;
  5498. _this._initialOrientationBeta = evt.beta;
  5499. }
  5500. _this._orientationGamma = evt.gamma;
  5501. _this._orientationBeta = evt.beta;
  5502. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5503. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5504. };
  5505. }
  5506. window.addEventListener("deviceorientation", this._orientationChanged);
  5507. };
  5508. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5509. if (this._attachedCanvas != canvas) {
  5510. return;
  5511. }
  5512. window.removeEventListener("deviceorientation", this._orientationChanged);
  5513. this._attachedCanvas = null;
  5514. this._orientationGamma = 0;
  5515. this._orientationBeta = 0;
  5516. this._initialOrientationGamma = 0;
  5517. this._initialOrientationBeta = 0;
  5518. };
  5519. DeviceOrientationCamera.prototype._checkInputs = function () {
  5520. if (!this._offsetX) {
  5521. return;
  5522. }
  5523. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5524. var speed = this._computeLocalCameraSpeed();
  5525. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5526. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5527. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5528. };
  5529. return DeviceOrientationCamera;
  5530. })(BABYLON.FreeCamera);
  5531. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5532. })(BABYLON || (BABYLON = {}));
  5533. var __extends = this.__extends || function (d, b) {
  5534. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5535. function __() { this.constructor = d; }
  5536. __.prototype = b.prototype;
  5537. d.prototype = new __();
  5538. };
  5539. var BABYLON;
  5540. (function (BABYLON) {
  5541. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5542. var ArcRotateCamera = (function (_super) {
  5543. __extends(ArcRotateCamera, _super);
  5544. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5545. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5546. this.alpha = alpha;
  5547. this.beta = beta;
  5548. this.radius = radius;
  5549. this.target = target;
  5550. this.inertialAlphaOffset = 0;
  5551. this.inertialBetaOffset = 0;
  5552. this.inertialRadiusOffset = 0;
  5553. this.lowerAlphaLimit = null;
  5554. this.upperAlphaLimit = null;
  5555. this.lowerBetaLimit = 0.01;
  5556. this.upperBetaLimit = Math.PI;
  5557. this.lowerRadiusLimit = null;
  5558. this.upperRadiusLimit = null;
  5559. this.angularSensibility = 1000.0;
  5560. this.wheelPrecision = 3.0;
  5561. this.keysUp = [38];
  5562. this.keysDown = [40];
  5563. this.keysLeft = [37];
  5564. this.keysRight = [39];
  5565. this.zoomOnFactor = 1;
  5566. this._keys = [];
  5567. this._viewMatrix = new BABYLON.Matrix();
  5568. this.checkCollisions = false;
  5569. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5570. this._collider = new BABYLON.Collider();
  5571. this._previousPosition = BABYLON.Vector3.Zero();
  5572. this._collisionVelocity = BABYLON.Vector3.Zero();
  5573. this._newPosition = BABYLON.Vector3.Zero();
  5574. this.getViewMatrix();
  5575. }
  5576. ArcRotateCamera.prototype._getTargetPosition = function () {
  5577. return this.target.position || this.target;
  5578. };
  5579. ArcRotateCamera.prototype._initCache = function () {
  5580. _super.prototype._initCache.call(this);
  5581. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5582. this._cache.alpha = undefined;
  5583. this._cache.beta = undefined;
  5584. this._cache.radius = undefined;
  5585. };
  5586. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5587. if (!ignoreParentClass) {
  5588. _super.prototype._updateCache.call(this);
  5589. }
  5590. this._cache.target.copyFrom(this._getTargetPosition());
  5591. this._cache.alpha = this.alpha;
  5592. this._cache.beta = this.beta;
  5593. this._cache.radius = this.radius;
  5594. };
  5595. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5596. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5597. return false;
  5598. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5599. };
  5600. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5601. var _this = this;
  5602. var previousPosition;
  5603. var pointerId;
  5604. if (this._attachedElement) {
  5605. return;
  5606. }
  5607. this._attachedElement = element;
  5608. var engine = this.getEngine();
  5609. if (this._onPointerDown === undefined) {
  5610. this._onPointerDown = function (evt) {
  5611. if (pointerId) {
  5612. return;
  5613. }
  5614. pointerId = evt.pointerId;
  5615. previousPosition = {
  5616. x: evt.clientX,
  5617. y: evt.clientY
  5618. };
  5619. if (!noPreventDefault) {
  5620. evt.preventDefault();
  5621. }
  5622. };
  5623. this._onPointerUp = function (evt) {
  5624. previousPosition = null;
  5625. pointerId = null;
  5626. if (!noPreventDefault) {
  5627. evt.preventDefault();
  5628. }
  5629. };
  5630. this._onPointerMove = function (evt) {
  5631. if (!previousPosition) {
  5632. return;
  5633. }
  5634. if (pointerId !== evt.pointerId) {
  5635. return;
  5636. }
  5637. var offsetX = evt.clientX - previousPosition.x;
  5638. var offsetY = evt.clientY - previousPosition.y;
  5639. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5640. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5641. previousPosition = {
  5642. x: evt.clientX,
  5643. y: evt.clientY
  5644. };
  5645. if (!noPreventDefault) {
  5646. evt.preventDefault();
  5647. }
  5648. };
  5649. this._onMouseMove = function (evt) {
  5650. if (!engine.isPointerLock) {
  5651. return;
  5652. }
  5653. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5654. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5655. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5656. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5657. if (!noPreventDefault) {
  5658. evt.preventDefault();
  5659. }
  5660. };
  5661. this._wheel = function (event) {
  5662. var delta = 0;
  5663. if (event.wheelDelta) {
  5664. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5665. } else if (event.detail) {
  5666. delta = -event.detail / _this.wheelPrecision;
  5667. }
  5668. if (delta)
  5669. _this.inertialRadiusOffset += delta;
  5670. if (event.preventDefault) {
  5671. if (!noPreventDefault) {
  5672. event.preventDefault();
  5673. }
  5674. }
  5675. };
  5676. this._onKeyDown = function (evt) {
  5677. 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) {
  5678. var index = _this._keys.indexOf(evt.keyCode);
  5679. if (index === -1) {
  5680. _this._keys.push(evt.keyCode);
  5681. }
  5682. if (evt.preventDefault) {
  5683. if (!noPreventDefault) {
  5684. evt.preventDefault();
  5685. }
  5686. }
  5687. }
  5688. };
  5689. this._onKeyUp = function (evt) {
  5690. 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) {
  5691. var index = _this._keys.indexOf(evt.keyCode);
  5692. if (index >= 0) {
  5693. _this._keys.splice(index, 1);
  5694. }
  5695. if (evt.preventDefault) {
  5696. if (!noPreventDefault) {
  5697. evt.preventDefault();
  5698. }
  5699. }
  5700. }
  5701. };
  5702. this._onLostFocus = function () {
  5703. _this._keys = [];
  5704. pointerId = null;
  5705. };
  5706. this._onGestureStart = function (e) {
  5707. if (window.MSGesture === undefined) {
  5708. return;
  5709. }
  5710. if (!_this._MSGestureHandler) {
  5711. _this._MSGestureHandler = new MSGesture();
  5712. _this._MSGestureHandler.target = element;
  5713. }
  5714. _this._MSGestureHandler.addPointer(e.pointerId);
  5715. };
  5716. this._onGesture = function (e) {
  5717. _this.radius *= e.scale;
  5718. if (e.preventDefault) {
  5719. if (!noPreventDefault) {
  5720. e.stopPropagation();
  5721. e.preventDefault();
  5722. }
  5723. }
  5724. };
  5725. this._reset = function () {
  5726. _this._keys = [];
  5727. _this.inertialAlphaOffset = 0;
  5728. _this.inertialBetaOffset = 0;
  5729. _this.inertialRadiusOffset = 0;
  5730. previousPosition = null;
  5731. pointerId = null;
  5732. };
  5733. }
  5734. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5735. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5736. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5737. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5738. element.addEventListener("mousemove", this._onMouseMove, false);
  5739. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5740. element.addEventListener("MSGestureChange", this._onGesture, false);
  5741. element.addEventListener('mousewheel', this._wheel, false);
  5742. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5743. BABYLON.Tools.RegisterTopRootEvents([
  5744. { name: "keydown", handler: this._onKeyDown },
  5745. { name: "keyup", handler: this._onKeyUp },
  5746. { name: "blur", handler: this._onLostFocus }
  5747. ]);
  5748. };
  5749. ArcRotateCamera.prototype.detachControl = function (element) {
  5750. if (this._attachedElement != element) {
  5751. return;
  5752. }
  5753. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5754. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5755. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5756. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5757. element.removeEventListener("mousemove", this._onMouseMove);
  5758. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5759. element.removeEventListener("MSGestureChange", this._onGesture);
  5760. element.removeEventListener('mousewheel', this._wheel);
  5761. element.removeEventListener('DOMMouseScroll', this._wheel);
  5762. BABYLON.Tools.UnregisterTopRootEvents([
  5763. { name: "keydown", handler: this._onKeyDown },
  5764. { name: "keyup", handler: this._onKeyUp },
  5765. { name: "blur", handler: this._onLostFocus }
  5766. ]);
  5767. this._MSGestureHandler = null;
  5768. this._attachedElement = null;
  5769. if (this._reset) {
  5770. this._reset();
  5771. }
  5772. };
  5773. ArcRotateCamera.prototype._update = function () {
  5774. for (var index = 0; index < this._keys.length; index++) {
  5775. var keyCode = this._keys[index];
  5776. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5777. this.inertialAlphaOffset -= 0.01;
  5778. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5779. this.inertialBetaOffset -= 0.01;
  5780. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5781. this.inertialAlphaOffset += 0.01;
  5782. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5783. this.inertialBetaOffset += 0.01;
  5784. }
  5785. }
  5786. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5787. this.alpha += this.inertialAlphaOffset;
  5788. this.beta += this.inertialBetaOffset;
  5789. this.radius -= this.inertialRadiusOffset;
  5790. this.inertialAlphaOffset *= this.inertia;
  5791. this.inertialBetaOffset *= this.inertia;
  5792. this.inertialRadiusOffset *= this.inertia;
  5793. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5794. this.inertialAlphaOffset = 0;
  5795. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5796. this.inertialBetaOffset = 0;
  5797. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5798. this.inertialRadiusOffset = 0;
  5799. }
  5800. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5801. this.alpha = this.lowerAlphaLimit;
  5802. }
  5803. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5804. this.alpha = this.upperAlphaLimit;
  5805. }
  5806. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5807. this.beta = this.lowerBetaLimit;
  5808. }
  5809. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5810. this.beta = this.upperBetaLimit;
  5811. }
  5812. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5813. this.radius = this.lowerRadiusLimit;
  5814. }
  5815. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5816. this.radius = this.upperRadiusLimit;
  5817. }
  5818. };
  5819. ArcRotateCamera.prototype.setPosition = function (position) {
  5820. var radiusv3 = position.subtract(this._getTargetPosition());
  5821. this.radius = radiusv3.length();
  5822. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5823. if (radiusv3.z < 0) {
  5824. this.alpha = 2 * Math.PI - this.alpha;
  5825. }
  5826. this.beta = Math.acos(radiusv3.y / this.radius);
  5827. };
  5828. ArcRotateCamera.prototype._getViewMatrix = function () {
  5829. var cosa = Math.cos(this.alpha);
  5830. var sina = Math.sin(this.alpha);
  5831. var cosb = Math.cos(this.beta);
  5832. var sinb = Math.sin(this.beta);
  5833. var target = this._getTargetPosition();
  5834. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5835. if (this.checkCollisions) {
  5836. this._collider.radius = this.collisionRadius;
  5837. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5838. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5839. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5840. this.position.copyFrom(this._previousPosition);
  5841. this.alpha = this._previousAlpha;
  5842. this.beta = this._previousBeta;
  5843. this.radius = this._previousRadius;
  5844. if (this.onCollide) {
  5845. this.onCollide(this._collider.collidedMesh);
  5846. }
  5847. }
  5848. }
  5849. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5850. this._previousAlpha = this.alpha;
  5851. this._previousBeta = this.beta;
  5852. this._previousRadius = this.radius;
  5853. this._previousPosition.copyFrom(this.position);
  5854. return this._viewMatrix;
  5855. };
  5856. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5857. meshes = meshes || this.getScene().meshes;
  5858. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5859. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5860. this.radius = distance * this.zoomOnFactor;
  5861. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5862. };
  5863. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5864. var meshesOrMinMaxVector;
  5865. var distance;
  5866. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5867. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5868. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5869. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5870. } else {
  5871. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5872. distance = meshesOrMinMaxVectorAndDistance.distance;
  5873. }
  5874. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5875. this.maxZ = distance * 2;
  5876. };
  5877. return ArcRotateCamera;
  5878. })(BABYLON.Camera);
  5879. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5880. })(BABYLON || (BABYLON = {}));
  5881. var BABYLON;
  5882. (function (BABYLON) {
  5883. var Scene = (function () {
  5884. function Scene(engine) {
  5885. this.autoClear = true;
  5886. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5887. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5888. this.forceWireframe = false;
  5889. this.cameraToUseForPointers = null;
  5890. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5891. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5892. this.fogDensity = 0.1;
  5893. this.fogStart = 0;
  5894. this.fogEnd = 1000.0;
  5895. this.lightsEnabled = true;
  5896. this.lights = new Array();
  5897. this.cameras = new Array();
  5898. this.activeCameras = new Array();
  5899. this.meshes = new Array();
  5900. this._geometries = new Array();
  5901. this.materials = new Array();
  5902. this.multiMaterials = new Array();
  5903. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5904. this.texturesEnabled = true;
  5905. this.textures = new Array();
  5906. this.particlesEnabled = true;
  5907. this.particleSystems = new Array();
  5908. this.spriteManagers = new Array();
  5909. this.layers = new Array();
  5910. this.skeletons = new Array();
  5911. this.lensFlareSystems = new Array();
  5912. this.collisionsEnabled = true;
  5913. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5914. this.postProcessesEnabled = true;
  5915. this.renderTargetsEnabled = true;
  5916. this.customRenderTargets = new Array();
  5917. this.importedMeshesFiles = new Array();
  5918. this._actionManagers = new Array();
  5919. this._meshesForIntersections = new BABYLON.SmartArray(256);
  5920. this._totalVertices = 0;
  5921. this._activeVertices = 0;
  5922. this._activeParticles = 0;
  5923. this._lastFrameDuration = 0;
  5924. this._evaluateActiveMeshesDuration = 0;
  5925. this._renderTargetsDuration = 0;
  5926. this._particlesDuration = 0;
  5927. this._renderDuration = 0;
  5928. this._spritesDuration = 0;
  5929. this._animationRatio = 0;
  5930. this._renderId = 0;
  5931. this._executeWhenReadyTimeoutId = -1;
  5932. this._toBeDisposed = new BABYLON.SmartArray(256);
  5933. this._onReadyCallbacks = new Array();
  5934. this._pendingData = [];
  5935. this._onBeforeRenderCallbacks = new Array();
  5936. this._activeMeshes = new BABYLON.SmartArray(256);
  5937. this._processedMaterials = new BABYLON.SmartArray(256);
  5938. this._renderTargets = new BABYLON.SmartArray(256);
  5939. this._activeParticleSystems = new BABYLON.SmartArray(256);
  5940. this._activeSkeletons = new BABYLON.SmartArray(32);
  5941. this._activeAnimatables = new Array();
  5942. this._transformMatrix = BABYLON.Matrix.Zero();
  5943. this._scaledPosition = BABYLON.Vector3.Zero();
  5944. this._scaledVelocity = BABYLON.Vector3.Zero();
  5945. this._engine = engine;
  5946. engine.scenes.push(this);
  5947. this._renderingManager = new BABYLON.RenderingManager(this);
  5948. this.postProcessManager = new BABYLON.PostProcessManager(this);
  5949. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  5950. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  5951. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  5952. this.attachControl();
  5953. }
  5954. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  5955. get: function () {
  5956. return this._meshUnderPointer;
  5957. },
  5958. enumerable: true,
  5959. configurable: true
  5960. });
  5961. Object.defineProperty(Scene.prototype, "pointerX", {
  5962. get: function () {
  5963. return this._pointerX;
  5964. },
  5965. enumerable: true,
  5966. configurable: true
  5967. });
  5968. Object.defineProperty(Scene.prototype, "pointerY", {
  5969. get: function () {
  5970. return this._pointerY;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. Scene.prototype.getBoundingBoxRenderer = function () {
  5976. return this._boundingBoxRenderer;
  5977. };
  5978. Scene.prototype.getOutlineRenderer = function () {
  5979. return this._outlineRenderer;
  5980. };
  5981. Scene.prototype.getEngine = function () {
  5982. return this._engine;
  5983. };
  5984. Scene.prototype.getTotalVertices = function () {
  5985. return this._totalVertices;
  5986. };
  5987. Scene.prototype.getActiveVertices = function () {
  5988. return this._activeVertices;
  5989. };
  5990. Scene.prototype.getActiveParticles = function () {
  5991. return this._activeParticles;
  5992. };
  5993. Scene.prototype.getLastFrameDuration = function () {
  5994. return this._lastFrameDuration;
  5995. };
  5996. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  5997. return this._evaluateActiveMeshesDuration;
  5998. };
  5999. Scene.prototype.getActiveMeshes = function () {
  6000. return this._activeMeshes;
  6001. };
  6002. Scene.prototype.getRenderTargetsDuration = function () {
  6003. return this._renderTargetsDuration;
  6004. };
  6005. Scene.prototype.getRenderDuration = function () {
  6006. return this._renderDuration;
  6007. };
  6008. Scene.prototype.getParticlesDuration = function () {
  6009. return this._particlesDuration;
  6010. };
  6011. Scene.prototype.getSpritesDuration = function () {
  6012. return this._spritesDuration;
  6013. };
  6014. Scene.prototype.getAnimationRatio = function () {
  6015. return this._animationRatio;
  6016. };
  6017. Scene.prototype.getRenderId = function () {
  6018. return this._renderId;
  6019. };
  6020. Scene.prototype._updatePointerPosition = function (evt) {
  6021. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6022. this._pointerX = evt.clientX - canvasRect.left;
  6023. this._pointerY = evt.clientY - canvasRect.top;
  6024. if (this.cameraToUseForPointers) {
  6025. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6026. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6027. }
  6028. };
  6029. Scene.prototype.attachControl = function () {
  6030. var _this = this;
  6031. this._onPointerMove = function (evt) {
  6032. var canvas = _this._engine.getRenderingCanvas();
  6033. _this._updatePointerPosition(evt);
  6034. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6035. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6036. }, false, _this.cameraToUseForPointers);
  6037. if (pickResult.hit) {
  6038. _this._meshUnderPointer = pickResult.pickedMesh;
  6039. _this.setPointerOverMesh(pickResult.pickedMesh);
  6040. canvas.style.cursor = "pointer";
  6041. } else {
  6042. _this.setPointerOverMesh(null);
  6043. canvas.style.cursor = "";
  6044. _this._meshUnderPointer = null;
  6045. }
  6046. };
  6047. this._onPointerDown = function (evt) {
  6048. var predicate = null;
  6049. if (!_this.onPointerDown) {
  6050. predicate = function (mesh) {
  6051. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6052. };
  6053. }
  6054. _this._updatePointerPosition(evt);
  6055. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6056. if (pickResult.hit) {
  6057. if (pickResult.pickedMesh.actionManager) {
  6058. switch (evt.button) {
  6059. case 0:
  6060. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6061. break;
  6062. case 1:
  6063. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6064. break;
  6065. case 2:
  6066. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6067. break;
  6068. }
  6069. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6070. }
  6071. }
  6072. if (_this.onPointerDown) {
  6073. _this.onPointerDown(evt, pickResult);
  6074. }
  6075. };
  6076. this._onKeyDown = function (evt) {
  6077. if (_this.actionManager) {
  6078. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6079. }
  6080. };
  6081. this._onKeyUp = function (evt) {
  6082. if (_this.actionManager) {
  6083. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6084. }
  6085. };
  6086. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6087. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6088. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6089. window.addEventListener("keydown", this._onKeyDown, false);
  6090. window.addEventListener("keyup", this._onKeyUp, false);
  6091. };
  6092. Scene.prototype.detachControl = function () {
  6093. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6094. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6095. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6096. window.removeEventListener("keydown", this._onKeyDown);
  6097. window.removeEventListener("keyup", this._onKeyUp);
  6098. };
  6099. Scene.prototype.isReady = function () {
  6100. if (this._pendingData.length > 0) {
  6101. return false;
  6102. }
  6103. for (var index = 0; index < this._geometries.length; index++) {
  6104. var geometry = this._geometries[index];
  6105. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6106. return false;
  6107. }
  6108. }
  6109. for (index = 0; index < this.meshes.length; index++) {
  6110. var mesh = this.meshes[index];
  6111. if (!mesh.isReady()) {
  6112. return false;
  6113. }
  6114. var mat = mesh.material;
  6115. if (mat) {
  6116. if (!mat.isReady(mesh)) {
  6117. return false;
  6118. }
  6119. }
  6120. }
  6121. return true;
  6122. };
  6123. Scene.prototype.registerBeforeRender = function (func) {
  6124. this._onBeforeRenderCallbacks.push(func);
  6125. };
  6126. Scene.prototype.unregisterBeforeRender = function (func) {
  6127. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6128. if (index > -1) {
  6129. this._onBeforeRenderCallbacks.splice(index, 1);
  6130. }
  6131. };
  6132. Scene.prototype._addPendingData = function (data) {
  6133. this._pendingData.push(data);
  6134. };
  6135. Scene.prototype._removePendingData = function (data) {
  6136. var index = this._pendingData.indexOf(data);
  6137. if (index !== -1) {
  6138. this._pendingData.splice(index, 1);
  6139. }
  6140. };
  6141. Scene.prototype.getWaitingItemsCount = function () {
  6142. return this._pendingData.length;
  6143. };
  6144. Scene.prototype.executeWhenReady = function (func) {
  6145. var _this = this;
  6146. this._onReadyCallbacks.push(func);
  6147. if (this._executeWhenReadyTimeoutId !== -1) {
  6148. return;
  6149. }
  6150. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6151. _this._checkIsReady();
  6152. }, 150);
  6153. };
  6154. Scene.prototype._checkIsReady = function () {
  6155. var _this = this;
  6156. if (this.isReady()) {
  6157. this._onReadyCallbacks.forEach(function (func) {
  6158. func();
  6159. });
  6160. this._onReadyCallbacks = [];
  6161. this._executeWhenReadyTimeoutId = -1;
  6162. return;
  6163. }
  6164. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6165. _this._checkIsReady();
  6166. }, 150);
  6167. };
  6168. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6169. if (speedRatio === undefined) {
  6170. speedRatio = 1.0;
  6171. }
  6172. this.stopAnimation(target);
  6173. if (!animatable) {
  6174. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6175. }
  6176. if (target.animations) {
  6177. animatable.appendAnimations(target, target.animations);
  6178. }
  6179. if (target.getAnimatables) {
  6180. var animatables = target.getAnimatables();
  6181. for (var index = 0; index < animatables.length; index++) {
  6182. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6183. }
  6184. }
  6185. return animatable;
  6186. };
  6187. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6188. if (speedRatio === undefined) {
  6189. speedRatio = 1.0;
  6190. }
  6191. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6192. return animatable;
  6193. };
  6194. Scene.prototype.getAnimatableByTarget = function (target) {
  6195. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6196. if (this._activeAnimatables[index].target === target) {
  6197. return this._activeAnimatables[index];
  6198. }
  6199. }
  6200. return null;
  6201. };
  6202. Scene.prototype.stopAnimation = function (target) {
  6203. var animatable = this.getAnimatableByTarget(target);
  6204. if (animatable) {
  6205. animatable.stop();
  6206. }
  6207. };
  6208. Scene.prototype._animate = function () {
  6209. if (!this._animationStartDate) {
  6210. this._animationStartDate = new Date().getTime();
  6211. }
  6212. var now = new Date().getTime();
  6213. var delay = now - this._animationStartDate;
  6214. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6215. if (!this._activeAnimatables[index]._animate(delay)) {
  6216. this._activeAnimatables.splice(index, 1);
  6217. index--;
  6218. }
  6219. }
  6220. };
  6221. Scene.prototype.getViewMatrix = function () {
  6222. return this._viewMatrix;
  6223. };
  6224. Scene.prototype.getProjectionMatrix = function () {
  6225. return this._projectionMatrix;
  6226. };
  6227. Scene.prototype.getTransformMatrix = function () {
  6228. return this._transformMatrix;
  6229. };
  6230. Scene.prototype.setTransformMatrix = function (view, projection) {
  6231. this._viewMatrix = view;
  6232. this._projectionMatrix = projection;
  6233. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6234. };
  6235. Scene.prototype.setActiveCameraByID = function (id) {
  6236. var camera = this.getCameraByID(id);
  6237. if (camera) {
  6238. this.activeCamera = camera;
  6239. return camera;
  6240. }
  6241. return null;
  6242. };
  6243. Scene.prototype.setActiveCameraByName = function (name) {
  6244. var camera = this.getCameraByName(name);
  6245. if (camera) {
  6246. this.activeCamera = camera;
  6247. return camera;
  6248. }
  6249. return null;
  6250. };
  6251. Scene.prototype.getMaterialByID = function (id) {
  6252. for (var index = 0; index < this.materials.length; index++) {
  6253. if (this.materials[index].id === id) {
  6254. return this.materials[index];
  6255. }
  6256. }
  6257. return null;
  6258. };
  6259. Scene.prototype.getMaterialByName = function (name) {
  6260. for (var index = 0; index < this.materials.length; index++) {
  6261. if (this.materials[index].name === name) {
  6262. return this.materials[index];
  6263. }
  6264. }
  6265. return null;
  6266. };
  6267. Scene.prototype.getCameraByID = function (id) {
  6268. for (var index = 0; index < this.cameras.length; index++) {
  6269. if (this.cameras[index].id === id) {
  6270. return this.cameras[index];
  6271. }
  6272. }
  6273. return null;
  6274. };
  6275. Scene.prototype.getCameraByName = function (name) {
  6276. for (var index = 0; index < this.cameras.length; index++) {
  6277. if (this.cameras[index].name === name) {
  6278. return this.cameras[index];
  6279. }
  6280. }
  6281. return null;
  6282. };
  6283. Scene.prototype.getLightByName = function (name) {
  6284. for (var index = 0; index < this.lights.length; index++) {
  6285. if (this.lights[index].name === name) {
  6286. return this.lights[index];
  6287. }
  6288. }
  6289. return null;
  6290. };
  6291. Scene.prototype.getLightByID = function (id) {
  6292. for (var index = 0; index < this.lights.length; index++) {
  6293. if (this.lights[index].id === id) {
  6294. return this.lights[index];
  6295. }
  6296. }
  6297. return null;
  6298. };
  6299. Scene.prototype.getGeometryByID = function (id) {
  6300. for (var index = 0; index < this._geometries.length; index++) {
  6301. if (this._geometries[index].id === id) {
  6302. return this._geometries[index];
  6303. }
  6304. }
  6305. return null;
  6306. };
  6307. Scene.prototype.pushGeometry = function (geometry, force) {
  6308. if (!force && this.getGeometryByID(geometry.id)) {
  6309. return false;
  6310. }
  6311. this._geometries.push(geometry);
  6312. return true;
  6313. };
  6314. Scene.prototype.getGeometries = function () {
  6315. return this._geometries;
  6316. };
  6317. Scene.prototype.getMeshByID = function (id) {
  6318. for (var index = 0; index < this.meshes.length; index++) {
  6319. if (this.meshes[index].id === id) {
  6320. return this.meshes[index];
  6321. }
  6322. }
  6323. return null;
  6324. };
  6325. Scene.prototype.getLastMeshByID = function (id) {
  6326. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6327. if (this.meshes[index].id === id) {
  6328. return this.meshes[index];
  6329. }
  6330. }
  6331. return null;
  6332. };
  6333. Scene.prototype.getLastEntryByID = function (id) {
  6334. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6335. if (this.meshes[index].id === id) {
  6336. return this.meshes[index];
  6337. }
  6338. }
  6339. for (index = this.cameras.length - 1; index >= 0; index--) {
  6340. if (this.cameras[index].id === id) {
  6341. return this.cameras[index];
  6342. }
  6343. }
  6344. for (index = this.lights.length - 1; index >= 0; index--) {
  6345. if (this.lights[index].id === id) {
  6346. return this.lights[index];
  6347. }
  6348. }
  6349. return null;
  6350. };
  6351. Scene.prototype.getMeshByName = function (name) {
  6352. for (var index = 0; index < this.meshes.length; index++) {
  6353. if (this.meshes[index].name === name) {
  6354. return this.meshes[index];
  6355. }
  6356. }
  6357. return null;
  6358. };
  6359. Scene.prototype.getLastSkeletonByID = function (id) {
  6360. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6361. if (this.skeletons[index].id === id) {
  6362. return this.skeletons[index];
  6363. }
  6364. }
  6365. return null;
  6366. };
  6367. Scene.prototype.getSkeletonById = function (id) {
  6368. for (var index = 0; index < this.skeletons.length; index++) {
  6369. if (this.skeletons[index].id === id) {
  6370. return this.skeletons[index];
  6371. }
  6372. }
  6373. return null;
  6374. };
  6375. Scene.prototype.getSkeletonByName = function (name) {
  6376. for (var index = 0; index < this.skeletons.length; index++) {
  6377. if (this.skeletons[index].name === name) {
  6378. return this.skeletons[index];
  6379. }
  6380. }
  6381. return null;
  6382. };
  6383. Scene.prototype.isActiveMesh = function (mesh) {
  6384. return (this._activeMeshes.indexOf(mesh) !== -1);
  6385. };
  6386. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6387. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6388. var material = subMesh.getMaterial();
  6389. if (mesh.showSubMeshesBoundingBox) {
  6390. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6391. }
  6392. if (material) {
  6393. if (material.getRenderTargetTextures) {
  6394. if (this._processedMaterials.indexOf(material) === -1) {
  6395. this._processedMaterials.push(material);
  6396. this._renderTargets.concat(material.getRenderTargetTextures());
  6397. }
  6398. }
  6399. this._activeVertices += subMesh.verticesCount;
  6400. this._renderingManager.dispatch(subMesh);
  6401. }
  6402. }
  6403. };
  6404. Scene.prototype._evaluateActiveMeshes = function () {
  6405. this._activeMeshes.reset();
  6406. this._renderingManager.reset();
  6407. this._processedMaterials.reset();
  6408. this._activeParticleSystems.reset();
  6409. this._activeSkeletons.reset();
  6410. this._boundingBoxRenderer.reset();
  6411. if (!this._frustumPlanes) {
  6412. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6413. } else {
  6414. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6415. }
  6416. var meshes;
  6417. var len;
  6418. if (this._selectionOctree) {
  6419. var selection = this._selectionOctree.select(this._frustumPlanes);
  6420. meshes = selection.data;
  6421. len = selection.length;
  6422. } else {
  6423. len = this.meshes.length;
  6424. meshes = this.meshes;
  6425. }
  6426. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6427. var mesh = meshes[meshIndex];
  6428. this._totalVertices += mesh.getTotalVertices();
  6429. if (!mesh.isReady()) {
  6430. continue;
  6431. }
  6432. mesh.computeWorldMatrix();
  6433. mesh._preActivate();
  6434. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6435. this._meshesForIntersections.pushNoDuplicate(mesh);
  6436. }
  6437. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6438. this._activeMeshes.push(mesh);
  6439. mesh._activate(this._renderId);
  6440. this._activeMesh(mesh);
  6441. }
  6442. }
  6443. var beforeParticlesDate = new Date().getTime();
  6444. if (this.particlesEnabled) {
  6445. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6446. var particleSystem = this.particleSystems[particleIndex];
  6447. if (!particleSystem.isStarted()) {
  6448. continue;
  6449. }
  6450. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6451. this._activeParticleSystems.push(particleSystem);
  6452. particleSystem.animate();
  6453. }
  6454. }
  6455. }
  6456. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6457. };
  6458. Scene.prototype._activeMesh = function (mesh) {
  6459. if (mesh.skeleton) {
  6460. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6461. }
  6462. if (mesh.showBoundingBox) {
  6463. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6464. }
  6465. if (mesh.subMeshes) {
  6466. var len;
  6467. var subMeshes;
  6468. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6469. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6470. len = intersections.length;
  6471. subMeshes = intersections.data;
  6472. } else {
  6473. subMeshes = mesh.subMeshes;
  6474. len = subMeshes.length;
  6475. }
  6476. for (var subIndex = 0; subIndex < len; subIndex++) {
  6477. var subMesh = subMeshes[subIndex];
  6478. this._evaluateSubMesh(subMesh, mesh);
  6479. }
  6480. }
  6481. };
  6482. Scene.prototype.updateTransformMatrix = function (force) {
  6483. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6484. };
  6485. Scene.prototype._renderForCamera = function (camera) {
  6486. var engine = this._engine;
  6487. this.activeCamera = camera;
  6488. if (!this.activeCamera)
  6489. throw new Error("Active camera not set");
  6490. engine.setViewport(this.activeCamera.viewport);
  6491. this._renderId++;
  6492. this.updateTransformMatrix();
  6493. if (this.beforeCameraRender) {
  6494. this.beforeCameraRender(this.activeCamera);
  6495. }
  6496. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6497. this._evaluateActiveMeshes();
  6498. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6499. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6500. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6501. skeleton.prepare();
  6502. }
  6503. var beforeRenderTargetDate = new Date().getTime();
  6504. if (this.renderTargetsEnabled) {
  6505. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6506. var renderTarget = this._renderTargets.data[renderIndex];
  6507. if (renderTarget._shouldRender()) {
  6508. this._renderId++;
  6509. renderTarget.render();
  6510. }
  6511. }
  6512. this._renderId++;
  6513. }
  6514. if (this._renderTargets.length > 0) {
  6515. engine.restoreDefaultFramebuffer();
  6516. }
  6517. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6518. this.postProcessManager._prepareFrame();
  6519. var beforeRenderDate = new Date().getTime();
  6520. if (this.layers.length) {
  6521. engine.setDepthBuffer(false);
  6522. var layerIndex;
  6523. var layer;
  6524. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6525. layer = this.layers[layerIndex];
  6526. if (layer.isBackground) {
  6527. layer.render();
  6528. }
  6529. }
  6530. engine.setDepthBuffer(true);
  6531. }
  6532. this._renderingManager.render(null, null, true, true);
  6533. this._boundingBoxRenderer.render();
  6534. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6535. this.lensFlareSystems[lensFlareSystemIndex].render();
  6536. }
  6537. if (this.layers.length) {
  6538. engine.setDepthBuffer(false);
  6539. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6540. layer = this.layers[layerIndex];
  6541. if (!layer.isBackground) {
  6542. layer.render();
  6543. }
  6544. }
  6545. engine.setDepthBuffer(true);
  6546. }
  6547. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6548. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6549. this.activeCamera._updateFromScene();
  6550. this._renderTargets.reset();
  6551. if (this.afterCameraRender) {
  6552. this.afterCameraRender(this.activeCamera);
  6553. }
  6554. };
  6555. Scene.prototype._processSubCameras = function (camera) {
  6556. if (camera.subCameras.length == 0) {
  6557. this._renderForCamera(camera);
  6558. return;
  6559. }
  6560. for (var index = 0; index < camera.subCameras.length; index++) {
  6561. this._renderForCamera(camera.subCameras[index]);
  6562. }
  6563. this.activeCamera = camera;
  6564. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6565. this.activeCamera._updateFromScene();
  6566. };
  6567. Scene.prototype._checkIntersections = function () {
  6568. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6569. var sourceMesh = this._meshesForIntersections.data[index];
  6570. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6571. var action = sourceMesh.actionManager.actions[actionIndex];
  6572. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6573. var otherMesh = action.getTriggerParameter();
  6574. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6575. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6576. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6577. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6578. sourceMesh._intersectionsInProgress.push(otherMesh);
  6579. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6580. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6581. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6582. if (indexOfOther > -1) {
  6583. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6584. }
  6585. }
  6586. }
  6587. }
  6588. }
  6589. };
  6590. Scene.prototype.render = function () {
  6591. var startDate = new Date().getTime();
  6592. this._particlesDuration = 0;
  6593. this._spritesDuration = 0;
  6594. this._activeParticles = 0;
  6595. this._renderDuration = 0;
  6596. this._evaluateActiveMeshesDuration = 0;
  6597. this._totalVertices = 0;
  6598. this._activeVertices = 0;
  6599. this._meshesForIntersections.reset();
  6600. if (this.actionManager) {
  6601. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6602. }
  6603. if (this.beforeRender) {
  6604. this.beforeRender();
  6605. }
  6606. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6607. this._onBeforeRenderCallbacks[callbackIndex]();
  6608. }
  6609. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6610. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6611. this._animate();
  6612. if (this._physicsEngine) {
  6613. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6614. }
  6615. var beforeRenderTargetDate = new Date().getTime();
  6616. var engine = this.getEngine();
  6617. if (this.renderTargetsEnabled) {
  6618. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6619. var renderTarget = this.customRenderTargets[customIndex];
  6620. if (renderTarget._shouldRender()) {
  6621. this._renderId++;
  6622. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6623. if (!this.activeCamera)
  6624. throw new Error("Active camera not set");
  6625. engine.setViewport(this.activeCamera.viewport);
  6626. this.updateTransformMatrix();
  6627. renderTarget.render();
  6628. }
  6629. }
  6630. this._renderId++;
  6631. }
  6632. if (this.customRenderTargets.length > 0) {
  6633. engine.restoreDefaultFramebuffer();
  6634. }
  6635. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6636. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6637. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6638. var light = this.lights[lightIndex];
  6639. var shadowGenerator = light.getShadowGenerator();
  6640. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6641. this._renderTargets.push(shadowGenerator.getShadowMap());
  6642. }
  6643. }
  6644. this.postProcessRenderPipelineManager.update();
  6645. if (this.activeCameras.length > 0) {
  6646. var currentRenderId = this._renderId;
  6647. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6648. this._renderId = currentRenderId;
  6649. this._processSubCameras(this.activeCameras[cameraIndex]);
  6650. }
  6651. } else {
  6652. if (!this.activeCamera) {
  6653. throw new Error("No camera defined");
  6654. }
  6655. this._processSubCameras(this.activeCamera);
  6656. }
  6657. this._checkIntersections();
  6658. if (this.afterRender) {
  6659. this.afterRender();
  6660. }
  6661. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6662. this._toBeDisposed.data[index].dispose();
  6663. this._toBeDisposed[index] = null;
  6664. }
  6665. this._toBeDisposed.reset();
  6666. this._lastFrameDuration = new Date().getTime() - startDate;
  6667. };
  6668. Scene.prototype.dispose = function () {
  6669. this.beforeRender = null;
  6670. this.afterRender = null;
  6671. this.skeletons = [];
  6672. this._boundingBoxRenderer.dispose();
  6673. if (this.onDispose) {
  6674. this.onDispose();
  6675. }
  6676. this.detachControl();
  6677. var canvas = this._engine.getRenderingCanvas();
  6678. var index;
  6679. for (index = 0; index < this.cameras.length; index++) {
  6680. this.cameras[index].detachControl(canvas);
  6681. }
  6682. while (this.lights.length) {
  6683. this.lights[0].dispose();
  6684. }
  6685. while (this.meshes.length) {
  6686. this.meshes[0].dispose(true);
  6687. }
  6688. while (this.cameras.length) {
  6689. this.cameras[0].dispose();
  6690. }
  6691. while (this.materials.length) {
  6692. this.materials[0].dispose();
  6693. }
  6694. while (this.particleSystems.length) {
  6695. this.particleSystems[0].dispose();
  6696. }
  6697. while (this.spriteManagers.length) {
  6698. this.spriteManagers[0].dispose();
  6699. }
  6700. while (this.layers.length) {
  6701. this.layers[0].dispose();
  6702. }
  6703. while (this.textures.length) {
  6704. this.textures[0].dispose();
  6705. }
  6706. this.postProcessManager.dispose();
  6707. if (this._physicsEngine) {
  6708. this.disablePhysicsEngine();
  6709. }
  6710. index = this._engine.scenes.indexOf(this);
  6711. if (index > -1) {
  6712. this._engine.scenes.splice(index, 1);
  6713. }
  6714. this._engine.wipeCaches();
  6715. };
  6716. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6717. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6718. position.divideToRef(collider.radius, this._scaledPosition);
  6719. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6720. collider.retry = 0;
  6721. collider.initialVelocity = this._scaledVelocity;
  6722. collider.initialPosition = this._scaledPosition;
  6723. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6724. finalPosition.multiplyInPlace(collider.radius);
  6725. };
  6726. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6727. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6728. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6729. if (collider.retry >= maximumRetry) {
  6730. finalPosition.copyFrom(position);
  6731. return;
  6732. }
  6733. collider._initialize(position, velocity, closeDistance);
  6734. for (var index = 0; index < this.meshes.length; index++) {
  6735. var mesh = this.meshes[index];
  6736. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6737. mesh._checkCollision(collider);
  6738. }
  6739. }
  6740. if (!collider.collisionFound) {
  6741. position.addToRef(velocity, finalPosition);
  6742. return;
  6743. }
  6744. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6745. collider._getResponse(position, velocity);
  6746. }
  6747. if (velocity.length() <= closeDistance) {
  6748. finalPosition.copyFrom(position);
  6749. return;
  6750. }
  6751. collider.retry++;
  6752. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6753. };
  6754. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6755. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6756. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6757. if (!this._selectionOctree) {
  6758. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6759. }
  6760. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6761. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6762. for (var index = 0; index < this.meshes.length; index++) {
  6763. var mesh = this.meshes[index];
  6764. mesh.computeWorldMatrix(true);
  6765. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6766. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6767. BABYLON.Tools.CheckExtends(minBox, min, max);
  6768. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6769. }
  6770. this._selectionOctree.update(min, max, this.meshes);
  6771. return this._selectionOctree;
  6772. };
  6773. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6774. var engine = this._engine;
  6775. if (!camera) {
  6776. if (!this.activeCamera)
  6777. throw new Error("Active camera not set");
  6778. camera = this.activeCamera;
  6779. }
  6780. var cameraViewport = camera.viewport;
  6781. var viewport = cameraViewport.toGlobal(engine);
  6782. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6783. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6784. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6785. };
  6786. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6787. var pickingInfo = null;
  6788. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6789. var mesh = this.meshes[meshIndex];
  6790. if (predicate) {
  6791. if (!predicate(mesh)) {
  6792. continue;
  6793. }
  6794. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6795. continue;
  6796. }
  6797. var world = mesh.getWorldMatrix();
  6798. var ray = rayFunction(world);
  6799. var result = mesh.intersects(ray, fastCheck);
  6800. if (!result || !result.hit)
  6801. continue;
  6802. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6803. continue;
  6804. pickingInfo = result;
  6805. if (fastCheck) {
  6806. break;
  6807. }
  6808. }
  6809. return pickingInfo || new BABYLON.PickingInfo();
  6810. };
  6811. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6812. var _this = this;
  6813. return this._internalPick(function (world) {
  6814. return _this.createPickingRay(x, y, world, camera);
  6815. }, predicate, fastCheck);
  6816. };
  6817. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6818. var _this = this;
  6819. return this._internalPick(function (world) {
  6820. if (!_this._pickWithRayInverseMatrix) {
  6821. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6822. }
  6823. world.invertToRef(_this._pickWithRayInverseMatrix);
  6824. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6825. }, predicate, fastCheck);
  6826. };
  6827. Scene.prototype.setPointerOverMesh = function (mesh) {
  6828. if (this._pointerOverMesh === mesh) {
  6829. return;
  6830. }
  6831. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6832. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6833. }
  6834. this._pointerOverMesh = mesh;
  6835. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6836. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6837. }
  6838. };
  6839. Scene.prototype.getPointerOverMesh = function () {
  6840. return this._pointerOverMesh;
  6841. };
  6842. Scene.prototype.getPhysicsEngine = function () {
  6843. return this._physicsEngine;
  6844. };
  6845. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6846. if (this._physicsEngine) {
  6847. return true;
  6848. }
  6849. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6850. if (!this._physicsEngine.isSupported()) {
  6851. this._physicsEngine = null;
  6852. return false;
  6853. }
  6854. this._physicsEngine._initialize(gravity);
  6855. return true;
  6856. };
  6857. Scene.prototype.disablePhysicsEngine = function () {
  6858. if (!this._physicsEngine) {
  6859. return;
  6860. }
  6861. this._physicsEngine.dispose();
  6862. this._physicsEngine = undefined;
  6863. };
  6864. Scene.prototype.isPhysicsEnabled = function () {
  6865. return this._physicsEngine !== undefined;
  6866. };
  6867. Scene.prototype.setGravity = function (gravity) {
  6868. if (!this._physicsEngine) {
  6869. return;
  6870. }
  6871. this._physicsEngine._setGravity(gravity);
  6872. };
  6873. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6874. if (parts.parts) {
  6875. options = parts;
  6876. parts = parts.parts;
  6877. }
  6878. if (!this._physicsEngine) {
  6879. return null;
  6880. }
  6881. for (var index = 0; index < parts.length; index++) {
  6882. var mesh = parts[index].mesh;
  6883. mesh._physicImpostor = parts[index].impostor;
  6884. mesh._physicsMass = options.mass / parts.length;
  6885. mesh._physicsFriction = options.friction;
  6886. mesh._physicRestitution = options.restitution;
  6887. }
  6888. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6889. };
  6890. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6891. for (var index = 0; index < compound.parts.length; index++) {
  6892. var mesh = compound.parts[index].mesh;
  6893. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6894. this._physicsEngine._unregisterMesh(mesh);
  6895. }
  6896. };
  6897. Scene.prototype._getByTags = function (list, tagsQuery) {
  6898. if (tagsQuery === undefined) {
  6899. return list;
  6900. }
  6901. var listByTags = [];
  6902. for (var i in list) {
  6903. var item = list[i];
  6904. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6905. listByTags.push(item);
  6906. }
  6907. }
  6908. return listByTags;
  6909. };
  6910. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6911. return this._getByTags(this.meshes, tagsQuery);
  6912. };
  6913. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6914. return this._getByTags(this.cameras, tagsQuery);
  6915. };
  6916. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6917. return this._getByTags(this.lights, tagsQuery);
  6918. };
  6919. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  6920. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  6921. };
  6922. Scene.FOGMODE_NONE = 0;
  6923. Scene.FOGMODE_EXP = 1;
  6924. Scene.FOGMODE_EXP2 = 2;
  6925. Scene.FOGMODE_LINEAR = 3;
  6926. Scene.MinDeltaTime = 1.0;
  6927. Scene.MaxDeltaTime = 1000.0;
  6928. return Scene;
  6929. })();
  6930. BABYLON.Scene = Scene;
  6931. })(BABYLON || (BABYLON = {}));
  6932. var BABYLON;
  6933. (function (BABYLON) {
  6934. var VertexBuffer = (function () {
  6935. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  6936. if (engine instanceof BABYLON.Mesh) {
  6937. this._engine = engine.getScene().getEngine();
  6938. } else {
  6939. this._engine = engine;
  6940. }
  6941. this._updatable = updatable;
  6942. this._data = data;
  6943. if (!postponeInternalCreation) {
  6944. this.create();
  6945. }
  6946. this._kind = kind;
  6947. switch (kind) {
  6948. case VertexBuffer.PositionKind:
  6949. this._strideSize = 3;
  6950. break;
  6951. case VertexBuffer.NormalKind:
  6952. this._strideSize = 3;
  6953. break;
  6954. case VertexBuffer.UVKind:
  6955. this._strideSize = 2;
  6956. break;
  6957. case VertexBuffer.UV2Kind:
  6958. this._strideSize = 2;
  6959. break;
  6960. case VertexBuffer.ColorKind:
  6961. this._strideSize = 3;
  6962. break;
  6963. case VertexBuffer.MatricesIndicesKind:
  6964. this._strideSize = 4;
  6965. break;
  6966. case VertexBuffer.MatricesWeightsKind:
  6967. this._strideSize = 4;
  6968. break;
  6969. }
  6970. }
  6971. VertexBuffer.prototype.isUpdatable = function () {
  6972. return this._updatable;
  6973. };
  6974. VertexBuffer.prototype.getData = function () {
  6975. return this._data;
  6976. };
  6977. VertexBuffer.prototype.getBuffer = function () {
  6978. return this._buffer;
  6979. };
  6980. VertexBuffer.prototype.getStrideSize = function () {
  6981. return this._strideSize;
  6982. };
  6983. VertexBuffer.prototype.create = function (data) {
  6984. if (!data && this._buffer) {
  6985. return;
  6986. }
  6987. data = data || this._data;
  6988. if (!this._buffer) {
  6989. if (this._updatable) {
  6990. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  6991. } else {
  6992. this._buffer = this._engine.createVertexBuffer(data);
  6993. }
  6994. }
  6995. if (this._updatable) {
  6996. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  6997. this._data = data;
  6998. }
  6999. };
  7000. VertexBuffer.prototype.update = function (data) {
  7001. this.create(data);
  7002. };
  7003. VertexBuffer.prototype.dispose = function () {
  7004. if (!this._buffer) {
  7005. return;
  7006. }
  7007. if (this._engine._releaseBuffer(this._buffer)) {
  7008. this._buffer = null;
  7009. }
  7010. };
  7011. Object.defineProperty(VertexBuffer, "PositionKind", {
  7012. get: function () {
  7013. return VertexBuffer._PositionKind;
  7014. },
  7015. enumerable: true,
  7016. configurable: true
  7017. });
  7018. Object.defineProperty(VertexBuffer, "NormalKind", {
  7019. get: function () {
  7020. return VertexBuffer._NormalKind;
  7021. },
  7022. enumerable: true,
  7023. configurable: true
  7024. });
  7025. Object.defineProperty(VertexBuffer, "UVKind", {
  7026. get: function () {
  7027. return VertexBuffer._UVKind;
  7028. },
  7029. enumerable: true,
  7030. configurable: true
  7031. });
  7032. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7033. get: function () {
  7034. return VertexBuffer._UV2Kind;
  7035. },
  7036. enumerable: true,
  7037. configurable: true
  7038. });
  7039. Object.defineProperty(VertexBuffer, "ColorKind", {
  7040. get: function () {
  7041. return VertexBuffer._ColorKind;
  7042. },
  7043. enumerable: true,
  7044. configurable: true
  7045. });
  7046. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7047. get: function () {
  7048. return VertexBuffer._MatricesIndicesKind;
  7049. },
  7050. enumerable: true,
  7051. configurable: true
  7052. });
  7053. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7054. get: function () {
  7055. return VertexBuffer._MatricesWeightsKind;
  7056. },
  7057. enumerable: true,
  7058. configurable: true
  7059. });
  7060. VertexBuffer._PositionKind = "position";
  7061. VertexBuffer._NormalKind = "normal";
  7062. VertexBuffer._UVKind = "uv";
  7063. VertexBuffer._UV2Kind = "uv2";
  7064. VertexBuffer._ColorKind = "color";
  7065. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7066. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7067. return VertexBuffer;
  7068. })();
  7069. BABYLON.VertexBuffer = VertexBuffer;
  7070. })(BABYLON || (BABYLON = {}));
  7071. var __extends = this.__extends || function (d, b) {
  7072. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7073. function __() { this.constructor = d; }
  7074. __.prototype = b.prototype;
  7075. d.prototype = new __();
  7076. };
  7077. var BABYLON;
  7078. (function (BABYLON) {
  7079. var AbstractMesh = (function (_super) {
  7080. __extends(AbstractMesh, _super);
  7081. function AbstractMesh(name, scene) {
  7082. _super.call(this, name, scene);
  7083. this.position = new BABYLON.Vector3(0, 0, 0);
  7084. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7085. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7086. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7087. this.visibility = 1.0;
  7088. this.infiniteDistance = false;
  7089. this.isVisible = true;
  7090. this.isPickable = true;
  7091. this.showBoundingBox = false;
  7092. this.showSubMeshesBoundingBox = false;
  7093. this.onDispose = null;
  7094. this.checkCollisions = false;
  7095. this.isBlocker = false;
  7096. this.renderingGroupId = 0;
  7097. this.receiveShadows = false;
  7098. this.renderOutline = false;
  7099. this.outlineColor = BABYLON.Color3.Red();
  7100. this.outlineWidth = 0.02;
  7101. this.useOctreeForRenderingSelection = true;
  7102. this.useOctreeForPicking = true;
  7103. this.useOctreeForCollisions = true;
  7104. this.layerMask = 0xFFFFFFFF;
  7105. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7106. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7107. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7108. this._collider = new BABYLON.Collider();
  7109. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7110. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7111. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7112. this._localScaling = BABYLON.Matrix.Zero();
  7113. this._localRotation = BABYLON.Matrix.Zero();
  7114. this._localTranslation = BABYLON.Matrix.Zero();
  7115. this._localBillboard = BABYLON.Matrix.Zero();
  7116. this._localPivotScaling = BABYLON.Matrix.Zero();
  7117. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7118. this._localWorld = BABYLON.Matrix.Zero();
  7119. this._worldMatrix = BABYLON.Matrix.Zero();
  7120. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7121. this._absolutePosition = BABYLON.Vector3.Zero();
  7122. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7123. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7124. this._isDirty = false;
  7125. this._pivotMatrix = BABYLON.Matrix.Identity();
  7126. this._isDisposed = false;
  7127. this._renderId = 0;
  7128. this._intersectionsInProgress = new Array();
  7129. scene.meshes.push(this);
  7130. }
  7131. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7132. get: function () {
  7133. return AbstractMesh._BILLBOARDMODE_NONE;
  7134. },
  7135. enumerable: true,
  7136. configurable: true
  7137. });
  7138. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7139. get: function () {
  7140. return AbstractMesh._BILLBOARDMODE_X;
  7141. },
  7142. enumerable: true,
  7143. configurable: true
  7144. });
  7145. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7146. get: function () {
  7147. return AbstractMesh._BILLBOARDMODE_Y;
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7153. get: function () {
  7154. return AbstractMesh._BILLBOARDMODE_Z;
  7155. },
  7156. enumerable: true,
  7157. configurable: true
  7158. });
  7159. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7160. get: function () {
  7161. return AbstractMesh._BILLBOARDMODE_ALL;
  7162. },
  7163. enumerable: true,
  7164. configurable: true
  7165. });
  7166. AbstractMesh.prototype.getTotalVertices = function () {
  7167. return 0;
  7168. };
  7169. AbstractMesh.prototype.getIndices = function () {
  7170. return null;
  7171. };
  7172. AbstractMesh.prototype.getVerticesData = function (kind) {
  7173. return null;
  7174. };
  7175. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7176. return false;
  7177. };
  7178. AbstractMesh.prototype.getBoundingInfo = function () {
  7179. if (!this._boundingInfo) {
  7180. this._updateBoundingInfo();
  7181. }
  7182. return this._boundingInfo;
  7183. };
  7184. AbstractMesh.prototype._preActivate = function () {
  7185. };
  7186. AbstractMesh.prototype._activate = function (renderId) {
  7187. this._renderId = renderId;
  7188. };
  7189. AbstractMesh.prototype.getWorldMatrix = function () {
  7190. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7191. this.computeWorldMatrix();
  7192. }
  7193. return this._worldMatrix;
  7194. };
  7195. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7196. get: function () {
  7197. return this._worldMatrix;
  7198. },
  7199. enumerable: true,
  7200. configurable: true
  7201. });
  7202. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7203. get: function () {
  7204. return this._absolutePosition;
  7205. },
  7206. enumerable: true,
  7207. configurable: true
  7208. });
  7209. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7210. if (!this.rotationQuaternion) {
  7211. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7212. this.rotation = BABYLON.Vector3.Zero();
  7213. }
  7214. if (!space || space == 0 /* LOCAL */) {
  7215. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7216. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7217. } else {
  7218. if (this.parent) {
  7219. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7220. invertParentWorldMatrix.invert();
  7221. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7222. }
  7223. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7224. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7225. }
  7226. };
  7227. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7228. var displacementVector = axis.scale(distance);
  7229. if (!space || space == 0 /* LOCAL */) {
  7230. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7231. this.setPositionWithLocalVector(tempV3);
  7232. } else {
  7233. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7234. }
  7235. };
  7236. AbstractMesh.prototype.getAbsolutePosition = function () {
  7237. this.computeWorldMatrix();
  7238. return this._absolutePosition;
  7239. };
  7240. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7241. if (!absolutePosition) {
  7242. return;
  7243. }
  7244. var absolutePositionX;
  7245. var absolutePositionY;
  7246. var absolutePositionZ;
  7247. if (absolutePosition.x === undefined) {
  7248. if (arguments.length < 3) {
  7249. return;
  7250. }
  7251. absolutePositionX = arguments[0];
  7252. absolutePositionY = arguments[1];
  7253. absolutePositionZ = arguments[2];
  7254. } else {
  7255. absolutePositionX = absolutePosition.x;
  7256. absolutePositionY = absolutePosition.y;
  7257. absolutePositionZ = absolutePosition.z;
  7258. }
  7259. if (this.parent) {
  7260. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7261. invertParentWorldMatrix.invert();
  7262. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7263. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7264. } else {
  7265. this.position.x = absolutePositionX;
  7266. this.position.y = absolutePositionY;
  7267. this.position.z = absolutePositionZ;
  7268. }
  7269. };
  7270. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7271. this._pivotMatrix = matrix;
  7272. this._cache.pivotMatrixUpdated = true;
  7273. };
  7274. AbstractMesh.prototype.getPivotMatrix = function () {
  7275. return this._pivotMatrix;
  7276. };
  7277. AbstractMesh.prototype._isSynchronized = function () {
  7278. if (this._isDirty) {
  7279. return false;
  7280. }
  7281. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7282. return false;
  7283. if (this._cache.pivotMatrixUpdated) {
  7284. return false;
  7285. }
  7286. if (this.infiniteDistance) {
  7287. return false;
  7288. }
  7289. if (!this._cache.position.equals(this.position))
  7290. return false;
  7291. if (this.rotationQuaternion) {
  7292. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7293. return false;
  7294. } else {
  7295. if (!this._cache.rotation.equals(this.rotation))
  7296. return false;
  7297. }
  7298. if (!this._cache.scaling.equals(this.scaling))
  7299. return false;
  7300. return true;
  7301. };
  7302. AbstractMesh.prototype._initCache = function () {
  7303. _super.prototype._initCache.call(this);
  7304. this._cache.localMatrixUpdated = false;
  7305. this._cache.position = BABYLON.Vector3.Zero();
  7306. this._cache.scaling = BABYLON.Vector3.Zero();
  7307. this._cache.rotation = BABYLON.Vector3.Zero();
  7308. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7309. };
  7310. AbstractMesh.prototype.markAsDirty = function (property) {
  7311. if (property === "rotation") {
  7312. this.rotationQuaternion = null;
  7313. }
  7314. this._currentRenderId = Number.MAX_VALUE;
  7315. this._isDirty = true;
  7316. };
  7317. AbstractMesh.prototype._updateBoundingInfo = function () {
  7318. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7319. this._boundingInfo._update(this.worldMatrixFromCache);
  7320. if (!this.subMeshes) {
  7321. return;
  7322. }
  7323. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7324. var subMesh = this.subMeshes[subIndex];
  7325. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7326. }
  7327. };
  7328. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7329. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7330. return this._worldMatrix;
  7331. }
  7332. this._cache.position.copyFrom(this.position);
  7333. this._cache.scaling.copyFrom(this.scaling);
  7334. this._cache.pivotMatrixUpdated = false;
  7335. this._currentRenderId = this.getScene().getRenderId();
  7336. this._isDirty = false;
  7337. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7338. if (this.rotationQuaternion) {
  7339. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7340. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7341. } else {
  7342. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7343. this._cache.rotation.copyFrom(this.rotation);
  7344. }
  7345. if (this.infiniteDistance && !this.parent) {
  7346. var camera = this.getScene().activeCamera;
  7347. var cameraWorldMatrix = camera.getWorldMatrix();
  7348. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7349. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7350. } else {
  7351. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7352. }
  7353. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7354. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7355. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7356. var localPosition = this.position.clone();
  7357. var zero = this.getScene().activeCamera.position.clone();
  7358. if (this.parent && this.parent.position) {
  7359. localPosition.addInPlace(this.parent.position);
  7360. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7361. }
  7362. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7363. zero = this.getScene().activeCamera.position;
  7364. } else {
  7365. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7366. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7367. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7368. zero.y = localPosition.y + 0.001;
  7369. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7370. zero.z = localPosition.z + 0.001;
  7371. }
  7372. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7373. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7374. this._localBillboard.invert();
  7375. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7376. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7377. }
  7378. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7379. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7380. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7381. } else {
  7382. this._worldMatrix.copyFrom(this._localWorld);
  7383. }
  7384. this._updateBoundingInfo();
  7385. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7386. return this._worldMatrix;
  7387. };
  7388. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7389. this.computeWorldMatrix();
  7390. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7391. };
  7392. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7393. this.computeWorldMatrix();
  7394. var invLocalWorldMatrix = this._localWorld.clone();
  7395. invLocalWorldMatrix.invert();
  7396. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7397. };
  7398. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7399. this.computeWorldMatrix();
  7400. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7401. };
  7402. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7403. yawCor = yawCor || 0;
  7404. pitchCor = pitchCor || 0;
  7405. rollCor = rollCor || 0;
  7406. var dv = targetPoint.subtract(this.position);
  7407. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7408. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7409. var pitch = Math.atan2(dv.y, len);
  7410. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7411. };
  7412. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7413. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7414. return false;
  7415. }
  7416. return true;
  7417. };
  7418. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7419. if (!this._boundingInfo || !mesh._boundingInfo) {
  7420. return false;
  7421. }
  7422. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7423. };
  7424. AbstractMesh.prototype.intersectsPoint = function (point) {
  7425. if (!this._boundingInfo) {
  7426. return false;
  7427. }
  7428. return this._boundingInfo.intersectsPoint(point);
  7429. };
  7430. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7431. var physicsEngine = this.getScene().getPhysicsEngine();
  7432. if (!physicsEngine) {
  7433. return;
  7434. }
  7435. if (impostor.impostor) {
  7436. options = impostor;
  7437. impostor = impostor.impostor;
  7438. }
  7439. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7440. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7441. physicsEngine._unregisterMesh(this);
  7442. return;
  7443. }
  7444. options.mass = options.mass || 0;
  7445. options.friction = options.friction || 0.2;
  7446. options.restitution = options.restitution || 0.9;
  7447. this._physicImpostor = impostor;
  7448. this._physicsMass = options.mass;
  7449. this._physicsFriction = options.friction;
  7450. this._physicRestitution = options.restitution;
  7451. physicsEngine._registerMesh(this, impostor, options);
  7452. };
  7453. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7454. if (!this._physicImpostor) {
  7455. return BABYLON.PhysicsEngine.NoImpostor;
  7456. }
  7457. return this._physicImpostor;
  7458. };
  7459. AbstractMesh.prototype.getPhysicsMass = function () {
  7460. if (!this._physicsMass) {
  7461. return 0;
  7462. }
  7463. return this._physicsMass;
  7464. };
  7465. AbstractMesh.prototype.getPhysicsFriction = function () {
  7466. if (!this._physicsFriction) {
  7467. return 0;
  7468. }
  7469. return this._physicsFriction;
  7470. };
  7471. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7472. if (!this._physicRestitution) {
  7473. return 0;
  7474. }
  7475. return this._physicRestitution;
  7476. };
  7477. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7478. if (!this._physicImpostor) {
  7479. return;
  7480. }
  7481. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7482. };
  7483. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7484. if (!this._physicImpostor) {
  7485. return;
  7486. }
  7487. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7488. };
  7489. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7490. if (!this._physicImpostor) {
  7491. return;
  7492. }
  7493. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7494. };
  7495. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7496. var globalPosition = this.getAbsolutePosition();
  7497. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7498. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7499. this._collider.radius = this.ellipsoid;
  7500. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7501. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7502. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7503. this.position.addInPlace(this._diffPositionForCollisions);
  7504. }
  7505. };
  7506. /**
  7507. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7508. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7509. */
  7510. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7511. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7512. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7513. if (!this._submeshesOctree) {
  7514. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7515. }
  7516. this.computeWorldMatrix(true);
  7517. var bbox = this.getBoundingInfo().boundingBox;
  7518. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7519. return this._submeshesOctree;
  7520. };
  7521. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7522. this._generatePointsArray();
  7523. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7524. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7525. subMesh._lastColliderWorldVertices = [];
  7526. subMesh._trianglePlanes = [];
  7527. var start = subMesh.verticesStart;
  7528. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7529. for (var i = start; i < end; i++) {
  7530. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7531. }
  7532. }
  7533. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7534. };
  7535. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7536. var subMeshes;
  7537. var len;
  7538. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7539. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7540. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7541. len = intersections.length;
  7542. subMeshes = intersections.data;
  7543. } else {
  7544. subMeshes = this.subMeshes;
  7545. len = subMeshes.length;
  7546. }
  7547. for (var index = 0; index < len; index++) {
  7548. var subMesh = subMeshes[index];
  7549. if (len > 1 && !subMesh._checkCollision(collider))
  7550. continue;
  7551. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7552. }
  7553. };
  7554. AbstractMesh.prototype._checkCollision = function (collider) {
  7555. if (!this._boundingInfo._checkCollision(collider))
  7556. return;
  7557. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7558. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7559. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7560. };
  7561. AbstractMesh.prototype._generatePointsArray = function () {
  7562. return false;
  7563. };
  7564. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7565. var pickingInfo = new BABYLON.PickingInfo();
  7566. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7567. return pickingInfo;
  7568. }
  7569. if (!this._generatePointsArray()) {
  7570. return pickingInfo;
  7571. }
  7572. var intersectInfo = null;
  7573. var subMeshes;
  7574. var len;
  7575. if (this._submeshesOctree && this.useOctreeForPicking) {
  7576. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7577. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7578. len = intersections.length;
  7579. subMeshes = intersections.data;
  7580. } else {
  7581. subMeshes = this.subMeshes;
  7582. len = subMeshes.length;
  7583. }
  7584. for (var index = 0; index < len; index++) {
  7585. var subMesh = subMeshes[index];
  7586. if (len > 1 && !subMesh.canIntersects(ray))
  7587. continue;
  7588. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7589. if (currentIntersectInfo) {
  7590. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7591. intersectInfo = currentIntersectInfo;
  7592. if (fastCheck) {
  7593. break;
  7594. }
  7595. }
  7596. }
  7597. }
  7598. if (intersectInfo) {
  7599. var world = this.getWorldMatrix();
  7600. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7601. var direction = ray.direction.clone();
  7602. direction.normalize();
  7603. direction = direction.scale(intersectInfo.distance);
  7604. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7605. var pickedPoint = worldOrigin.add(worldDirection);
  7606. pickingInfo.hit = true;
  7607. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7608. pickingInfo.pickedPoint = pickedPoint;
  7609. pickingInfo.pickedMesh = this;
  7610. pickingInfo.bu = intersectInfo.bu;
  7611. pickingInfo.bv = intersectInfo.bv;
  7612. pickingInfo.faceId = intersectInfo.faceId;
  7613. return pickingInfo;
  7614. }
  7615. return pickingInfo;
  7616. };
  7617. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7618. return null;
  7619. };
  7620. AbstractMesh.prototype.releaseSubMeshes = function () {
  7621. if (this.subMeshes) {
  7622. while (this.subMeshes.length) {
  7623. this.subMeshes[0].dispose();
  7624. }
  7625. } else {
  7626. this.subMeshes = new Array();
  7627. }
  7628. };
  7629. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7630. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7631. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7632. }
  7633. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7634. var other = this._intersectionsInProgress[index];
  7635. var pos = other._intersectionsInProgress.indexOf(this);
  7636. other._intersectionsInProgress.splice(pos, 1);
  7637. }
  7638. this._intersectionsInProgress = [];
  7639. this.releaseSubMeshes();
  7640. var index = this.getScene().meshes.indexOf(this);
  7641. if (index != -1) {
  7642. this.getScene().meshes.splice(index, 1);
  7643. }
  7644. if (!doNotRecurse) {
  7645. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7646. if (this.getScene().particleSystems[index].emitter == this) {
  7647. this.getScene().particleSystems[index].dispose();
  7648. index--;
  7649. }
  7650. }
  7651. var objects = this.getScene().meshes.slice(0);
  7652. for (index = 0; index < objects.length; index++) {
  7653. if (objects[index].parent == this) {
  7654. objects[index].dispose();
  7655. }
  7656. }
  7657. } else {
  7658. for (index = 0; index < this.getScene().meshes.length; index++) {
  7659. var obj = this.getScene().meshes[index];
  7660. if (obj.parent === this) {
  7661. obj.parent = null;
  7662. obj.computeWorldMatrix(true);
  7663. }
  7664. }
  7665. }
  7666. this._isDisposed = true;
  7667. if (this.onDispose) {
  7668. this.onDispose();
  7669. }
  7670. };
  7671. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7672. AbstractMesh._BILLBOARDMODE_X = 1;
  7673. AbstractMesh._BILLBOARDMODE_Y = 2;
  7674. AbstractMesh._BILLBOARDMODE_Z = 4;
  7675. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7676. return AbstractMesh;
  7677. })(BABYLON.Node);
  7678. BABYLON.AbstractMesh = AbstractMesh;
  7679. })(BABYLON || (BABYLON = {}));
  7680. var __extends = this.__extends || function (d, b) {
  7681. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7682. function __() { this.constructor = d; }
  7683. __.prototype = b.prototype;
  7684. d.prototype = new __();
  7685. };
  7686. var BABYLON;
  7687. (function (BABYLON) {
  7688. var _InstancesBatch = (function () {
  7689. function _InstancesBatch() {
  7690. this.mustReturn = false;
  7691. this.visibleInstances = new Array();
  7692. this.renderSelf = new Array();
  7693. }
  7694. return _InstancesBatch;
  7695. })();
  7696. BABYLON._InstancesBatch = _InstancesBatch;
  7697. var Mesh = (function (_super) {
  7698. __extends(Mesh, _super);
  7699. function Mesh(name, scene) {
  7700. _super.call(this, name, scene);
  7701. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7702. this.instances = new Array();
  7703. this._onBeforeRenderCallbacks = new Array();
  7704. this._onAfterRenderCallbacks = new Array();
  7705. this._visibleInstances = {};
  7706. this._renderIdForInstances = new Array();
  7707. this._batchCache = new _InstancesBatch();
  7708. this._instancesBufferSize = 32 * 16 * 4;
  7709. }
  7710. Mesh.prototype.getTotalVertices = function () {
  7711. if (!this._geometry) {
  7712. return 0;
  7713. }
  7714. return this._geometry.getTotalVertices();
  7715. };
  7716. Mesh.prototype.getVerticesData = function (kind) {
  7717. if (!this._geometry) {
  7718. return null;
  7719. }
  7720. return this._geometry.getVerticesData(kind);
  7721. };
  7722. Mesh.prototype.getVertexBuffer = function (kind) {
  7723. if (!this._geometry) {
  7724. return undefined;
  7725. }
  7726. return this._geometry.getVertexBuffer(kind);
  7727. };
  7728. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7729. if (!this._geometry) {
  7730. if (this._delayInfo) {
  7731. return this._delayInfo.indexOf(kind) !== -1;
  7732. }
  7733. return false;
  7734. }
  7735. return this._geometry.isVerticesDataPresent(kind);
  7736. };
  7737. Mesh.prototype.getVerticesDataKinds = function () {
  7738. if (!this._geometry) {
  7739. var result = [];
  7740. if (this._delayInfo) {
  7741. for (var kind in this._delayInfo) {
  7742. result.push(kind);
  7743. }
  7744. }
  7745. return result;
  7746. }
  7747. return this._geometry.getVerticesDataKinds();
  7748. };
  7749. Mesh.prototype.getTotalIndices = function () {
  7750. if (!this._geometry) {
  7751. return 0;
  7752. }
  7753. return this._geometry.getTotalIndices();
  7754. };
  7755. Mesh.prototype.getIndices = function () {
  7756. if (!this._geometry) {
  7757. return [];
  7758. }
  7759. return this._geometry.getIndices();
  7760. };
  7761. Mesh.prototype.isReady = function () {
  7762. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7763. return false;
  7764. }
  7765. return _super.prototype.isReady.call(this);
  7766. };
  7767. Mesh.prototype.isDisposed = function () {
  7768. return this._isDisposed;
  7769. };
  7770. Mesh.prototype._preActivate = function () {
  7771. var sceneRenderId = this.getScene().getRenderId();
  7772. if (this._preActivateId == sceneRenderId) {
  7773. return;
  7774. }
  7775. this._preActivateId = sceneRenderId;
  7776. this._visibleInstances = null;
  7777. };
  7778. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7779. if (!this._visibleInstances) {
  7780. this._visibleInstances = {};
  7781. this._visibleInstances.defaultRenderId = renderId;
  7782. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7783. }
  7784. if (!this._visibleInstances[renderId]) {
  7785. this._visibleInstances[renderId] = new Array();
  7786. }
  7787. this._visibleInstances[renderId].push(instance);
  7788. };
  7789. Mesh.prototype.refreshBoundingInfo = function () {
  7790. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7791. if (data) {
  7792. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7793. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7794. }
  7795. if (this.subMeshes) {
  7796. for (var index = 0; index < this.subMeshes.length; index++) {
  7797. this.subMeshes[index].refreshBoundingInfo();
  7798. }
  7799. }
  7800. this._updateBoundingInfo();
  7801. };
  7802. Mesh.prototype._createGlobalSubMesh = function () {
  7803. var totalVertices = this.getTotalVertices();
  7804. if (!totalVertices || !this.getIndices()) {
  7805. return null;
  7806. }
  7807. this.releaseSubMeshes();
  7808. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7809. };
  7810. Mesh.prototype.subdivide = function (count) {
  7811. if (count < 1) {
  7812. return;
  7813. }
  7814. var totalIndices = this.getTotalIndices();
  7815. var subdivisionSize = (totalIndices / count) | 0;
  7816. var offset = 0;
  7817. while (subdivisionSize % 3 != 0) {
  7818. subdivisionSize++;
  7819. }
  7820. this.releaseSubMeshes();
  7821. for (var index = 0; index < count; index++) {
  7822. if (offset >= totalIndices) {
  7823. break;
  7824. }
  7825. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7826. offset += subdivisionSize;
  7827. }
  7828. this.synchronizeInstances();
  7829. };
  7830. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7831. if (kind instanceof Array) {
  7832. var temp = data;
  7833. data = kind;
  7834. kind = temp;
  7835. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7836. }
  7837. if (!this._geometry) {
  7838. var vertexData = new BABYLON.VertexData();
  7839. vertexData.set(data, kind);
  7840. var scene = this.getScene();
  7841. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7842. } else {
  7843. this._geometry.setVerticesData(kind, data, updatable);
  7844. }
  7845. };
  7846. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7847. if (!this._geometry) {
  7848. return;
  7849. }
  7850. if (!makeItUnique) {
  7851. this._geometry.updateVerticesData(kind, data, updateExtends);
  7852. } else {
  7853. this.makeGeometryUnique();
  7854. this.updateVerticesData(kind, data, updateExtends, false);
  7855. }
  7856. };
  7857. Mesh.prototype.makeGeometryUnique = function () {
  7858. if (!this._geometry) {
  7859. return;
  7860. }
  7861. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7862. geometry.applyToMesh(this);
  7863. };
  7864. Mesh.prototype.setIndices = function (indices) {
  7865. if (!this._geometry) {
  7866. var vertexData = new BABYLON.VertexData();
  7867. vertexData.indices = indices;
  7868. var scene = this.getScene();
  7869. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7870. } else {
  7871. this._geometry.setIndices(indices);
  7872. }
  7873. };
  7874. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7875. var engine = this.getScene().getEngine();
  7876. var indexToBind = this._geometry.getIndexBuffer();
  7877. if (wireframe) {
  7878. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7879. }
  7880. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7881. };
  7882. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7883. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7884. return;
  7885. }
  7886. var engine = this.getScene().getEngine();
  7887. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7888. };
  7889. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7890. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7891. return;
  7892. }
  7893. var engine = this.getScene().getEngine();
  7894. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7895. };
  7896. Mesh.prototype.registerBeforeRender = function (func) {
  7897. this._onBeforeRenderCallbacks.push(func);
  7898. };
  7899. Mesh.prototype.unregisterBeforeRender = function (func) {
  7900. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7901. if (index > -1) {
  7902. this._onBeforeRenderCallbacks.splice(index, 1);
  7903. }
  7904. };
  7905. Mesh.prototype.registerAfterRender = function (func) {
  7906. this._onAfterRenderCallbacks.push(func);
  7907. };
  7908. Mesh.prototype.unregisterAfterRender = function (func) {
  7909. var index = this._onAfterRenderCallbacks.indexOf(func);
  7910. if (index > -1) {
  7911. this._onAfterRenderCallbacks.splice(index, 1);
  7912. }
  7913. };
  7914. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7915. var scene = this.getScene();
  7916. this._batchCache.mustReturn = false;
  7917. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7918. this._batchCache.visibleInstances[subMeshId] = null;
  7919. if (this._visibleInstances) {
  7920. var currentRenderId = scene.getRenderId();
  7921. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  7922. var selfRenderId = this._renderId;
  7923. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  7924. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  7925. currentRenderId = this._visibleInstances.defaultRenderId;
  7926. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  7927. }
  7928. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  7929. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  7930. this._batchCache.mustReturn = true;
  7931. return this._batchCache;
  7932. }
  7933. if (currentRenderId !== selfRenderId) {
  7934. this._batchCache.renderSelf[subMeshId] = false;
  7935. }
  7936. }
  7937. this._renderIdForInstances[subMeshId] = currentRenderId;
  7938. }
  7939. return this._batchCache;
  7940. };
  7941. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  7942. var matricesCount = this.instances.length + 1;
  7943. var bufferSize = matricesCount * 16 * 4;
  7944. while (this._instancesBufferSize < bufferSize) {
  7945. this._instancesBufferSize *= 2;
  7946. }
  7947. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  7948. if (this._worldMatricesInstancesBuffer) {
  7949. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  7950. }
  7951. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  7952. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  7953. }
  7954. var offset = 0;
  7955. var instancesCount = 0;
  7956. var world = this.getWorldMatrix();
  7957. if (batch.renderSelf[subMesh._id]) {
  7958. world.copyToArray(this._worldMatricesInstancesArray, offset);
  7959. offset += 16;
  7960. instancesCount++;
  7961. }
  7962. var visibleInstances = batch.visibleInstances[subMesh._id];
  7963. if (visibleInstances) {
  7964. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  7965. var instance = visibleInstances[instanceIndex];
  7966. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  7967. offset += 16;
  7968. instancesCount++;
  7969. }
  7970. }
  7971. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  7972. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  7973. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  7974. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  7975. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  7976. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  7977. this._draw(subMesh, !wireFrame, instancesCount);
  7978. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  7979. };
  7980. Mesh.prototype.render = function (subMesh) {
  7981. var scene = this.getScene();
  7982. var batch = this._getInstancesRenderList(subMesh._id);
  7983. if (batch.mustReturn) {
  7984. return;
  7985. }
  7986. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7987. return;
  7988. }
  7989. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7990. this._onBeforeRenderCallbacks[callbackIndex]();
  7991. }
  7992. var engine = scene.getEngine();
  7993. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  7994. var effectiveMaterial = subMesh.getMaterial();
  7995. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  7996. return;
  7997. }
  7998. var savedDepthWrite = engine.getDepthWrite();
  7999. if (this.renderOutline) {
  8000. engine.setDepthWrite(false);
  8001. scene.getOutlineRenderer().render(subMesh, batch);
  8002. }
  8003. effectiveMaterial._preBind();
  8004. var effect = effectiveMaterial.getEffect();
  8005. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8006. this._bind(subMesh, effect, wireFrame);
  8007. var world = this.getWorldMatrix();
  8008. effectiveMaterial.bind(world, this);
  8009. if (hardwareInstancedRendering) {
  8010. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8011. } else {
  8012. if (batch.renderSelf[subMesh._id]) {
  8013. this._draw(subMesh, !wireFrame);
  8014. }
  8015. if (batch.visibleInstances[subMesh._id]) {
  8016. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8017. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8018. world = instance.getWorldMatrix();
  8019. effectiveMaterial.bindOnlyWorldMatrix(world);
  8020. this._draw(subMesh, !wireFrame);
  8021. }
  8022. }
  8023. }
  8024. effectiveMaterial.unbind();
  8025. if (this.renderOutline && savedDepthWrite) {
  8026. engine.setDepthWrite(true);
  8027. engine.setColorWrite(false);
  8028. scene.getOutlineRenderer().render(subMesh, batch);
  8029. engine.setColorWrite(true);
  8030. }
  8031. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8032. this._onAfterRenderCallbacks[callbackIndex]();
  8033. }
  8034. };
  8035. Mesh.prototype.getEmittedParticleSystems = function () {
  8036. var results = new Array();
  8037. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8038. var particleSystem = this.getScene().particleSystems[index];
  8039. if (particleSystem.emitter === this) {
  8040. results.push(particleSystem);
  8041. }
  8042. }
  8043. return results;
  8044. };
  8045. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8046. var results = new Array();
  8047. var descendants = this.getDescendants();
  8048. descendants.push(this);
  8049. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8050. var particleSystem = this.getScene().particleSystems[index];
  8051. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8052. results.push(particleSystem);
  8053. }
  8054. }
  8055. return results;
  8056. };
  8057. Mesh.prototype.getChildren = function () {
  8058. var results = [];
  8059. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8060. var mesh = this.getScene().meshes[index];
  8061. if (mesh.parent == this) {
  8062. results.push(mesh);
  8063. }
  8064. }
  8065. return results;
  8066. };
  8067. Mesh.prototype._checkDelayState = function () {
  8068. var _this = this;
  8069. var that = this;
  8070. var scene = this.getScene();
  8071. if (this._geometry) {
  8072. this._geometry.load(scene);
  8073. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8074. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8075. scene._addPendingData(that);
  8076. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8077. _this._delayLoadingFunction(JSON.parse(data), _this);
  8078. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8079. scene._removePendingData(_this);
  8080. }, function () {
  8081. }, scene.database);
  8082. }
  8083. };
  8084. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8085. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8086. return false;
  8087. }
  8088. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8089. return false;
  8090. }
  8091. this._checkDelayState();
  8092. return true;
  8093. };
  8094. Mesh.prototype.setMaterialByID = function (id) {
  8095. var materials = this.getScene().materials;
  8096. for (var index = 0; index < materials.length; index++) {
  8097. if (materials[index].id == id) {
  8098. this.material = materials[index];
  8099. return;
  8100. }
  8101. }
  8102. var multiMaterials = this.getScene().multiMaterials;
  8103. for (index = 0; index < multiMaterials.length; index++) {
  8104. if (multiMaterials[index].id == id) {
  8105. this.material = multiMaterials[index];
  8106. return;
  8107. }
  8108. }
  8109. };
  8110. Mesh.prototype.getAnimatables = function () {
  8111. var results = [];
  8112. if (this.material) {
  8113. results.push(this.material);
  8114. }
  8115. return results;
  8116. };
  8117. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8118. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8119. return;
  8120. }
  8121. this._resetPointsArrayCache();
  8122. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8123. var temp = [];
  8124. for (var index = 0; index < data.length; index += 3) {
  8125. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8126. }
  8127. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8128. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8129. return;
  8130. }
  8131. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8132. for (index = 0; index < data.length; index += 3) {
  8133. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8134. }
  8135. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8136. };
  8137. Mesh.prototype._resetPointsArrayCache = function () {
  8138. this._positions = null;
  8139. };
  8140. Mesh.prototype._generatePointsArray = function () {
  8141. if (this._positions)
  8142. return true;
  8143. this._positions = [];
  8144. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8145. if (!data) {
  8146. return false;
  8147. }
  8148. for (var index = 0; index < data.length; index += 3) {
  8149. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8150. }
  8151. return true;
  8152. };
  8153. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8154. var result = new BABYLON.Mesh(name, this.getScene());
  8155. this._geometry.applyToMesh(result);
  8156. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8157. result.material = this.material;
  8158. if (newParent) {
  8159. result.parent = newParent;
  8160. }
  8161. if (!doNotCloneChildren) {
  8162. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8163. var mesh = this.getScene().meshes[index];
  8164. if (mesh.parent == this) {
  8165. mesh.clone(mesh.name, result);
  8166. }
  8167. }
  8168. }
  8169. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8170. var system = this.getScene().particleSystems[index];
  8171. if (system.emitter == this) {
  8172. system.clone(system.name, result);
  8173. }
  8174. }
  8175. result.computeWorldMatrix(true);
  8176. return result;
  8177. };
  8178. Mesh.prototype.dispose = function (doNotRecurse) {
  8179. if (this._geometry) {
  8180. this._geometry.releaseForMesh(this, true);
  8181. }
  8182. if (this._worldMatricesInstancesBuffer) {
  8183. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8184. this._worldMatricesInstancesBuffer = null;
  8185. }
  8186. while (this.instances.length) {
  8187. this.instances[0].dispose();
  8188. }
  8189. _super.prototype.dispose.call(this, doNotRecurse);
  8190. };
  8191. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8192. var _this = this;
  8193. var scene = this.getScene();
  8194. var onload = function (img) {
  8195. var canvas = document.createElement("canvas");
  8196. var context = canvas.getContext("2d");
  8197. var heightMapWidth = img.width;
  8198. var heightMapHeight = img.height;
  8199. canvas.width = heightMapWidth;
  8200. canvas.height = heightMapHeight;
  8201. context.drawImage(img, 0, 0);
  8202. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8203. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8204. };
  8205. BABYLON.Tools.LoadImage(url, onload, function () {
  8206. }, scene.database);
  8207. };
  8208. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8209. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8210. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8211. return;
  8212. }
  8213. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8214. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8215. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8216. var position = BABYLON.Vector3.Zero();
  8217. var normal = BABYLON.Vector3.Zero();
  8218. var uv = BABYLON.Vector2.Zero();
  8219. for (var index = 0; index < positions.length; index += 3) {
  8220. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8221. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8222. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8223. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8224. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8225. var pos = (u + v * heightMapWidth) * 4;
  8226. var r = buffer[pos] / 255.0;
  8227. var g = buffer[pos + 1] / 255.0;
  8228. var b = buffer[pos + 2] / 255.0;
  8229. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8230. normal.normalize();
  8231. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8232. position = position.add(normal);
  8233. position.toArray(positions, index);
  8234. }
  8235. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8236. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8237. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8238. };
  8239. Mesh.prototype.convertToFlatShadedMesh = function () {
  8240. var kinds = this.getVerticesDataKinds();
  8241. var vbs = [];
  8242. var data = [];
  8243. var newdata = [];
  8244. var updatableNormals = false;
  8245. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8246. var kind = kinds[kindIndex];
  8247. var vertexBuffer = this.getVertexBuffer(kind);
  8248. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8249. updatableNormals = vertexBuffer.isUpdatable();
  8250. kinds.splice(kindIndex, 1);
  8251. kindIndex--;
  8252. continue;
  8253. }
  8254. vbs[kind] = vertexBuffer;
  8255. data[kind] = vbs[kind].getData();
  8256. newdata[kind] = [];
  8257. }
  8258. var previousSubmeshes = this.subMeshes.slice(0);
  8259. var indices = this.getIndices();
  8260. var totalIndices = this.getTotalIndices();
  8261. for (index = 0; index < totalIndices; index++) {
  8262. var vertexIndex = indices[index];
  8263. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8264. kind = kinds[kindIndex];
  8265. var stride = vbs[kind].getStrideSize();
  8266. for (var offset = 0; offset < stride; offset++) {
  8267. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8268. }
  8269. }
  8270. }
  8271. var normals = [];
  8272. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8273. for (var index = 0; index < totalIndices; index += 3) {
  8274. indices[index] = index;
  8275. indices[index + 1] = index + 1;
  8276. indices[index + 2] = index + 2;
  8277. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8278. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8279. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8280. var p1p2 = p1.subtract(p2);
  8281. var p3p2 = p3.subtract(p2);
  8282. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8283. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8284. normals.push(normal.x);
  8285. normals.push(normal.y);
  8286. normals.push(normal.z);
  8287. }
  8288. }
  8289. this.setIndices(indices);
  8290. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8291. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8292. kind = kinds[kindIndex];
  8293. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8294. }
  8295. this.releaseSubMeshes();
  8296. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8297. var previousOne = previousSubmeshes[submeshIndex];
  8298. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8299. }
  8300. this.synchronizeInstances();
  8301. };
  8302. Mesh.prototype.createInstance = function (name) {
  8303. return new BABYLON.InstancedMesh(name, this);
  8304. };
  8305. Mesh.prototype.synchronizeInstances = function () {
  8306. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8307. var instance = this.instances[instanceIndex];
  8308. instance._syncSubMeshes();
  8309. }
  8310. };
  8311. Mesh.CreateBox = function (name, size, scene, updatable) {
  8312. var box = new BABYLON.Mesh(name, scene);
  8313. var vertexData = BABYLON.VertexData.CreateBox(size);
  8314. vertexData.applyToMesh(box, updatable);
  8315. return box;
  8316. };
  8317. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8318. var sphere = new BABYLON.Mesh(name, scene);
  8319. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8320. vertexData.applyToMesh(sphere, updatable);
  8321. return sphere;
  8322. };
  8323. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8324. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8325. if (scene !== undefined) {
  8326. updatable = scene;
  8327. }
  8328. scene = subdivisions;
  8329. subdivisions = 1;
  8330. }
  8331. var cylinder = new BABYLON.Mesh(name, scene);
  8332. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8333. vertexData.applyToMesh(cylinder, updatable);
  8334. return cylinder;
  8335. };
  8336. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8337. var torus = new BABYLON.Mesh(name, scene);
  8338. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8339. vertexData.applyToMesh(torus, updatable);
  8340. return torus;
  8341. };
  8342. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8343. var torusKnot = new BABYLON.Mesh(name, scene);
  8344. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8345. vertexData.applyToMesh(torusKnot, updatable);
  8346. return torusKnot;
  8347. };
  8348. Mesh.CreateLines = function (name, points, scene, updatable) {
  8349. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8350. var vertexData = BABYLON.VertexData.CreateLines(points);
  8351. vertexData.applyToMesh(lines, updatable);
  8352. return lines;
  8353. };
  8354. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8355. var plane = new BABYLON.Mesh(name, scene);
  8356. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8357. vertexData.applyToMesh(plane, updatable);
  8358. return plane;
  8359. };
  8360. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8361. var ground = new BABYLON.GroundMesh(name, scene);
  8362. ground._setReady(false);
  8363. ground._subdivisions = subdivisions;
  8364. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8365. vertexData.applyToMesh(ground, updatable);
  8366. ground._setReady(true);
  8367. return ground;
  8368. };
  8369. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8370. var tiledGround = new BABYLON.Mesh(name, scene);
  8371. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8372. vertexData.applyToMesh(tiledGround, updatable);
  8373. return tiledGround;
  8374. };
  8375. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8376. var ground = new BABYLON.GroundMesh(name, scene);
  8377. ground._subdivisions = subdivisions;
  8378. ground._setReady(false);
  8379. var onload = function (img) {
  8380. var canvas = document.createElement("canvas");
  8381. var context = canvas.getContext("2d");
  8382. var heightMapWidth = img.width;
  8383. var heightMapHeight = img.height;
  8384. canvas.width = heightMapWidth;
  8385. canvas.height = heightMapHeight;
  8386. context.drawImage(img, 0, 0);
  8387. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8388. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8389. vertexData.applyToMesh(ground, updatable);
  8390. ground._setReady(true);
  8391. };
  8392. BABYLON.Tools.LoadImage(url, onload, function () {
  8393. }, scene.database);
  8394. return ground;
  8395. };
  8396. Mesh.MinMax = function (meshes) {
  8397. var minVector = null;
  8398. var maxVector = null;
  8399. for (var i in meshes) {
  8400. var mesh = meshes[i];
  8401. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8402. if (!minVector) {
  8403. minVector = boundingBox.minimumWorld;
  8404. maxVector = boundingBox.maximumWorld;
  8405. continue;
  8406. }
  8407. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8408. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8409. }
  8410. return {
  8411. min: minVector,
  8412. max: maxVector
  8413. };
  8414. };
  8415. Mesh.Center = function (meshesOrMinMaxVector) {
  8416. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8417. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8418. };
  8419. return Mesh;
  8420. })(BABYLON.AbstractMesh);
  8421. BABYLON.Mesh = Mesh;
  8422. })(BABYLON || (BABYLON = {}));
  8423. var __extends = this.__extends || function (d, b) {
  8424. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8425. function __() { this.constructor = d; }
  8426. __.prototype = b.prototype;
  8427. d.prototype = new __();
  8428. };
  8429. var BABYLON;
  8430. (function (BABYLON) {
  8431. var GroundMesh = (function (_super) {
  8432. __extends(GroundMesh, _super);
  8433. function GroundMesh(name, scene) {
  8434. _super.call(this, name, scene);
  8435. this.generateOctree = false;
  8436. this._worldInverse = new BABYLON.Matrix();
  8437. }
  8438. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8439. get: function () {
  8440. return this._subdivisions;
  8441. },
  8442. enumerable: true,
  8443. configurable: true
  8444. });
  8445. GroundMesh.prototype.optimize = function (chunksCount) {
  8446. this.subdivide(this._subdivisions);
  8447. this.createOrUpdateSubmeshesOctree(32);
  8448. };
  8449. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8450. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8451. this.getWorldMatrix().invertToRef(this._worldInverse);
  8452. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8453. var pickInfo = this.intersects(ray);
  8454. if (pickInfo.hit) {
  8455. return pickInfo.pickedPoint.y;
  8456. }
  8457. return 0;
  8458. };
  8459. return GroundMesh;
  8460. })(BABYLON.Mesh);
  8461. BABYLON.GroundMesh = GroundMesh;
  8462. })(BABYLON || (BABYLON = {}));
  8463. var __extends = this.__extends || function (d, b) {
  8464. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8465. function __() { this.constructor = d; }
  8466. __.prototype = b.prototype;
  8467. d.prototype = new __();
  8468. };
  8469. var BABYLON;
  8470. (function (BABYLON) {
  8471. var InstancedMesh = (function (_super) {
  8472. __extends(InstancedMesh, _super);
  8473. function InstancedMesh(name, source) {
  8474. _super.call(this, name, source.getScene());
  8475. source.instances.push(this);
  8476. this._sourceMesh = source;
  8477. this.position.copyFrom(source.position);
  8478. this.rotation.copyFrom(source.rotation);
  8479. this.scaling.copyFrom(source.scaling);
  8480. if (source.rotationQuaternion) {
  8481. this.rotationQuaternion = source.rotationQuaternion.clone();
  8482. }
  8483. this.infiniteDistance = source.infiniteDistance;
  8484. this.setPivotMatrix(source.getPivotMatrix());
  8485. this.refreshBoundingInfo();
  8486. this._syncSubMeshes();
  8487. }
  8488. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8489. get: function () {
  8490. return this._sourceMesh.receiveShadows;
  8491. },
  8492. enumerable: true,
  8493. configurable: true
  8494. });
  8495. Object.defineProperty(InstancedMesh.prototype, "material", {
  8496. get: function () {
  8497. return this._sourceMesh.material;
  8498. },
  8499. enumerable: true,
  8500. configurable: true
  8501. });
  8502. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8503. get: function () {
  8504. return this._sourceMesh.visibility;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8510. get: function () {
  8511. return this._sourceMesh.skeleton;
  8512. },
  8513. enumerable: true,
  8514. configurable: true
  8515. });
  8516. InstancedMesh.prototype.getTotalVertices = function () {
  8517. return this._sourceMesh.getTotalVertices();
  8518. };
  8519. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8520. get: function () {
  8521. return this._sourceMesh;
  8522. },
  8523. enumerable: true,
  8524. configurable: true
  8525. });
  8526. InstancedMesh.prototype.getVerticesData = function (kind) {
  8527. return this._sourceMesh.getVerticesData(kind);
  8528. };
  8529. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8530. return this._sourceMesh.isVerticesDataPresent(kind);
  8531. };
  8532. InstancedMesh.prototype.getIndices = function () {
  8533. return this._sourceMesh.getIndices();
  8534. };
  8535. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8536. get: function () {
  8537. return this._sourceMesh._positions;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8543. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8544. if (data) {
  8545. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8546. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8547. }
  8548. this._updateBoundingInfo();
  8549. };
  8550. InstancedMesh.prototype._preActivate = function () {
  8551. this.sourceMesh._preActivate();
  8552. };
  8553. InstancedMesh.prototype._activate = function (renderId) {
  8554. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8555. };
  8556. InstancedMesh.prototype._syncSubMeshes = function () {
  8557. this.releaseSubMeshes();
  8558. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8559. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8560. }
  8561. };
  8562. InstancedMesh.prototype._generatePointsArray = function () {
  8563. return this._sourceMesh._generatePointsArray();
  8564. };
  8565. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8566. var result = this._sourceMesh.createInstance(name);
  8567. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8568. this.refreshBoundingInfo();
  8569. if (newParent) {
  8570. result.parent = newParent;
  8571. }
  8572. if (!doNotCloneChildren) {
  8573. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8574. var mesh = this.getScene().meshes[index];
  8575. if (mesh.parent == this) {
  8576. mesh.clone(mesh.name, result);
  8577. }
  8578. }
  8579. }
  8580. result.computeWorldMatrix(true);
  8581. return result;
  8582. };
  8583. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8584. var index = this._sourceMesh.instances.indexOf(this);
  8585. this._sourceMesh.instances.splice(index, 1);
  8586. _super.prototype.dispose.call(this, doNotRecurse);
  8587. };
  8588. return InstancedMesh;
  8589. })(BABYLON.AbstractMesh);
  8590. BABYLON.InstancedMesh = InstancedMesh;
  8591. })(BABYLON || (BABYLON = {}));
  8592. var BABYLON;
  8593. (function (BABYLON) {
  8594. var SubMesh = (function () {
  8595. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8596. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8597. this.materialIndex = materialIndex;
  8598. this.verticesStart = verticesStart;
  8599. this.verticesCount = verticesCount;
  8600. this.indexStart = indexStart;
  8601. this.indexCount = indexCount;
  8602. this._renderId = 0;
  8603. this._mesh = mesh;
  8604. this._renderingMesh = renderingMesh || mesh;
  8605. mesh.subMeshes.push(this);
  8606. this._id = mesh.subMeshes.length - 1;
  8607. if (createBoundingBox) {
  8608. this.refreshBoundingInfo();
  8609. }
  8610. }
  8611. SubMesh.prototype.getBoundingInfo = function () {
  8612. return this._boundingInfo;
  8613. };
  8614. SubMesh.prototype.getMesh = function () {
  8615. return this._mesh;
  8616. };
  8617. SubMesh.prototype.getRenderingMesh = function () {
  8618. return this._renderingMesh;
  8619. };
  8620. SubMesh.prototype.getMaterial = function () {
  8621. var rootMaterial = this._renderingMesh.material;
  8622. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8623. var multiMaterial = rootMaterial;
  8624. return multiMaterial.getSubMaterial(this.materialIndex);
  8625. }
  8626. if (!rootMaterial) {
  8627. return this._mesh.getScene().defaultMaterial;
  8628. }
  8629. return rootMaterial;
  8630. };
  8631. SubMesh.prototype.refreshBoundingInfo = function () {
  8632. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8633. if (!data) {
  8634. this._boundingInfo = this._mesh._boundingInfo;
  8635. return;
  8636. }
  8637. var indices = this._renderingMesh.getIndices();
  8638. var extend;
  8639. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8640. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8641. } else {
  8642. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8643. }
  8644. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8645. };
  8646. SubMesh.prototype._checkCollision = function (collider) {
  8647. return this._boundingInfo._checkCollision(collider);
  8648. };
  8649. SubMesh.prototype.updateBoundingInfo = function (world) {
  8650. if (!this._boundingInfo) {
  8651. this.refreshBoundingInfo();
  8652. }
  8653. this._boundingInfo._update(world);
  8654. };
  8655. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8656. return this._boundingInfo.isInFrustum(frustumPlanes);
  8657. };
  8658. SubMesh.prototype.render = function () {
  8659. this._renderingMesh.render(this);
  8660. };
  8661. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8662. if (!this._linesIndexBuffer) {
  8663. var linesIndices = [];
  8664. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8665. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8666. }
  8667. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8668. this.linesIndexCount = linesIndices.length;
  8669. }
  8670. return this._linesIndexBuffer;
  8671. };
  8672. SubMesh.prototype.canIntersects = function (ray) {
  8673. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8674. };
  8675. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8676. var intersectInfo = null;
  8677. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8678. var p0 = positions[indices[index]];
  8679. var p1 = positions[indices[index + 1]];
  8680. var p2 = positions[indices[index + 2]];
  8681. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8682. if (currentIntersectInfo) {
  8683. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8684. intersectInfo = currentIntersectInfo;
  8685. intersectInfo.faceId = index / 3;
  8686. if (fastCheck) {
  8687. break;
  8688. }
  8689. }
  8690. }
  8691. }
  8692. return intersectInfo;
  8693. };
  8694. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8695. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8696. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8697. return result;
  8698. };
  8699. SubMesh.prototype.dispose = function () {
  8700. if (this._linesIndexBuffer) {
  8701. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8702. this._linesIndexBuffer = null;
  8703. }
  8704. var index = this._mesh.subMeshes.indexOf(this);
  8705. this._mesh.subMeshes.splice(index, 1);
  8706. };
  8707. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8708. var minVertexIndex = Number.MAX_VALUE;
  8709. var maxVertexIndex = -Number.MAX_VALUE;
  8710. renderingMesh = renderingMesh || mesh;
  8711. var indices = renderingMesh.getIndices();
  8712. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8713. var vertexIndex = indices[index];
  8714. if (vertexIndex < minVertexIndex)
  8715. minVertexIndex = vertexIndex;
  8716. if (vertexIndex > maxVertexIndex)
  8717. maxVertexIndex = vertexIndex;
  8718. }
  8719. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8720. };
  8721. return SubMesh;
  8722. })();
  8723. BABYLON.SubMesh = SubMesh;
  8724. })(BABYLON || (BABYLON = {}));
  8725. var BABYLON;
  8726. (function (BABYLON) {
  8727. var BaseTexture = (function () {
  8728. function BaseTexture(scene) {
  8729. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8730. this.hasAlpha = false;
  8731. this.getAlphaFromRGB = false;
  8732. this.level = 1;
  8733. this.isCube = false;
  8734. this.isRenderTarget = false;
  8735. this.animations = new Array();
  8736. this.coordinatesIndex = 0;
  8737. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8738. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8739. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8740. this.anisotropicFilteringLevel = 4;
  8741. this._scene = scene;
  8742. this._scene.textures.push(this);
  8743. }
  8744. BaseTexture.prototype.getScene = function () {
  8745. return this._scene;
  8746. };
  8747. BaseTexture.prototype.getTextureMatrix = function () {
  8748. return null;
  8749. };
  8750. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8751. return null;
  8752. };
  8753. BaseTexture.prototype.getInternalTexture = function () {
  8754. return this._texture;
  8755. };
  8756. BaseTexture.prototype.isReady = function () {
  8757. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8758. return true;
  8759. }
  8760. if (this._texture) {
  8761. return this._texture.isReady;
  8762. }
  8763. return false;
  8764. };
  8765. BaseTexture.prototype.getSize = function () {
  8766. if (this._texture._width) {
  8767. return { width: this._texture._width, height: this._texture._height };
  8768. }
  8769. if (this._texture._size) {
  8770. return { width: this._texture._size, height: this._texture._size };
  8771. }
  8772. return { width: 0, height: 0 };
  8773. };
  8774. BaseTexture.prototype.getBaseSize = function () {
  8775. if (!this.isReady())
  8776. return { width: 0, height: 0 };
  8777. if (this._texture._size) {
  8778. return { width: this._texture._size, height: this._texture._size };
  8779. }
  8780. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8781. };
  8782. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8783. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8784. for (var index = 0; index < texturesCache.length; index++) {
  8785. var texturesCacheEntry = texturesCache[index];
  8786. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8787. texturesCacheEntry.references++;
  8788. return texturesCacheEntry;
  8789. }
  8790. }
  8791. return null;
  8792. };
  8793. BaseTexture.prototype.delayLoad = function () {
  8794. };
  8795. BaseTexture.prototype.releaseInternalTexture = function () {
  8796. if (!this._texture) {
  8797. return;
  8798. }
  8799. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8800. this._texture.references--;
  8801. if (this._texture.references == 0) {
  8802. var index = texturesCache.indexOf(this._texture);
  8803. texturesCache.splice(index, 1);
  8804. this._scene.getEngine()._releaseTexture(this._texture);
  8805. delete this._texture;
  8806. }
  8807. };
  8808. BaseTexture.prototype.clone = function () {
  8809. return null;
  8810. };
  8811. BaseTexture.prototype.dispose = function () {
  8812. var index = this._scene.textures.indexOf(this);
  8813. if (index >= 0) {
  8814. this._scene.textures.splice(index, 1);
  8815. }
  8816. if (this._texture === undefined) {
  8817. return;
  8818. }
  8819. this.releaseInternalTexture();
  8820. if (this.onDispose) {
  8821. this.onDispose();
  8822. }
  8823. };
  8824. return BaseTexture;
  8825. })();
  8826. BABYLON.BaseTexture = BaseTexture;
  8827. })(BABYLON || (BABYLON = {}));
  8828. var BABYLON;
  8829. (function (BABYLON) {
  8830. var RenderingGroup = (function () {
  8831. function RenderingGroup(index, scene) {
  8832. this.index = index;
  8833. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8834. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8835. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8836. this._scene = scene;
  8837. }
  8838. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8839. if (customRenderFunction) {
  8840. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8841. return true;
  8842. }
  8843. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8844. return false;
  8845. }
  8846. var engine = this._scene.getEngine();
  8847. var subIndex;
  8848. var submesh;
  8849. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8850. submesh = this._opaqueSubMeshes.data[subIndex];
  8851. this._activeVertices += submesh.verticesCount;
  8852. submesh.render();
  8853. }
  8854. engine.setAlphaTesting(true);
  8855. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8856. submesh = this._alphaTestSubMeshes.data[subIndex];
  8857. this._activeVertices += submesh.verticesCount;
  8858. submesh.render();
  8859. }
  8860. engine.setAlphaTesting(false);
  8861. if (beforeTransparents) {
  8862. beforeTransparents();
  8863. }
  8864. if (this._transparentSubMeshes.length) {
  8865. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8866. submesh = this._transparentSubMeshes.data[subIndex];
  8867. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8868. }
  8869. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8870. sortedArray.sort(function (a, b) {
  8871. if (a._distanceToCamera < b._distanceToCamera) {
  8872. return 1;
  8873. }
  8874. if (a._distanceToCamera > b._distanceToCamera) {
  8875. return -1;
  8876. }
  8877. return 0;
  8878. });
  8879. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8880. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8881. submesh = sortedArray[subIndex];
  8882. this._activeVertices += submesh.verticesCount;
  8883. submesh.render();
  8884. }
  8885. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8886. }
  8887. return true;
  8888. };
  8889. RenderingGroup.prototype.prepare = function () {
  8890. this._opaqueSubMeshes.reset();
  8891. this._transparentSubMeshes.reset();
  8892. this._alphaTestSubMeshes.reset();
  8893. };
  8894. RenderingGroup.prototype.dispatch = function (subMesh) {
  8895. var material = subMesh.getMaterial();
  8896. var mesh = subMesh.getMesh();
  8897. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8898. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8899. this._transparentSubMeshes.push(subMesh);
  8900. }
  8901. } else if (material.needAlphaTesting()) {
  8902. this._alphaTestSubMeshes.push(subMesh);
  8903. } else {
  8904. this._opaqueSubMeshes.push(subMesh);
  8905. }
  8906. };
  8907. return RenderingGroup;
  8908. })();
  8909. BABYLON.RenderingGroup = RenderingGroup;
  8910. })(BABYLON || (BABYLON = {}));
  8911. var BABYLON;
  8912. (function (BABYLON) {
  8913. var RenderingManager = (function () {
  8914. function RenderingManager(scene) {
  8915. this._renderingGroups = new Array();
  8916. this._scene = scene;
  8917. }
  8918. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  8919. if (this._scene._activeParticleSystems.length === 0) {
  8920. return;
  8921. }
  8922. var beforeParticlesDate = new Date().getTime();
  8923. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  8924. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  8925. if (particleSystem.renderingGroupId !== index) {
  8926. continue;
  8927. }
  8928. this._clearDepthBuffer();
  8929. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  8930. this._scene._activeParticles += particleSystem.render();
  8931. }
  8932. }
  8933. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8934. };
  8935. RenderingManager.prototype._renderSprites = function (index) {
  8936. if (this._scene.spriteManagers.length === 0) {
  8937. return;
  8938. }
  8939. var beforeSpritessDate = new Date().getTime();
  8940. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  8941. var spriteManager = this._scene.spriteManagers[id];
  8942. if (spriteManager.renderingGroupId === index) {
  8943. this._clearDepthBuffer();
  8944. spriteManager.render();
  8945. }
  8946. }
  8947. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  8948. };
  8949. RenderingManager.prototype._clearDepthBuffer = function () {
  8950. if (this._depthBufferAlreadyCleaned) {
  8951. return;
  8952. }
  8953. this._scene.getEngine().clear(0, false, true);
  8954. this._depthBufferAlreadyCleaned = true;
  8955. };
  8956. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  8957. var _this = this;
  8958. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  8959. this._depthBufferAlreadyCleaned = false;
  8960. var renderingGroup = this._renderingGroups[index];
  8961. if (renderingGroup) {
  8962. this._clearDepthBuffer();
  8963. if (!renderingGroup.render(customRenderFunction, function () {
  8964. if (renderSprites) {
  8965. _this._renderSprites(index);
  8966. }
  8967. })) {
  8968. this._renderingGroups.splice(index, 1);
  8969. }
  8970. } else if (renderSprites) {
  8971. this._renderSprites(index);
  8972. }
  8973. if (renderParticles) {
  8974. this._renderParticles(index, activeMeshes);
  8975. }
  8976. }
  8977. };
  8978. RenderingManager.prototype.reset = function () {
  8979. for (var index in this._renderingGroups) {
  8980. var renderingGroup = this._renderingGroups[index];
  8981. renderingGroup.prepare();
  8982. }
  8983. };
  8984. RenderingManager.prototype.dispatch = function (subMesh) {
  8985. var mesh = subMesh.getMesh();
  8986. var renderingGroupId = mesh.renderingGroupId || 0;
  8987. if (!this._renderingGroups[renderingGroupId]) {
  8988. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  8989. }
  8990. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  8991. };
  8992. RenderingManager.MAX_RENDERINGGROUPS = 4;
  8993. return RenderingManager;
  8994. })();
  8995. BABYLON.RenderingManager = RenderingManager;
  8996. })(BABYLON || (BABYLON = {}));
  8997. var __extends = this.__extends || function (d, b) {
  8998. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8999. function __() { this.constructor = d; }
  9000. __.prototype = b.prototype;
  9001. d.prototype = new __();
  9002. };
  9003. var BABYLON;
  9004. (function (BABYLON) {
  9005. var Texture = (function (_super) {
  9006. __extends(Texture, _super);
  9007. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  9008. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9009. _super.call(this, scene);
  9010. this.uOffset = 0;
  9011. this.vOffset = 0;
  9012. this.uScale = 1.0;
  9013. this.vScale = 1.0;
  9014. this.uAng = 0;
  9015. this.vAng = 0;
  9016. this.wAng = 0;
  9017. this.name = url;
  9018. this.url = url;
  9019. this._noMipmap = noMipmap;
  9020. this._invertY = invertY;
  9021. this._samplingMode = samplingMode;
  9022. if (!url) {
  9023. return;
  9024. }
  9025. this._texture = this._getFromCache(url, noMipmap);
  9026. if (!this._texture) {
  9027. if (!scene.useDelayedTextureLoading) {
  9028. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  9029. } else {
  9030. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9031. }
  9032. }
  9033. }
  9034. Texture.prototype.delayLoad = function () {
  9035. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9036. return;
  9037. }
  9038. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9039. this._texture = this._getFromCache(this.url, this._noMipmap);
  9040. if (!this._texture) {
  9041. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9042. }
  9043. };
  9044. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9045. x -= this.uOffset + 0.5;
  9046. y -= this.vOffset + 0.5;
  9047. z -= 0.5;
  9048. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9049. t.x *= this.uScale;
  9050. t.y *= this.vScale;
  9051. t.x += 0.5;
  9052. t.y += 0.5;
  9053. t.z += 0.5;
  9054. };
  9055. Texture.prototype.getTextureMatrix = function () {
  9056. 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) {
  9057. return this._cachedTextureMatrix;
  9058. }
  9059. this._cachedUOffset = this.uOffset;
  9060. this._cachedVOffset = this.vOffset;
  9061. this._cachedUScale = this.uScale;
  9062. this._cachedVScale = this.vScale;
  9063. this._cachedUAng = this.uAng;
  9064. this._cachedVAng = this.vAng;
  9065. this._cachedWAng = this.wAng;
  9066. if (!this._cachedTextureMatrix) {
  9067. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9068. this._rowGenerationMatrix = new BABYLON.Matrix();
  9069. this._t0 = BABYLON.Vector3.Zero();
  9070. this._t1 = BABYLON.Vector3.Zero();
  9071. this._t2 = BABYLON.Vector3.Zero();
  9072. }
  9073. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9074. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9075. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9076. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9077. this._t1.subtractInPlace(this._t0);
  9078. this._t2.subtractInPlace(this._t0);
  9079. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9080. this._cachedTextureMatrix.m[0] = this._t1.x;
  9081. this._cachedTextureMatrix.m[1] = this._t1.y;
  9082. this._cachedTextureMatrix.m[2] = this._t1.z;
  9083. this._cachedTextureMatrix.m[4] = this._t2.x;
  9084. this._cachedTextureMatrix.m[5] = this._t2.y;
  9085. this._cachedTextureMatrix.m[6] = this._t2.z;
  9086. this._cachedTextureMatrix.m[8] = this._t0.x;
  9087. this._cachedTextureMatrix.m[9] = this._t0.y;
  9088. this._cachedTextureMatrix.m[10] = this._t0.z;
  9089. return this._cachedTextureMatrix;
  9090. };
  9091. Texture.prototype.getReflectionTextureMatrix = function () {
  9092. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9093. return this._cachedTextureMatrix;
  9094. }
  9095. if (!this._cachedTextureMatrix) {
  9096. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9097. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9098. }
  9099. switch (this.coordinatesMode) {
  9100. case BABYLON.Texture.SPHERICAL_MODE:
  9101. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9102. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9103. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9104. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9105. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9106. break;
  9107. case BABYLON.Texture.PLANAR_MODE:
  9108. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9109. this._cachedTextureMatrix[0] = this.uScale;
  9110. this._cachedTextureMatrix[5] = this.vScale;
  9111. this._cachedTextureMatrix[12] = this.uOffset;
  9112. this._cachedTextureMatrix[13] = this.vOffset;
  9113. break;
  9114. case BABYLON.Texture.PROJECTION_MODE:
  9115. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9116. this._projectionModeMatrix.m[0] = 0.5;
  9117. this._projectionModeMatrix.m[5] = -0.5;
  9118. this._projectionModeMatrix.m[10] = 0.0;
  9119. this._projectionModeMatrix.m[12] = 0.5;
  9120. this._projectionModeMatrix.m[13] = 0.5;
  9121. this._projectionModeMatrix.m[14] = 1.0;
  9122. this._projectionModeMatrix.m[15] = 1.0;
  9123. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9124. break;
  9125. default:
  9126. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9127. break;
  9128. }
  9129. return this._cachedTextureMatrix;
  9130. };
  9131. Texture.prototype.clone = function () {
  9132. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9133. newTexture.hasAlpha = this.hasAlpha;
  9134. newTexture.level = this.level;
  9135. newTexture.wrapU = this.wrapU;
  9136. newTexture.wrapV = this.wrapV;
  9137. newTexture.coordinatesIndex = this.coordinatesIndex;
  9138. newTexture.coordinatesMode = this.coordinatesMode;
  9139. newTexture.uOffset = this.uOffset;
  9140. newTexture.vOffset = this.vOffset;
  9141. newTexture.uScale = this.uScale;
  9142. newTexture.vScale = this.vScale;
  9143. newTexture.uAng = this.uAng;
  9144. newTexture.vAng = this.vAng;
  9145. newTexture.wAng = this.wAng;
  9146. return newTexture;
  9147. };
  9148. Texture.NEAREST_SAMPLINGMODE = 1;
  9149. Texture.BILINEAR_SAMPLINGMODE = 2;
  9150. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9151. Texture.EXPLICIT_MODE = 0;
  9152. Texture.SPHERICAL_MODE = 1;
  9153. Texture.PLANAR_MODE = 2;
  9154. Texture.CUBIC_MODE = 3;
  9155. Texture.PROJECTION_MODE = 4;
  9156. Texture.SKYBOX_MODE = 5;
  9157. Texture.CLAMP_ADDRESSMODE = 0;
  9158. Texture.WRAP_ADDRESSMODE = 1;
  9159. Texture.MIRROR_ADDRESSMODE = 2;
  9160. return Texture;
  9161. })(BABYLON.BaseTexture);
  9162. BABYLON.Texture = Texture;
  9163. })(BABYLON || (BABYLON = {}));
  9164. var __extends = this.__extends || function (d, b) {
  9165. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9166. function __() { this.constructor = d; }
  9167. __.prototype = b.prototype;
  9168. d.prototype = new __();
  9169. };
  9170. var BABYLON;
  9171. (function (BABYLON) {
  9172. var CubeTexture = (function (_super) {
  9173. __extends(CubeTexture, _super);
  9174. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9175. _super.call(this, scene);
  9176. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9177. this.name = rootUrl;
  9178. this.url = rootUrl;
  9179. this._noMipmap = noMipmap;
  9180. this.hasAlpha = false;
  9181. this._texture = this._getFromCache(rootUrl, noMipmap);
  9182. if (!extensions) {
  9183. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9184. }
  9185. this._extensions = extensions;
  9186. if (!this._texture) {
  9187. if (!scene.useDelayedTextureLoading) {
  9188. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9189. } else {
  9190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9191. }
  9192. }
  9193. this.isCube = true;
  9194. this._textureMatrix = BABYLON.Matrix.Identity();
  9195. }
  9196. CubeTexture.prototype.clone = function () {
  9197. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9198. newTexture.level = this.level;
  9199. newTexture.wrapU = this.wrapU;
  9200. newTexture.wrapV = this.wrapV;
  9201. newTexture.coordinatesIndex = this.coordinatesIndex;
  9202. newTexture.coordinatesMode = this.coordinatesMode;
  9203. return newTexture;
  9204. };
  9205. CubeTexture.prototype.delayLoad = function () {
  9206. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9207. return;
  9208. }
  9209. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9210. this._texture = this._getFromCache(this.url, this._noMipmap);
  9211. if (!this._texture) {
  9212. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9213. }
  9214. };
  9215. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9216. return this._textureMatrix;
  9217. };
  9218. return CubeTexture;
  9219. })(BABYLON.BaseTexture);
  9220. BABYLON.CubeTexture = CubeTexture;
  9221. })(BABYLON || (BABYLON = {}));
  9222. var __extends = this.__extends || function (d, b) {
  9223. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9224. function __() { this.constructor = d; }
  9225. __.prototype = b.prototype;
  9226. d.prototype = new __();
  9227. };
  9228. var BABYLON;
  9229. (function (BABYLON) {
  9230. var RenderTargetTexture = (function (_super) {
  9231. __extends(RenderTargetTexture, _super);
  9232. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9233. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9234. _super.call(this, null, scene, !generateMipMaps);
  9235. this.renderList = new Array();
  9236. this.renderParticles = true;
  9237. this.renderSprites = false;
  9238. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9239. this._currentRefreshId = -1;
  9240. this._refreshRate = 1;
  9241. this.name = name;
  9242. this.isRenderTarget = true;
  9243. this._size = size;
  9244. this._generateMipMaps = generateMipMaps;
  9245. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9246. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9247. this._renderingManager = new BABYLON.RenderingManager(scene);
  9248. }
  9249. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9250. this._currentRefreshId = -1;
  9251. };
  9252. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9253. get: function () {
  9254. return this._refreshRate;
  9255. },
  9256. set: function (value) {
  9257. this._refreshRate = value;
  9258. this.resetRefreshCounter();
  9259. },
  9260. enumerable: true,
  9261. configurable: true
  9262. });
  9263. RenderTargetTexture.prototype._shouldRender = function () {
  9264. if (this._currentRefreshId === -1) {
  9265. this._currentRefreshId = 1;
  9266. return true;
  9267. }
  9268. if (this.refreshRate == this._currentRefreshId) {
  9269. this._currentRefreshId = 1;
  9270. return true;
  9271. }
  9272. this._currentRefreshId++;
  9273. return false;
  9274. };
  9275. RenderTargetTexture.prototype.getRenderSize = function () {
  9276. return this._size;
  9277. };
  9278. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9279. this.releaseInternalTexture();
  9280. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9281. };
  9282. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9283. var scene = this.getScene();
  9284. var engine = scene.getEngine();
  9285. if (this._waitingRenderList) {
  9286. this.renderList = [];
  9287. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9288. var id = this._waitingRenderList[index];
  9289. this.renderList.push(scene.getMeshByID(id));
  9290. }
  9291. delete this._waitingRenderList;
  9292. }
  9293. if (!this.renderList) {
  9294. return;
  9295. }
  9296. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9297. engine.bindFramebuffer(this._texture);
  9298. }
  9299. engine.clear(scene.clearColor, true, true);
  9300. this._renderingManager.reset();
  9301. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9302. var mesh = this.renderList[meshIndex];
  9303. if (mesh) {
  9304. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9305. this.resetRefreshCounter();
  9306. continue;
  9307. }
  9308. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9309. mesh._activate(scene.getRenderId());
  9310. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9311. var subMesh = mesh.subMeshes[subIndex];
  9312. scene._activeVertices += subMesh.verticesCount;
  9313. this._renderingManager.dispatch(subMesh);
  9314. }
  9315. }
  9316. }
  9317. }
  9318. if (!this._doNotChangeAspectRatio) {
  9319. scene.updateTransformMatrix(true);
  9320. }
  9321. if (this.onBeforeRender) {
  9322. this.onBeforeRender();
  9323. }
  9324. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9325. if (useCameraPostProcess) {
  9326. scene.postProcessManager._finalizeFrame(false, this._texture);
  9327. }
  9328. if (this.onAfterRender) {
  9329. this.onAfterRender();
  9330. }
  9331. engine.unBindFramebuffer(this._texture);
  9332. if (!this._doNotChangeAspectRatio) {
  9333. scene.updateTransformMatrix(true);
  9334. }
  9335. };
  9336. RenderTargetTexture.prototype.clone = function () {
  9337. var textureSize = this.getSize();
  9338. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9339. newTexture.hasAlpha = this.hasAlpha;
  9340. newTexture.level = this.level;
  9341. newTexture.coordinatesMode = this.coordinatesMode;
  9342. newTexture.renderList = this.renderList.slice(0);
  9343. return newTexture;
  9344. };
  9345. return RenderTargetTexture;
  9346. })(BABYLON.Texture);
  9347. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9348. })(BABYLON || (BABYLON = {}));
  9349. var __extends = this.__extends || function (d, b) {
  9350. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9351. function __() { this.constructor = d; }
  9352. __.prototype = b.prototype;
  9353. d.prototype = new __();
  9354. };
  9355. var BABYLON;
  9356. (function (BABYLON) {
  9357. var MirrorTexture = (function (_super) {
  9358. __extends(MirrorTexture, _super);
  9359. function MirrorTexture(name, size, scene, generateMipMaps) {
  9360. var _this = this;
  9361. _super.call(this, name, size, scene, generateMipMaps, true);
  9362. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9363. this._transformMatrix = BABYLON.Matrix.Zero();
  9364. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9365. this.onBeforeRender = function () {
  9366. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9367. _this._savedViewMatrix = scene.getViewMatrix();
  9368. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9369. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9370. scene.clipPlane = _this.mirrorPlane;
  9371. scene.getEngine().cullBackFaces = false;
  9372. };
  9373. this.onAfterRender = function () {
  9374. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9375. scene.getEngine().cullBackFaces = true;
  9376. delete scene.clipPlane;
  9377. };
  9378. }
  9379. MirrorTexture.prototype.clone = function () {
  9380. var textureSize = this.getSize();
  9381. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9382. newTexture.hasAlpha = this.hasAlpha;
  9383. newTexture.level = this.level;
  9384. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9385. newTexture.renderList = this.renderList.slice(0);
  9386. return newTexture;
  9387. };
  9388. return MirrorTexture;
  9389. })(BABYLON.RenderTargetTexture);
  9390. BABYLON.MirrorTexture = MirrorTexture;
  9391. })(BABYLON || (BABYLON = {}));
  9392. var __extends = this.__extends || function (d, b) {
  9393. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9394. function __() { this.constructor = d; }
  9395. __.prototype = b.prototype;
  9396. d.prototype = new __();
  9397. };
  9398. var BABYLON;
  9399. (function (BABYLON) {
  9400. var DynamicTexture = (function (_super) {
  9401. __extends(DynamicTexture, _super);
  9402. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9403. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9404. _super.call(this, null, scene, !generateMipMaps);
  9405. this.name = name;
  9406. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9407. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9408. this._generateMipMaps = generateMipMaps;
  9409. if (options.getContext) {
  9410. this._canvas = options;
  9411. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9412. } else {
  9413. this._canvas = document.createElement("canvas");
  9414. if (options.width) {
  9415. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9416. } else {
  9417. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9418. }
  9419. }
  9420. var textureSize = this.getSize();
  9421. this._canvas.width = textureSize.width;
  9422. this._canvas.height = textureSize.height;
  9423. this._context = this._canvas.getContext("2d");
  9424. }
  9425. DynamicTexture.prototype.getContext = function () {
  9426. return this._context;
  9427. };
  9428. DynamicTexture.prototype.update = function (invertY) {
  9429. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9430. };
  9431. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9432. var size = this.getSize();
  9433. if (clearColor) {
  9434. this._context.fillStyle = clearColor;
  9435. this._context.fillRect(0, 0, size.width, size.height);
  9436. }
  9437. this._context.font = font;
  9438. if (x === null) {
  9439. var textSize = this._context.measureText(text);
  9440. x = (size.width - textSize.width) / 2;
  9441. }
  9442. this._context.fillStyle = color;
  9443. this._context.fillText(text, x, y);
  9444. this.update(invertY);
  9445. };
  9446. DynamicTexture.prototype.clone = function () {
  9447. var textureSize = this.getSize();
  9448. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9449. newTexture.hasAlpha = this.hasAlpha;
  9450. newTexture.level = this.level;
  9451. newTexture.wrapU = this.wrapU;
  9452. newTexture.wrapV = this.wrapV;
  9453. return newTexture;
  9454. };
  9455. return DynamicTexture;
  9456. })(BABYLON.Texture);
  9457. BABYLON.DynamicTexture = DynamicTexture;
  9458. })(BABYLON || (BABYLON = {}));
  9459. var __extends = this.__extends || function (d, b) {
  9460. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9461. function __() { this.constructor = d; }
  9462. __.prototype = b.prototype;
  9463. d.prototype = new __();
  9464. };
  9465. var BABYLON;
  9466. (function (BABYLON) {
  9467. var VideoTexture = (function (_super) {
  9468. __extends(VideoTexture, _super);
  9469. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9470. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9471. var _this = this;
  9472. _super.call(this, null, scene, !generateMipMaps, invertY);
  9473. this._autoLaunch = true;
  9474. this.name = name;
  9475. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9476. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9477. var requiredWidth = size.width || size;
  9478. var requiredHeight = size.height || size;
  9479. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9480. var textureSize = this.getSize();
  9481. this.video = document.createElement("video");
  9482. this.video.width = textureSize.width;
  9483. this.video.height = textureSize.height;
  9484. this.video.autoplay = false;
  9485. this.video.loop = true;
  9486. this.video.addEventListener("canplaythrough", function () {
  9487. if (_this._texture) {
  9488. _this._texture.isReady = true;
  9489. }
  9490. });
  9491. urls.forEach(function (url) {
  9492. var source = document.createElement("source");
  9493. source.src = url;
  9494. _this.video.appendChild(source);
  9495. });
  9496. this._lastUpdate = new Date().getTime();
  9497. }
  9498. VideoTexture.prototype.update = function () {
  9499. if (this._autoLaunch) {
  9500. this._autoLaunch = false;
  9501. this.video.play();
  9502. }
  9503. var now = new Date().getTime();
  9504. if (now - this._lastUpdate < 15) {
  9505. return false;
  9506. }
  9507. this._lastUpdate = now;
  9508. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9509. return true;
  9510. };
  9511. return VideoTexture;
  9512. })(BABYLON.Texture);
  9513. BABYLON.VideoTexture = VideoTexture;
  9514. })(BABYLON || (BABYLON = {}));
  9515. var BABYLON;
  9516. (function (BABYLON) {
  9517. var EffectFallbacks = (function () {
  9518. function EffectFallbacks() {
  9519. this._defines = {};
  9520. this._currentRank = 32;
  9521. this._maxRank = -1;
  9522. }
  9523. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9524. if (!this._defines[rank]) {
  9525. if (rank < this._currentRank) {
  9526. this._currentRank = rank;
  9527. }
  9528. if (rank > this._maxRank) {
  9529. this._maxRank = rank;
  9530. }
  9531. this._defines[rank] = new Array();
  9532. }
  9533. this._defines[rank].push(define);
  9534. };
  9535. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9536. get: function () {
  9537. return this._currentRank <= this._maxRank;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9543. var currentFallbacks = this._defines[this._currentRank];
  9544. for (var index = 0; index < currentFallbacks.length; index++) {
  9545. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9546. }
  9547. this._currentRank++;
  9548. return currentDefines;
  9549. };
  9550. return EffectFallbacks;
  9551. })();
  9552. BABYLON.EffectFallbacks = EffectFallbacks;
  9553. var Effect = (function () {
  9554. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9555. var _this = this;
  9556. this._isReady = false;
  9557. this._compilationError = "";
  9558. this._valueCache = [];
  9559. this._engine = engine;
  9560. this.name = baseName;
  9561. this.defines = defines;
  9562. this._uniformsNames = uniformsNames.concat(samplers);
  9563. this._samplers = samplers;
  9564. this._attributesNames = attributesNames;
  9565. this.onError = onError;
  9566. this.onCompiled = onCompiled;
  9567. var vertexSource;
  9568. var fragmentSource;
  9569. if (baseName.vertexElement) {
  9570. vertexSource = document.getElementById(baseName.vertexElement);
  9571. } else {
  9572. vertexSource = baseName.vertex || baseName;
  9573. }
  9574. if (baseName.fragmentElement) {
  9575. fragmentSource = document.getElementById(baseName.fragmentElement);
  9576. } else {
  9577. fragmentSource = baseName.fragment || baseName;
  9578. }
  9579. this._loadVertexShader(vertexSource, function (vertexCode) {
  9580. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9581. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9582. });
  9583. });
  9584. }
  9585. Effect.prototype.isReady = function () {
  9586. return this._isReady;
  9587. };
  9588. Effect.prototype.getProgram = function () {
  9589. return this._program;
  9590. };
  9591. Effect.prototype.getAttributesNames = function () {
  9592. return this._attributesNames;
  9593. };
  9594. Effect.prototype.getAttributeLocation = function (index) {
  9595. return this._attributes[index];
  9596. };
  9597. Effect.prototype.getAttributeLocationByName = function (name) {
  9598. var index = this._attributesNames.indexOf(name);
  9599. return this._attributes[index];
  9600. };
  9601. Effect.prototype.getAttributesCount = function () {
  9602. return this._attributes.length;
  9603. };
  9604. Effect.prototype.getUniformIndex = function (uniformName) {
  9605. return this._uniformsNames.indexOf(uniformName);
  9606. };
  9607. Effect.prototype.getUniform = function (uniformName) {
  9608. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9609. };
  9610. Effect.prototype.getSamplers = function () {
  9611. return this._samplers;
  9612. };
  9613. Effect.prototype.getCompilationError = function () {
  9614. return this._compilationError;
  9615. };
  9616. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9617. if (vertex instanceof HTMLElement) {
  9618. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9619. callback(vertexCode);
  9620. return;
  9621. }
  9622. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9623. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9624. return;
  9625. }
  9626. var vertexShaderUrl;
  9627. if (vertex[0] === ".") {
  9628. vertexShaderUrl = vertex;
  9629. } else {
  9630. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9631. }
  9632. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9633. };
  9634. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9635. if (fragment instanceof HTMLElement) {
  9636. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9637. callback(fragmentCode);
  9638. return;
  9639. }
  9640. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9641. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9642. return;
  9643. }
  9644. var fragmentShaderUrl;
  9645. if (fragment[0] === ".") {
  9646. fragmentShaderUrl = fragment;
  9647. } else {
  9648. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9649. }
  9650. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9651. };
  9652. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9653. try {
  9654. var engine = this._engine;
  9655. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9656. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9657. this._attributes = engine.getAttributes(this._program, attributesNames);
  9658. for (var index = 0; index < this._samplers.length; index++) {
  9659. var sampler = this.getUniform(this._samplers[index]);
  9660. if (sampler == null) {
  9661. this._samplers.splice(index, 1);
  9662. index--;
  9663. }
  9664. }
  9665. engine.bindSamplers(this);
  9666. this._isReady = true;
  9667. if (this.onCompiled) {
  9668. this.onCompiled(this);
  9669. }
  9670. } catch (e) {
  9671. if (fallbacks && fallbacks.isMoreFallbacks) {
  9672. defines = fallbacks.reduce(defines);
  9673. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9674. } else {
  9675. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9676. BABYLON.Tools.Error("Defines: " + defines);
  9677. BABYLON.Tools.Error("Error: " + e.message);
  9678. this._compilationError = e.message;
  9679. if (this.onError) {
  9680. this.onError(this, this._compilationError);
  9681. }
  9682. }
  9683. }
  9684. };
  9685. Effect.prototype._bindTexture = function (channel, texture) {
  9686. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9687. };
  9688. Effect.prototype.setTexture = function (channel, texture) {
  9689. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9690. };
  9691. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9692. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9693. };
  9694. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9695. if (!this._valueCache[uniformName]) {
  9696. this._valueCache[uniformName] = [x, y];
  9697. return;
  9698. }
  9699. this._valueCache[uniformName][0] = x;
  9700. this._valueCache[uniformName][1] = y;
  9701. };
  9702. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9703. if (!this._valueCache[uniformName]) {
  9704. this._valueCache[uniformName] = [x, y, z];
  9705. return;
  9706. }
  9707. this._valueCache[uniformName][0] = x;
  9708. this._valueCache[uniformName][1] = y;
  9709. this._valueCache[uniformName][2] = z;
  9710. };
  9711. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9712. if (!this._valueCache[uniformName]) {
  9713. this._valueCache[uniformName] = [x, y, z, w];
  9714. return;
  9715. }
  9716. this._valueCache[uniformName][0] = x;
  9717. this._valueCache[uniformName][1] = y;
  9718. this._valueCache[uniformName][2] = z;
  9719. this._valueCache[uniformName][3] = w;
  9720. };
  9721. Effect.prototype.setArray = function (uniformName, array) {
  9722. this._engine.setArray(this.getUniform(uniformName), array);
  9723. return this;
  9724. };
  9725. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9726. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9727. return this;
  9728. };
  9729. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9730. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9731. return this;
  9732. };
  9733. Effect.prototype.setFloat = function (uniformName, value) {
  9734. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9735. return this;
  9736. this._valueCache[uniformName] = value;
  9737. this._engine.setFloat(this.getUniform(uniformName), value);
  9738. return this;
  9739. };
  9740. Effect.prototype.setBool = function (uniformName, bool) {
  9741. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9742. return this;
  9743. this._valueCache[uniformName] = bool;
  9744. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9745. return this;
  9746. };
  9747. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9748. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9749. return this;
  9750. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9751. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9752. return this;
  9753. };
  9754. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9755. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9756. return this;
  9757. this._cacheFloat2(uniformName, x, y);
  9758. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9759. return this;
  9760. };
  9761. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9762. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9763. return this;
  9764. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9765. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9766. return this;
  9767. };
  9768. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9769. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9770. return this;
  9771. this._cacheFloat3(uniformName, x, y, z);
  9772. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9773. return this;
  9774. };
  9775. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9776. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9777. return this;
  9778. this._cacheFloat4(uniformName, x, y, z, w);
  9779. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9780. return this;
  9781. };
  9782. Effect.prototype.setColor3 = function (uniformName, color3) {
  9783. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9784. return this;
  9785. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9786. this._engine.setColor3(this.getUniform(uniformName), color3);
  9787. return this;
  9788. };
  9789. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9790. 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)
  9791. return this;
  9792. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9793. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9794. return this;
  9795. };
  9796. 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}",
  9797. 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}",
  9798. 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}",
  9799. colorPixelShader:"precision mediump float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9800. 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}",
  9801. 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}",
  9802. 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 + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\n }\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n 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}",
  9803. 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}",
  9804. 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}",
  9805. 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}",
  9806. 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}",
  9807. 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}",
  9808. 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}",
  9809. 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 + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  9810. 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}",
  9811. 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}",
  9812. 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}",
  9813. 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}",
  9814. 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}",
  9815. 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}",
  9816. 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}",
  9817. 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}",
  9818. 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}",
  9819. 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}",
  9820. 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}",
  9821. 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}",
  9822. 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}",
  9823. 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}",
  9824. 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}",
  9825. };
  9826. return Effect;
  9827. })();
  9828. BABYLON.Effect = Effect;
  9829. })(BABYLON || (BABYLON = {}));
  9830. var BABYLON;
  9831. (function (BABYLON) {
  9832. var Material = (function () {
  9833. function Material(name, scene, doNotAdd) {
  9834. this.name = name;
  9835. this.checkReadyOnEveryCall = true;
  9836. this.checkReadyOnlyOnce = false;
  9837. this.state = "";
  9838. this.alpha = 1.0;
  9839. this.wireframe = false;
  9840. this.backFaceCulling = true;
  9841. this._wasPreviouslyReady = false;
  9842. this.id = name;
  9843. this._scene = scene;
  9844. if (!doNotAdd) {
  9845. scene.materials.push(this);
  9846. }
  9847. }
  9848. Material.prototype.isReady = function (mesh, useInstances) {
  9849. return true;
  9850. };
  9851. Material.prototype.getEffect = function () {
  9852. return this._effect;
  9853. };
  9854. Material.prototype.getScene = function () {
  9855. return this._scene;
  9856. };
  9857. Material.prototype.needAlphaBlending = function () {
  9858. return (this.alpha < 1.0);
  9859. };
  9860. Material.prototype.needAlphaTesting = function () {
  9861. return false;
  9862. };
  9863. Material.prototype.getAlphaTestTexture = function () {
  9864. return null;
  9865. };
  9866. Material.prototype.trackCreation = function (onCompiled, onError) {
  9867. };
  9868. Material.prototype._preBind = function () {
  9869. var engine = this._scene.getEngine();
  9870. engine.enableEffect(this._effect);
  9871. engine.setState(this.backFaceCulling);
  9872. };
  9873. Material.prototype.bind = function (world, mesh) {
  9874. };
  9875. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9876. };
  9877. Material.prototype.unbind = function () {
  9878. };
  9879. Material.prototype.dispose = function (forceDisposeEffect) {
  9880. var index = this._scene.materials.indexOf(this);
  9881. this._scene.materials.splice(index, 1);
  9882. if (forceDisposeEffect && this._effect) {
  9883. this._scene.getEngine()._releaseEffect(this._effect);
  9884. this._effect = null;
  9885. }
  9886. if (this.onDispose) {
  9887. this.onDispose();
  9888. }
  9889. };
  9890. return Material;
  9891. })();
  9892. BABYLON.Material = Material;
  9893. })(BABYLON || (BABYLON = {}));
  9894. var __extends = this.__extends || function (d, b) {
  9895. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9896. function __() { this.constructor = d; }
  9897. __.prototype = b.prototype;
  9898. d.prototype = new __();
  9899. };
  9900. var BABYLON;
  9901. (function (BABYLON) {
  9902. var maxSimultaneousLights = 4;
  9903. var FresnelParameters = (function () {
  9904. function FresnelParameters() {
  9905. this.isEnabled = true;
  9906. this.leftColor = BABYLON.Color3.White();
  9907. this.rightColor = BABYLON.Color3.Black();
  9908. this.bias = 0;
  9909. this.power = 1;
  9910. }
  9911. return FresnelParameters;
  9912. })();
  9913. BABYLON.FresnelParameters = FresnelParameters;
  9914. var StandardMaterial = (function (_super) {
  9915. __extends(StandardMaterial, _super);
  9916. function StandardMaterial(name, scene) {
  9917. var _this = this;
  9918. _super.call(this, name, scene);
  9919. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9920. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  9921. this.specularColor = new BABYLON.Color3(1, 1, 1);
  9922. this.specularPower = 64;
  9923. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  9924. this.useAlphaFromDiffuseTexture = false;
  9925. this._cachedDefines = null;
  9926. this._renderTargets = new BABYLON.SmartArray(16);
  9927. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  9928. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  9929. this._scaledDiffuse = new BABYLON.Color3();
  9930. this._scaledSpecular = new BABYLON.Color3();
  9931. this.getRenderTargetTextures = function () {
  9932. _this._renderTargets.reset();
  9933. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  9934. _this._renderTargets.push(_this.reflectionTexture);
  9935. }
  9936. return _this._renderTargets;
  9937. };
  9938. }
  9939. StandardMaterial.prototype.needAlphaBlending = function () {
  9940. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  9941. };
  9942. StandardMaterial.prototype.needAlphaTesting = function () {
  9943. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  9944. };
  9945. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  9946. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  9947. };
  9948. StandardMaterial.prototype.getAlphaTestTexture = function () {
  9949. return this.diffuseTexture;
  9950. };
  9951. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  9952. if (this.checkReadyOnlyOnce) {
  9953. if (this._wasPreviouslyReady) {
  9954. return true;
  9955. }
  9956. }
  9957. var scene = this.getScene();
  9958. if (!this.checkReadyOnEveryCall) {
  9959. if (this._renderId === scene.getRenderId()) {
  9960. return true;
  9961. }
  9962. }
  9963. var engine = scene.getEngine();
  9964. var defines = [];
  9965. var fallbacks = new BABYLON.EffectFallbacks();
  9966. if (scene.texturesEnabled) {
  9967. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  9968. if (!this.diffuseTexture.isReady()) {
  9969. return false;
  9970. } else {
  9971. defines.push("#define DIFFUSE");
  9972. }
  9973. }
  9974. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  9975. if (!this.ambientTexture.isReady()) {
  9976. return false;
  9977. } else {
  9978. defines.push("#define AMBIENT");
  9979. }
  9980. }
  9981. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  9982. if (!this.opacityTexture.isReady()) {
  9983. return false;
  9984. } else {
  9985. defines.push("#define OPACITY");
  9986. if (this.opacityTexture.getAlphaFromRGB) {
  9987. defines.push("#define OPACITYRGB");
  9988. }
  9989. }
  9990. }
  9991. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  9992. if (!this.reflectionTexture.isReady()) {
  9993. return false;
  9994. } else {
  9995. defines.push("#define REFLECTION");
  9996. fallbacks.addFallback(0, "REFLECTION");
  9997. }
  9998. }
  9999. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10000. if (!this.emissiveTexture.isReady()) {
  10001. return false;
  10002. } else {
  10003. defines.push("#define EMISSIVE");
  10004. }
  10005. }
  10006. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10007. if (!this.specularTexture.isReady()) {
  10008. return false;
  10009. } else {
  10010. defines.push("#define SPECULAR");
  10011. fallbacks.addFallback(0, "SPECULAR");
  10012. }
  10013. }
  10014. }
  10015. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10016. if (!this.bumpTexture.isReady()) {
  10017. return false;
  10018. } else {
  10019. defines.push("#define BUMP");
  10020. fallbacks.addFallback(0, "BUMP");
  10021. }
  10022. }
  10023. if (scene.clipPlane) {
  10024. defines.push("#define CLIPPLANE");
  10025. }
  10026. if (engine.getAlphaTesting()) {
  10027. defines.push("#define ALPHATEST");
  10028. }
  10029. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10030. defines.push("#define ALPHAFROMDIFFUSE");
  10031. }
  10032. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10033. defines.push("#define FOG");
  10034. fallbacks.addFallback(1, "FOG");
  10035. }
  10036. var shadowsActivated = false;
  10037. var lightIndex = 0;
  10038. if (scene.lightsEnabled) {
  10039. for (var index = 0; index < scene.lights.length; index++) {
  10040. var light = scene.lights[index];
  10041. if (!light.isEnabled()) {
  10042. continue;
  10043. }
  10044. if (light._excludedMeshesIds.length > 0) {
  10045. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10046. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10047. if (excludedMesh) {
  10048. light.excludedMeshes.push(excludedMesh);
  10049. }
  10050. }
  10051. light._excludedMeshesIds = [];
  10052. }
  10053. if (light._includedOnlyMeshesIds.length > 0) {
  10054. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10055. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10056. if (includedOnlyMesh) {
  10057. light.includedOnlyMeshes.push(includedOnlyMesh);
  10058. }
  10059. }
  10060. light._includedOnlyMeshesIds = [];
  10061. }
  10062. if (!light.canAffectMesh(mesh)) {
  10063. continue;
  10064. }
  10065. defines.push("#define LIGHT" + lightIndex);
  10066. if (lightIndex > 0) {
  10067. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10068. }
  10069. var type;
  10070. if (light instanceof BABYLON.SpotLight) {
  10071. type = "#define SPOTLIGHT" + lightIndex;
  10072. } else if (light instanceof BABYLON.HemisphericLight) {
  10073. type = "#define HEMILIGHT" + lightIndex;
  10074. } else {
  10075. type = "#define POINTDIRLIGHT" + lightIndex;
  10076. }
  10077. defines.push(type);
  10078. if (lightIndex > 0) {
  10079. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10080. }
  10081. var shadowGenerator = light.getShadowGenerator();
  10082. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10083. defines.push("#define SHADOW" + lightIndex);
  10084. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10085. if (!shadowsActivated) {
  10086. defines.push("#define SHADOWS");
  10087. shadowsActivated = true;
  10088. }
  10089. if (shadowGenerator.useVarianceShadowMap) {
  10090. defines.push("#define SHADOWVSM" + lightIndex);
  10091. if (lightIndex > 0) {
  10092. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10093. }
  10094. }
  10095. if (shadowGenerator.usePoissonSampling) {
  10096. defines.push("#define SHADOWPCF" + lightIndex);
  10097. if (lightIndex > 0) {
  10098. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10099. }
  10100. }
  10101. }
  10102. lightIndex++;
  10103. if (lightIndex == maxSimultaneousLights)
  10104. break;
  10105. }
  10106. }
  10107. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10108. var fresnelRank = 1;
  10109. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10110. defines.push("#define DIFFUSEFRESNEL");
  10111. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10112. fresnelRank++;
  10113. }
  10114. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10115. defines.push("#define OPACITYFRESNEL");
  10116. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10117. fresnelRank++;
  10118. }
  10119. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10120. defines.push("#define REFLECTIONFRESNEL");
  10121. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10122. fresnelRank++;
  10123. }
  10124. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10125. defines.push("#define EMISSIVEFRESNEL");
  10126. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10127. fresnelRank++;
  10128. }
  10129. defines.push("#define FRESNEL");
  10130. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10131. }
  10132. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10133. if (mesh) {
  10134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10135. attribs.push(BABYLON.VertexBuffer.UVKind);
  10136. defines.push("#define UV1");
  10137. }
  10138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10139. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10140. defines.push("#define UV2");
  10141. }
  10142. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10143. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10144. defines.push("#define VERTEXCOLOR");
  10145. }
  10146. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10149. defines.push("#define BONES");
  10150. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10151. defines.push("#define BONES4");
  10152. fallbacks.addFallback(0, "BONES4");
  10153. }
  10154. if (useInstances) {
  10155. defines.push("#define INSTANCES");
  10156. attribs.push("world0");
  10157. attribs.push("world1");
  10158. attribs.push("world2");
  10159. attribs.push("world3");
  10160. }
  10161. }
  10162. var join = defines.join("\n");
  10163. if (this._cachedDefines != join) {
  10164. this._cachedDefines = join;
  10165. var shaderName = "default";
  10166. if (!scene.getEngine().getCaps().standardDerivatives) {
  10167. shaderName = "legacydefault";
  10168. }
  10169. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10170. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10171. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10172. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10173. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10174. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10175. "vFogInfos", "vFogColor",
  10176. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10177. "mBones",
  10178. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10179. "darkness0", "darkness1", "darkness2", "darkness3",
  10180. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10181. ], [
  10182. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10183. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10184. ], join, fallbacks, this.onCompiled, this.onError);
  10185. }
  10186. if (!this._effect.isReady()) {
  10187. return false;
  10188. }
  10189. this._renderId = scene.getRenderId();
  10190. this._wasPreviouslyReady = true;
  10191. return true;
  10192. };
  10193. StandardMaterial.prototype.unbind = function () {
  10194. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10195. this._effect.setTexture("reflection2DSampler", null);
  10196. }
  10197. };
  10198. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10199. this._effect.setMatrix("world", world);
  10200. };
  10201. StandardMaterial.prototype.bind = function (world, mesh) {
  10202. var scene = this.getScene();
  10203. this.bindOnlyWorldMatrix(world);
  10204. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10205. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10206. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10207. }
  10208. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10209. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10210. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10211. }
  10212. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10213. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10214. }
  10215. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10216. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10217. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10218. }
  10219. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10220. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10221. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10222. }
  10223. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10224. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10225. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10226. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10227. }
  10228. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10229. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10230. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10231. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10232. }
  10233. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10234. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10235. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10236. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10237. }
  10238. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10239. if (this.reflectionTexture.isCube) {
  10240. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10241. } else {
  10242. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10243. }
  10244. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10245. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10246. }
  10247. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10248. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10249. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10250. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10251. }
  10252. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10253. this._effect.setTexture("specularSampler", this.specularTexture);
  10254. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10255. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10256. }
  10257. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10258. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10259. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10260. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10261. }
  10262. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10263. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10264. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10265. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10266. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10267. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10268. if (scene.lightsEnabled) {
  10269. var lightIndex = 0;
  10270. for (var index = 0; index < scene.lights.length; index++) {
  10271. var light = scene.lights[index];
  10272. if (!light.isEnabled()) {
  10273. continue;
  10274. }
  10275. if (!light.canAffectMesh(mesh)) {
  10276. continue;
  10277. }
  10278. if (light instanceof BABYLON.PointLight) {
  10279. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10280. } else if (light instanceof BABYLON.DirectionalLight) {
  10281. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10282. } else if (light instanceof BABYLON.SpotLight) {
  10283. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10284. } else if (light instanceof BABYLON.HemisphericLight) {
  10285. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10286. }
  10287. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10288. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10289. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10290. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10291. var shadowGenerator = light.getShadowGenerator();
  10292. if (mesh.receiveShadows && shadowGenerator) {
  10293. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10294. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10295. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10296. }
  10297. lightIndex++;
  10298. if (lightIndex == maxSimultaneousLights)
  10299. break;
  10300. }
  10301. }
  10302. if (scene.clipPlane) {
  10303. var clipPlane = scene.clipPlane;
  10304. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10305. }
  10306. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10307. this._effect.setMatrix("view", scene.getViewMatrix());
  10308. }
  10309. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10310. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10311. this._effect.setColor3("vFogColor", scene.fogColor);
  10312. }
  10313. };
  10314. StandardMaterial.prototype.getAnimatables = function () {
  10315. var results = [];
  10316. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10317. results.push(this.diffuseTexture);
  10318. }
  10319. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10320. results.push(this.ambientTexture);
  10321. }
  10322. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10323. results.push(this.opacityTexture);
  10324. }
  10325. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10326. results.push(this.reflectionTexture);
  10327. }
  10328. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10329. results.push(this.emissiveTexture);
  10330. }
  10331. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10332. results.push(this.specularTexture);
  10333. }
  10334. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10335. results.push(this.bumpTexture);
  10336. }
  10337. return results;
  10338. };
  10339. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10340. if (this.diffuseTexture) {
  10341. this.diffuseTexture.dispose();
  10342. }
  10343. if (this.ambientTexture) {
  10344. this.ambientTexture.dispose();
  10345. }
  10346. if (this.opacityTexture) {
  10347. this.opacityTexture.dispose();
  10348. }
  10349. if (this.reflectionTexture) {
  10350. this.reflectionTexture.dispose();
  10351. }
  10352. if (this.emissiveTexture) {
  10353. this.emissiveTexture.dispose();
  10354. }
  10355. if (this.specularTexture) {
  10356. this.specularTexture.dispose();
  10357. }
  10358. if (this.bumpTexture) {
  10359. this.bumpTexture.dispose();
  10360. }
  10361. _super.prototype.dispose.call(this, forceDisposeEffect);
  10362. };
  10363. StandardMaterial.prototype.clone = function (name) {
  10364. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10365. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10366. newStandardMaterial.alpha = this.alpha;
  10367. newStandardMaterial.wireframe = this.wireframe;
  10368. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10369. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10370. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10371. }
  10372. if (this.ambientTexture && this.ambientTexture.clone) {
  10373. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10374. }
  10375. if (this.opacityTexture && this.opacityTexture.clone) {
  10376. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10377. }
  10378. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10379. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10380. }
  10381. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10382. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10383. }
  10384. if (this.specularTexture && this.specularTexture.clone) {
  10385. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10386. }
  10387. if (this.bumpTexture && this.bumpTexture.clone) {
  10388. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10389. }
  10390. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10391. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10392. newStandardMaterial.specularColor = this.specularColor.clone();
  10393. newStandardMaterial.specularPower = this.specularPower;
  10394. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10395. return newStandardMaterial;
  10396. };
  10397. StandardMaterial.DiffuseTextureEnabled = true;
  10398. StandardMaterial.AmbientTextureEnabled = true;
  10399. StandardMaterial.OpacityTextureEnabled = true;
  10400. StandardMaterial.ReflectionTextureEnabled = true;
  10401. StandardMaterial.EmissiveTextureEnabled = true;
  10402. StandardMaterial.SpecularTextureEnabled = true;
  10403. StandardMaterial.BumpTextureEnabled = true;
  10404. return StandardMaterial;
  10405. })(BABYLON.Material);
  10406. BABYLON.StandardMaterial = StandardMaterial;
  10407. })(BABYLON || (BABYLON = {}));
  10408. var __extends = this.__extends || function (d, b) {
  10409. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10410. function __() { this.constructor = d; }
  10411. __.prototype = b.prototype;
  10412. d.prototype = new __();
  10413. };
  10414. var BABYLON;
  10415. (function (BABYLON) {
  10416. var MultiMaterial = (function (_super) {
  10417. __extends(MultiMaterial, _super);
  10418. function MultiMaterial(name, scene) {
  10419. _super.call(this, name, scene, true);
  10420. this.subMaterials = new Array();
  10421. scene.multiMaterials.push(this);
  10422. }
  10423. MultiMaterial.prototype.getSubMaterial = function (index) {
  10424. if (index < 0 || index >= this.subMaterials.length) {
  10425. return this.getScene().defaultMaterial;
  10426. }
  10427. return this.subMaterials[index];
  10428. };
  10429. MultiMaterial.prototype.isReady = function (mesh) {
  10430. for (var index = 0; index < this.subMaterials.length; index++) {
  10431. var subMaterial = this.subMaterials[index];
  10432. if (subMaterial) {
  10433. if (!this.subMaterials[index].isReady(mesh)) {
  10434. return false;
  10435. }
  10436. }
  10437. }
  10438. return true;
  10439. };
  10440. return MultiMaterial;
  10441. })(BABYLON.Material);
  10442. BABYLON.MultiMaterial = MultiMaterial;
  10443. })(BABYLON || (BABYLON = {}));
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. var Database = (function () {
  10447. function Database(urlToScene, callbackManifestChecked) {
  10448. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10449. this.callbackManifestChecked = callbackManifestChecked;
  10450. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10451. this.db = null;
  10452. this.enableSceneOffline = false;
  10453. this.enableTexturesOffline = false;
  10454. this.manifestVersionFound = 0;
  10455. this.mustUpdateRessources = false;
  10456. this.hasReachedQuota = false;
  10457. this.checkManifestFile();
  10458. }
  10459. Database.prototype.checkManifestFile = function () {
  10460. var _this = this;
  10461. function noManifestFile() {
  10462. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10463. that.enableSceneOffline = false;
  10464. that.enableTexturesOffline = false;
  10465. that.callbackManifestChecked(false);
  10466. }
  10467. var that = this;
  10468. var manifestURL = this.currentSceneUrl + ".manifest";
  10469. var xhr = new XMLHttpRequest();
  10470. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10471. xhr.open("GET", manifestURLTimeStamped, true);
  10472. xhr.addEventListener("load", function () {
  10473. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10474. try {
  10475. var manifestFile = JSON.parse(xhr.response);
  10476. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10477. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10478. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10479. _this.manifestVersionFound = manifestFile.version;
  10480. }
  10481. if (_this.callbackManifestChecked) {
  10482. _this.callbackManifestChecked(true);
  10483. }
  10484. } catch (ex) {
  10485. noManifestFile();
  10486. }
  10487. } else {
  10488. noManifestFile();
  10489. }
  10490. }, false);
  10491. xhr.addEventListener("error", function (event) {
  10492. noManifestFile();
  10493. }, false);
  10494. try {
  10495. xhr.send();
  10496. } catch (ex) {
  10497. BABYLON.Tools.Error("Error on XHR send request.");
  10498. that.callbackManifestChecked(false);
  10499. }
  10500. };
  10501. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10502. var _this = this;
  10503. function handleError() {
  10504. that.isSupported = false;
  10505. if (errorCallback)
  10506. errorCallback();
  10507. }
  10508. var that = this;
  10509. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10510. this.isSupported = false;
  10511. if (errorCallback)
  10512. errorCallback();
  10513. } else {
  10514. if (!this.db) {
  10515. this.hasReachedQuota = false;
  10516. this.isSupported = true;
  10517. var request = this.idbFactory.open("babylonjs", 1);
  10518. request.onerror = function (event) {
  10519. handleError();
  10520. };
  10521. request.onblocked = function (event) {
  10522. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10523. handleError();
  10524. };
  10525. request.onsuccess = function (event) {
  10526. _this.db = request.result;
  10527. successCallback();
  10528. };
  10529. request.onupgradeneeded = function (event) {
  10530. _this.db = (event.target).result;
  10531. try {
  10532. if (event.oldVersion > 0) {
  10533. _this.db.deleteObjectStore("scenes");
  10534. _this.db.deleteObjectStore("versions");
  10535. _this.db.deleteObjectStore("textures");
  10536. }
  10537. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10538. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10539. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10540. } catch (ex) {
  10541. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10542. handleError();
  10543. }
  10544. };
  10545. } else {
  10546. if (successCallback)
  10547. successCallback();
  10548. }
  10549. }
  10550. };
  10551. Database.prototype.loadImageFromDB = function (url, image) {
  10552. var _this = this;
  10553. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10554. var saveAndLoadImage = function () {
  10555. if (!_this.hasReachedQuota && _this.db !== null) {
  10556. _this._saveImageIntoDBAsync(completeURL, image);
  10557. } else {
  10558. image.src = url;
  10559. }
  10560. };
  10561. if (!this.mustUpdateRessources) {
  10562. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10563. } else {
  10564. saveAndLoadImage();
  10565. }
  10566. };
  10567. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10568. if (this.isSupported && this.db !== null) {
  10569. var texture;
  10570. var transaction = this.db.transaction(["textures"]);
  10571. transaction.onabort = function (event) {
  10572. image.src = url;
  10573. };
  10574. transaction.oncomplete = function (event) {
  10575. var blobTextureURL;
  10576. if (texture) {
  10577. var URL = window.URL || window.webkitURL;
  10578. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10579. image.onerror = function () {
  10580. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10581. image.src = url;
  10582. };
  10583. image.src = blobTextureURL;
  10584. } else {
  10585. notInDBCallback();
  10586. }
  10587. };
  10588. var getRequest = transaction.objectStore("textures").get(url);
  10589. getRequest.onsuccess = function (event) {
  10590. texture = (event.target).result;
  10591. };
  10592. getRequest.onerror = function (event) {
  10593. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10594. image.src = url;
  10595. };
  10596. } else {
  10597. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10598. image.src = url;
  10599. }
  10600. };
  10601. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10602. var _this = this;
  10603. if (this.isSupported) {
  10604. var generateBlobUrl = function () {
  10605. var blobTextureURL;
  10606. if (blob) {
  10607. var URL = window.URL || window.webkitURL;
  10608. try {
  10609. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10610. } catch (ex) {
  10611. blobTextureURL = URL.createObjectURL(blob);
  10612. }
  10613. }
  10614. image.src = blobTextureURL;
  10615. };
  10616. if (BABYLON.Database.isUASupportingBlobStorage) {
  10617. var xhr = new XMLHttpRequest(), blob;
  10618. xhr.open("GET", url, true);
  10619. xhr.responseType = "blob";
  10620. xhr.addEventListener("load", function () {
  10621. if (xhr.status === 200) {
  10622. blob = xhr.response;
  10623. var transaction = _this.db.transaction(["textures"], "readwrite");
  10624. transaction.onabort = function (event) {
  10625. try {
  10626. if (event.srcElement.error.name === "QuotaExceededError") {
  10627. this.hasReachedQuota = true;
  10628. }
  10629. } catch (ex) {
  10630. }
  10631. generateBlobUrl();
  10632. };
  10633. transaction.oncomplete = function (event) {
  10634. generateBlobUrl();
  10635. };
  10636. var newTexture = { textureUrl: url, data: blob };
  10637. try {
  10638. var addRequest = transaction.objectStore("textures").put(newTexture);
  10639. addRequest.onsuccess = function (event) {
  10640. };
  10641. addRequest.onerror = function (event) {
  10642. generateBlobUrl();
  10643. };
  10644. } catch (ex) {
  10645. if (ex.code === 25) {
  10646. BABYLON.Database.isUASupportingBlobStorage = false;
  10647. }
  10648. image.src = url;
  10649. }
  10650. } else {
  10651. image.src = url;
  10652. }
  10653. }, false);
  10654. xhr.addEventListener("error", function (event) {
  10655. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10656. image.src = url;
  10657. }, false);
  10658. xhr.send();
  10659. } else {
  10660. image.src = url;
  10661. }
  10662. } else {
  10663. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10664. image.src = url;
  10665. }
  10666. };
  10667. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10668. var _this = this;
  10669. var updateVersion = function (event) {
  10670. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10671. };
  10672. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10673. };
  10674. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10675. var _this = this;
  10676. if (this.isSupported) {
  10677. var version;
  10678. try {
  10679. var transaction = this.db.transaction(["versions"]);
  10680. transaction.oncomplete = function (event) {
  10681. if (version) {
  10682. if (_this.manifestVersionFound > version.data) {
  10683. _this.mustUpdateRessources = true;
  10684. updateInDBCallback();
  10685. } else {
  10686. callback(version.data);
  10687. }
  10688. } else {
  10689. _this.mustUpdateRessources = true;
  10690. updateInDBCallback();
  10691. }
  10692. };
  10693. transaction.onabort = function (event) {
  10694. callback(-1);
  10695. };
  10696. var getRequest = transaction.objectStore("versions").get(url);
  10697. getRequest.onsuccess = function (event) {
  10698. version = (event.target).result;
  10699. };
  10700. getRequest.onerror = function (event) {
  10701. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10702. callback(-1);
  10703. };
  10704. } catch (ex) {
  10705. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10706. callback(-1);
  10707. }
  10708. } else {
  10709. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10710. callback(-1);
  10711. }
  10712. };
  10713. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10714. var _this = this;
  10715. if (this.isSupported && !this.hasReachedQuota) {
  10716. try {
  10717. var transaction = this.db.transaction(["versions"], "readwrite");
  10718. transaction.onabort = function (event) {
  10719. try {
  10720. if (event.srcElement.error.name === "QuotaExceededError") {
  10721. _this.hasReachedQuota = true;
  10722. }
  10723. } catch (ex) {
  10724. }
  10725. callback(-1);
  10726. };
  10727. transaction.oncomplete = function (event) {
  10728. callback(_this.manifestVersionFound);
  10729. };
  10730. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10731. var addRequest = transaction.objectStore("versions").put(newVersion);
  10732. addRequest.onsuccess = function (event) {
  10733. };
  10734. addRequest.onerror = function (event) {
  10735. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10736. };
  10737. } catch (ex) {
  10738. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10739. callback(-1);
  10740. }
  10741. } else {
  10742. callback(-1);
  10743. }
  10744. };
  10745. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10746. var _this = this;
  10747. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10748. var saveAndLoadFile = function (event) {
  10749. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10750. };
  10751. this._checkVersionFromDB(completeUrl, function (version) {
  10752. if (version !== -1) {
  10753. if (!_this.mustUpdateRessources) {
  10754. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10755. } else {
  10756. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10757. }
  10758. } else {
  10759. errorCallback();
  10760. }
  10761. });
  10762. };
  10763. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10764. if (this.isSupported) {
  10765. var targetStore;
  10766. if (url.indexOf(".babylon") !== -1) {
  10767. targetStore = "scenes";
  10768. } else {
  10769. targetStore = "textures";
  10770. }
  10771. var file;
  10772. var transaction = this.db.transaction([targetStore]);
  10773. transaction.oncomplete = function (event) {
  10774. if (file) {
  10775. callback(file.data);
  10776. } else {
  10777. notInDBCallback();
  10778. }
  10779. };
  10780. transaction.onabort = function (event) {
  10781. notInDBCallback();
  10782. };
  10783. var getRequest = transaction.objectStore(targetStore).get(url);
  10784. getRequest.onsuccess = function (event) {
  10785. file = (event.target).result;
  10786. };
  10787. getRequest.onerror = function (event) {
  10788. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10789. notInDBCallback();
  10790. };
  10791. } else {
  10792. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10793. callback();
  10794. }
  10795. };
  10796. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10797. var _this = this;
  10798. if (this.isSupported) {
  10799. var targetStore;
  10800. if (url.indexOf(".babylon") !== -1) {
  10801. targetStore = "scenes";
  10802. } else {
  10803. targetStore = "textures";
  10804. }
  10805. var xhr = new XMLHttpRequest(), fileData;
  10806. xhr.open("GET", url, true);
  10807. if (useArrayBuffer) {
  10808. xhr.responseType = "arraybuffer";
  10809. }
  10810. xhr.onprogress = progressCallback;
  10811. xhr.addEventListener("load", function () {
  10812. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10813. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10814. if (!_this.hasReachedQuota) {
  10815. var transaction = _this.db.transaction([targetStore], "readwrite");
  10816. transaction.onabort = function (event) {
  10817. try {
  10818. if (event.srcElement.error.name === "QuotaExceededError") {
  10819. this.hasReachedQuota = true;
  10820. }
  10821. } catch (ex) {
  10822. }
  10823. callback(fileData);
  10824. };
  10825. transaction.oncomplete = function (event) {
  10826. callback(fileData);
  10827. };
  10828. var newFile;
  10829. if (targetStore === "scenes") {
  10830. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10831. } else {
  10832. newFile = { textureUrl: url, data: fileData };
  10833. }
  10834. try {
  10835. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10836. addRequest.onsuccess = function (event) {
  10837. };
  10838. addRequest.onerror = function (event) {
  10839. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10840. };
  10841. } catch (ex) {
  10842. callback(fileData);
  10843. }
  10844. } else {
  10845. callback(fileData);
  10846. }
  10847. } else {
  10848. callback();
  10849. }
  10850. }, false);
  10851. xhr.addEventListener("error", function (event) {
  10852. BABYLON.Tools.Error("error on XHR request.");
  10853. callback();
  10854. }, false);
  10855. xhr.send();
  10856. } else {
  10857. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10858. callback();
  10859. }
  10860. };
  10861. Database.isUASupportingBlobStorage = true;
  10862. Database.parseURL = function (url) {
  10863. var a = document.createElement('a');
  10864. a.href = url;
  10865. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10866. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10867. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10868. return absLocation;
  10869. };
  10870. Database.ReturnFullUrlLocation = function (url) {
  10871. if (url.indexOf("http:/") === -1) {
  10872. return (BABYLON.Database.parseURL(window.location.href) + url);
  10873. } else {
  10874. return url;
  10875. }
  10876. };
  10877. return Database;
  10878. })();
  10879. BABYLON.Database = Database;
  10880. })(BABYLON || (BABYLON = {}));
  10881. var BABYLON;
  10882. (function (BABYLON) {
  10883. var SpriteManager = (function () {
  10884. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10885. this.name = name;
  10886. this.cellSize = cellSize;
  10887. this.sprites = new Array();
  10888. this.renderingGroupId = 0;
  10889. this._vertexDeclaration = [3, 4, 4, 4];
  10890. this._vertexStrideSize = 15 * 4;
  10891. this._capacity = capacity;
  10892. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10893. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10894. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10895. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10896. this._scene = scene;
  10897. this._scene.spriteManagers.push(this);
  10898. this._vertexDeclaration = [3, 4, 4, 4];
  10899. this._vertexStrideSize = 15 * 4;
  10900. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10901. var indices = [];
  10902. var index = 0;
  10903. for (var count = 0; count < capacity; count++) {
  10904. indices.push(index);
  10905. indices.push(index + 1);
  10906. indices.push(index + 2);
  10907. indices.push(index);
  10908. indices.push(index + 2);
  10909. indices.push(index + 3);
  10910. index += 4;
  10911. }
  10912. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10913. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  10914. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  10915. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  10916. }
  10917. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  10918. var arrayOffset = index * 15;
  10919. if (offsetX == 0)
  10920. offsetX = this._epsilon;
  10921. else if (offsetX == 1)
  10922. offsetX = 1 - this._epsilon;
  10923. if (offsetY == 0)
  10924. offsetY = this._epsilon;
  10925. else if (offsetY == 1)
  10926. offsetY = 1 - this._epsilon;
  10927. this._vertices[arrayOffset] = sprite.position.x;
  10928. this._vertices[arrayOffset + 1] = sprite.position.y;
  10929. this._vertices[arrayOffset + 2] = sprite.position.z;
  10930. this._vertices[arrayOffset + 3] = sprite.angle;
  10931. this._vertices[arrayOffset + 4] = sprite.size;
  10932. this._vertices[arrayOffset + 5] = offsetX;
  10933. this._vertices[arrayOffset + 6] = offsetY;
  10934. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  10935. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  10936. var offset = (sprite.cellIndex / rowSize) >> 0;
  10937. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  10938. this._vertices[arrayOffset + 10] = offset;
  10939. this._vertices[arrayOffset + 11] = sprite.color.r;
  10940. this._vertices[arrayOffset + 12] = sprite.color.g;
  10941. this._vertices[arrayOffset + 13] = sprite.color.b;
  10942. this._vertices[arrayOffset + 14] = sprite.color.a;
  10943. };
  10944. SpriteManager.prototype.render = function () {
  10945. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  10946. return;
  10947. var engine = this._scene.getEngine();
  10948. var baseSize = this._spriteTexture.getBaseSize();
  10949. var deltaTime = BABYLON.Tools.GetDeltaTime();
  10950. var max = Math.min(this._capacity, this.sprites.length);
  10951. var rowSize = baseSize.width / this.cellSize;
  10952. var offset = 0;
  10953. for (var index = 0; index < max; index++) {
  10954. var sprite = this.sprites[index];
  10955. if (!sprite) {
  10956. continue;
  10957. }
  10958. sprite._animate(deltaTime);
  10959. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  10960. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  10961. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  10962. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  10963. }
  10964. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  10965. var effect = this._effectBase;
  10966. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10967. effect = this._effectFog;
  10968. }
  10969. engine.enableEffect(effect);
  10970. var viewMatrix = this._scene.getViewMatrix();
  10971. effect.setTexture("diffuseSampler", this._spriteTexture);
  10972. effect.setMatrix("view", viewMatrix);
  10973. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  10974. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  10975. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10976. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  10977. effect.setColor3("vFogColor", this._scene.fogColor);
  10978. }
  10979. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  10980. effect.setBool("alphaTest", true);
  10981. engine.setColorWrite(false);
  10982. engine.draw(true, 0, max * 6);
  10983. engine.setColorWrite(true);
  10984. effect.setBool("alphaTest", false);
  10985. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10986. engine.draw(true, 0, max * 6);
  10987. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10988. };
  10989. SpriteManager.prototype.dispose = function () {
  10990. if (this._vertexBuffer) {
  10991. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  10992. this._vertexBuffer = null;
  10993. }
  10994. if (this._indexBuffer) {
  10995. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  10996. this._indexBuffer = null;
  10997. }
  10998. if (this._spriteTexture) {
  10999. this._spriteTexture.dispose();
  11000. this._spriteTexture = null;
  11001. }
  11002. var index = this._scene.spriteManagers.indexOf(this);
  11003. this._scene.spriteManagers.splice(index, 1);
  11004. if (this.onDispose) {
  11005. this.onDispose();
  11006. }
  11007. };
  11008. return SpriteManager;
  11009. })();
  11010. BABYLON.SpriteManager = SpriteManager;
  11011. })(BABYLON || (BABYLON = {}));
  11012. var BABYLON;
  11013. (function (BABYLON) {
  11014. var Sprite = (function () {
  11015. function Sprite(name, manager) {
  11016. this.name = name;
  11017. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11018. this.size = 1.0;
  11019. this.angle = 0;
  11020. this.cellIndex = 0;
  11021. this.invertU = 0;
  11022. this.invertV = 0;
  11023. this.animations = new Array();
  11024. this._animationStarted = false;
  11025. this._loopAnimation = false;
  11026. this._fromIndex = 0;
  11027. this._toIndex = 0;
  11028. this._delay = 0;
  11029. this._direction = 1;
  11030. this._frameCount = 0;
  11031. this._time = 0;
  11032. this._manager = manager;
  11033. this._manager.sprites.push(this);
  11034. this.position = BABYLON.Vector3.Zero();
  11035. }
  11036. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11037. this._fromIndex = from;
  11038. this._toIndex = to;
  11039. this._loopAnimation = loop;
  11040. this._delay = delay;
  11041. this._animationStarted = true;
  11042. this._direction = from < to ? 1 : -1;
  11043. this.cellIndex = from;
  11044. this._time = 0;
  11045. };
  11046. Sprite.prototype.stopAnimation = function () {
  11047. this._animationStarted = false;
  11048. };
  11049. Sprite.prototype._animate = function (deltaTime) {
  11050. if (!this._animationStarted)
  11051. return;
  11052. this._time += deltaTime;
  11053. if (this._time > this._delay) {
  11054. this._time = this._time % this._delay;
  11055. this.cellIndex += this._direction;
  11056. if (this.cellIndex == this._toIndex) {
  11057. if (this._loopAnimation) {
  11058. this.cellIndex = this._fromIndex;
  11059. } else {
  11060. this._animationStarted = false;
  11061. if (this.disposeWhenFinishedAnimating) {
  11062. this.dispose();
  11063. }
  11064. }
  11065. }
  11066. }
  11067. };
  11068. Sprite.prototype.dispose = function () {
  11069. for (var i = 0; i < this._manager.sprites.length; i++) {
  11070. if (this._manager.sprites[i] == this) {
  11071. this._manager.sprites.splice(i, 1);
  11072. }
  11073. }
  11074. };
  11075. return Sprite;
  11076. })();
  11077. BABYLON.Sprite = Sprite;
  11078. })(BABYLON || (BABYLON = {}));
  11079. var BABYLON;
  11080. (function (BABYLON) {
  11081. var Layer = (function () {
  11082. function Layer(name, imgUrl, scene, isBackground, color) {
  11083. this.name = name;
  11084. this._vertexDeclaration = [2];
  11085. this._vertexStrideSize = 2 * 4;
  11086. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11087. this.isBackground = isBackground === undefined ? true : isBackground;
  11088. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11089. this._scene = scene;
  11090. this._scene.layers.push(this);
  11091. var vertices = [];
  11092. vertices.push(1, 1);
  11093. vertices.push(-1, 1);
  11094. vertices.push(-1, -1);
  11095. vertices.push(1, -1);
  11096. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11097. var indices = [];
  11098. indices.push(0);
  11099. indices.push(1);
  11100. indices.push(2);
  11101. indices.push(0);
  11102. indices.push(2);
  11103. indices.push(3);
  11104. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11105. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11106. }
  11107. Layer.prototype.render = function () {
  11108. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11109. return;
  11110. var engine = this._scene.getEngine();
  11111. engine.enableEffect(this._effect);
  11112. engine.setState(false);
  11113. this._effect.setTexture("textureSampler", this.texture);
  11114. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11115. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11116. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11117. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11118. engine.draw(true, 0, 6);
  11119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11120. };
  11121. Layer.prototype.dispose = function () {
  11122. if (this._vertexBuffer) {
  11123. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11124. this._vertexBuffer = null;
  11125. }
  11126. if (this._indexBuffer) {
  11127. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11128. this._indexBuffer = null;
  11129. }
  11130. if (this.texture) {
  11131. this.texture.dispose();
  11132. this.texture = null;
  11133. }
  11134. var index = this._scene.layers.indexOf(this);
  11135. this._scene.layers.splice(index, 1);
  11136. if (this.onDispose) {
  11137. this.onDispose();
  11138. }
  11139. };
  11140. return Layer;
  11141. })();
  11142. BABYLON.Layer = Layer;
  11143. })(BABYLON || (BABYLON = {}));
  11144. var BABYLON;
  11145. (function (BABYLON) {
  11146. var Particle = (function () {
  11147. function Particle() {
  11148. this.position = BABYLON.Vector3.Zero();
  11149. this.direction = BABYLON.Vector3.Zero();
  11150. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11151. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11152. this.lifeTime = 1.0;
  11153. this.age = 0;
  11154. this.size = 0;
  11155. this.angle = 0;
  11156. this.angularSpeed = 0;
  11157. }
  11158. return Particle;
  11159. })();
  11160. BABYLON.Particle = Particle;
  11161. })(BABYLON || (BABYLON = {}));
  11162. var BABYLON;
  11163. (function (BABYLON) {
  11164. var randomNumber = function (min, max) {
  11165. if (min == max) {
  11166. return (min);
  11167. }
  11168. var random = Math.random();
  11169. return ((random * (max - min)) + min);
  11170. };
  11171. var ParticleSystem = (function () {
  11172. function ParticleSystem(name, capacity, scene, fragmentElement) {
  11173. var _this = this;
  11174. this.name = name;
  11175. this.fragmentElement = fragmentElement;
  11176. this.renderingGroupId = 0;
  11177. this.emitter = null;
  11178. this.emitRate = 10;
  11179. this.manualEmitCount = -1;
  11180. this.updateSpeed = 0.01;
  11181. this.targetStopDuration = 0;
  11182. this.disposeOnStop = false;
  11183. this.minEmitPower = 1;
  11184. this.maxEmitPower = 1;
  11185. this.minLifeTime = 1;
  11186. this.maxLifeTime = 1;
  11187. this.minSize = 1;
  11188. this.maxSize = 1;
  11189. this.minAngularSpeed = 0;
  11190. this.maxAngularSpeed = 0;
  11191. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11192. this.forceDepthWrite = false;
  11193. this.gravity = BABYLON.Vector3.Zero();
  11194. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11195. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11196. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11197. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11198. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11199. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11200. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11201. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11202. this.particles = new Array();
  11203. this._vertexDeclaration = [3, 4, 4];
  11204. this._vertexStrideSize = 11 * 4;
  11205. this._stockParticles = new Array();
  11206. this._newPartsExcess = 0;
  11207. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11208. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11209. this._scaledDirection = BABYLON.Vector3.Zero();
  11210. this._scaledGravity = BABYLON.Vector3.Zero();
  11211. this._currentRenderId = -1;
  11212. this._started = false;
  11213. this._stopped = false;
  11214. this._actualFrame = 0;
  11215. this.id = name;
  11216. this._capacity = capacity;
  11217. this._scene = scene;
  11218. scene.particleSystems.push(this);
  11219. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11220. var indices = [];
  11221. var index = 0;
  11222. for (var count = 0; count < capacity; count++) {
  11223. indices.push(index);
  11224. indices.push(index + 1);
  11225. indices.push(index + 2);
  11226. indices.push(index);
  11227. indices.push(index + 2);
  11228. indices.push(index + 3);
  11229. index += 4;
  11230. }
  11231. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11232. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11233. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11234. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11235. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11236. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11237. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11238. };
  11239. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11240. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11241. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11242. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11243. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11244. };
  11245. }
  11246. ParticleSystem.prototype.getCapacity = function () {
  11247. return this._capacity;
  11248. };
  11249. ParticleSystem.prototype.isAlive = function () {
  11250. return this._alive;
  11251. };
  11252. ParticleSystem.prototype.isStarted = function () {
  11253. return this._started;
  11254. };
  11255. ParticleSystem.prototype.start = function () {
  11256. this._started = true;
  11257. this._stopped = false;
  11258. this._actualFrame = 0;
  11259. };
  11260. ParticleSystem.prototype.stop = function () {
  11261. this._stopped = true;
  11262. };
  11263. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11264. var offset = index * 11;
  11265. this._vertices[offset] = particle.position.x;
  11266. this._vertices[offset + 1] = particle.position.y;
  11267. this._vertices[offset + 2] = particle.position.z;
  11268. this._vertices[offset + 3] = particle.color.r;
  11269. this._vertices[offset + 4] = particle.color.g;
  11270. this._vertices[offset + 5] = particle.color.b;
  11271. this._vertices[offset + 6] = particle.color.a;
  11272. this._vertices[offset + 7] = particle.angle;
  11273. this._vertices[offset + 8] = particle.size;
  11274. this._vertices[offset + 9] = offsetX;
  11275. this._vertices[offset + 10] = offsetY;
  11276. };
  11277. ParticleSystem.prototype._update = function (newParticles) {
  11278. this._alive = this.particles.length > 0;
  11279. for (var index = 0; index < this.particles.length; index++) {
  11280. var particle = this.particles[index];
  11281. particle.age += this._scaledUpdateSpeed;
  11282. if (particle.age >= particle.lifeTime) {
  11283. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11284. index--;
  11285. continue;
  11286. } else {
  11287. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11288. particle.color.addInPlace(this._scaledColorStep);
  11289. if (particle.color.a < 0)
  11290. particle.color.a = 0;
  11291. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11292. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11293. particle.position.addInPlace(this._scaledDirection);
  11294. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11295. particle.direction.addInPlace(this._scaledGravity);
  11296. }
  11297. }
  11298. var worldMatrix;
  11299. if (this.emitter.position) {
  11300. worldMatrix = this.emitter.getWorldMatrix();
  11301. } else {
  11302. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11303. }
  11304. for (index = 0; index < newParticles; index++) {
  11305. if (this.particles.length == this._capacity) {
  11306. break;
  11307. }
  11308. if (this._stockParticles.length !== 0) {
  11309. particle = this._stockParticles.pop();
  11310. particle.age = 0;
  11311. } else {
  11312. particle = new BABYLON.Particle();
  11313. }
  11314. this.particles.push(particle);
  11315. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11316. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11317. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11318. particle.size = randomNumber(this.minSize, this.maxSize);
  11319. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11320. this.startPositionFunction(worldMatrix, particle.position);
  11321. var step = randomNumber(0, 1.0);
  11322. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11323. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11324. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11325. }
  11326. };
  11327. ParticleSystem.prototype._getEffect = function () {
  11328. var defines = [];
  11329. if (this._scene.clipPlane) {
  11330. defines.push("#define CLIPPLANE");
  11331. }
  11332. var join = defines.join("\n");
  11333. if (this._cachedDefines != join) {
  11334. this._cachedDefines = join;
  11335. var baseName;
  11336. if (this.fragmentElement) {
  11337. baseName = {
  11338. vertex: "particles",
  11339. fragmentElement: this.fragmentElement
  11340. };
  11341. } else {
  11342. baseName = "particles";
  11343. }
  11344. this._effect = this._scene.getEngine().createEffect(baseName, ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11345. }
  11346. return this._effect;
  11347. };
  11348. ParticleSystem.prototype.animate = function () {
  11349. if (!this._started)
  11350. return;
  11351. var effect = this._getEffect();
  11352. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11353. return;
  11354. if (this._currentRenderId === this._scene.getRenderId()) {
  11355. return;
  11356. }
  11357. this._currentRenderId = this._scene.getRenderId();
  11358. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11359. var emitCout;
  11360. if (this.manualEmitCount > -1) {
  11361. emitCout = this.manualEmitCount;
  11362. this.manualEmitCount = 0;
  11363. } else {
  11364. emitCout = this.emitRate;
  11365. }
  11366. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11367. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11368. if (this._newPartsExcess > 1.0) {
  11369. newParticles += this._newPartsExcess >> 0;
  11370. this._newPartsExcess -= this._newPartsExcess >> 0;
  11371. }
  11372. this._alive = false;
  11373. if (!this._stopped) {
  11374. this._actualFrame += this._scaledUpdateSpeed;
  11375. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11376. this.stop();
  11377. } else {
  11378. newParticles = 0;
  11379. }
  11380. this._update(newParticles);
  11381. if (this._stopped) {
  11382. if (!this._alive) {
  11383. this._started = false;
  11384. if (this.disposeOnStop) {
  11385. this._scene._toBeDisposed.push(this);
  11386. }
  11387. }
  11388. }
  11389. var offset = 0;
  11390. for (var index = 0; index < this.particles.length; index++) {
  11391. var particle = this.particles[index];
  11392. this._appendParticleVertex(offset++, particle, 0, 0);
  11393. this._appendParticleVertex(offset++, particle, 1, 0);
  11394. this._appendParticleVertex(offset++, particle, 1, 1);
  11395. this._appendParticleVertex(offset++, particle, 0, 1);
  11396. }
  11397. var engine = this._scene.getEngine();
  11398. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11399. };
  11400. ParticleSystem.prototype.render = function () {
  11401. var effect = this._getEffect();
  11402. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11403. return 0;
  11404. var engine = this._scene.getEngine();
  11405. engine.enableEffect(effect);
  11406. var viewMatrix = this._scene.getViewMatrix();
  11407. effect.setTexture("diffuseSampler", this.particleTexture);
  11408. effect.setMatrix("view", viewMatrix);
  11409. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11410. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11411. if (this._scene.clipPlane) {
  11412. var clipPlane = this._scene.clipPlane;
  11413. var invView = viewMatrix.clone();
  11414. invView.invert();
  11415. effect.setMatrix("invView", invView);
  11416. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11417. }
  11418. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11419. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11420. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11421. } else {
  11422. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11423. }
  11424. if (this.forceDepthWrite) {
  11425. engine.setDepthWrite(true);
  11426. }
  11427. engine.draw(true, 0, this.particles.length * 6);
  11428. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11429. return this.particles.length;
  11430. };
  11431. ParticleSystem.prototype.dispose = function () {
  11432. if (this._vertexBuffer) {
  11433. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11434. this._vertexBuffer = null;
  11435. }
  11436. if (this._indexBuffer) {
  11437. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11438. this._indexBuffer = null;
  11439. }
  11440. if (this.particleTexture) {
  11441. this.particleTexture.dispose();
  11442. this.particleTexture = null;
  11443. }
  11444. var index = this._scene.particleSystems.indexOf(this);
  11445. this._scene.particleSystems.splice(index, 1);
  11446. if (this.onDispose) {
  11447. this.onDispose();
  11448. }
  11449. };
  11450. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11451. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11452. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11453. if (newEmitter === undefined) {
  11454. newEmitter = this.emitter;
  11455. }
  11456. result.emitter = newEmitter;
  11457. if (this.particleTexture) {
  11458. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11459. }
  11460. result.start();
  11461. return result;
  11462. };
  11463. ParticleSystem.BLENDMODE_ONEONE = 0;
  11464. ParticleSystem.BLENDMODE_STANDARD = 1;
  11465. return ParticleSystem;
  11466. })();
  11467. BABYLON.ParticleSystem = ParticleSystem;
  11468. })(BABYLON || (BABYLON = {}));
  11469. var BABYLON;
  11470. (function (BABYLON) {
  11471. var Animation = (function () {
  11472. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11473. this.name = name;
  11474. this.targetProperty = targetProperty;
  11475. this.framePerSecond = framePerSecond;
  11476. this.dataType = dataType;
  11477. this.loopMode = loopMode;
  11478. this._offsetsCache = {};
  11479. this._highLimitsCache = {};
  11480. this._stopped = false;
  11481. this.targetPropertyPath = targetProperty.split(".");
  11482. this.dataType = dataType;
  11483. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11484. }
  11485. Animation.prototype.isStopped = function () {
  11486. return this._stopped;
  11487. };
  11488. Animation.prototype.getKeys = function () {
  11489. return this._keys;
  11490. };
  11491. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11492. return startValue + (endValue - startValue) * gradient;
  11493. };
  11494. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11495. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11496. };
  11497. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11498. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11499. };
  11500. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11501. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11502. };
  11503. Animation.prototype.clone = function () {
  11504. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11505. clone.setKeys(this._keys);
  11506. return clone;
  11507. };
  11508. Animation.prototype.setKeys = function (values) {
  11509. this._keys = values.slice(0);
  11510. this._offsetsCache = {};
  11511. this._highLimitsCache = {};
  11512. };
  11513. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11514. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11515. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11516. }
  11517. this.currentFrame = currentFrame;
  11518. for (var key = 0; key < this._keys.length; key++) {
  11519. if (this._keys[key + 1].frame >= currentFrame) {
  11520. var startValue = this._keys[key].value;
  11521. var endValue = this._keys[key + 1].value;
  11522. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11523. switch (this.dataType) {
  11524. case Animation.ANIMATIONTYPE_FLOAT:
  11525. switch (loopMode) {
  11526. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11527. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11528. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11529. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11530. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11531. }
  11532. break;
  11533. case Animation.ANIMATIONTYPE_QUATERNION:
  11534. var quaternion = null;
  11535. switch (loopMode) {
  11536. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11537. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11538. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11539. break;
  11540. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11541. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11542. break;
  11543. }
  11544. return quaternion;
  11545. case Animation.ANIMATIONTYPE_VECTOR3:
  11546. switch (loopMode) {
  11547. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11548. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11549. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11550. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11551. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11552. }
  11553. case Animation.ANIMATIONTYPE_COLOR3:
  11554. switch (loopMode) {
  11555. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11556. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11557. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11558. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11559. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11560. }
  11561. case Animation.ANIMATIONTYPE_MATRIX:
  11562. switch (loopMode) {
  11563. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11564. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11565. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11566. return startValue;
  11567. }
  11568. default:
  11569. break;
  11570. }
  11571. break;
  11572. }
  11573. }
  11574. return this._keys[this._keys.length - 1].value;
  11575. };
  11576. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11577. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11578. this._stopped = true;
  11579. return false;
  11580. }
  11581. var returnValue = true;
  11582. if (this._keys[0].frame != 0) {
  11583. var newKey = {
  11584. frame: 0,
  11585. value: this._keys[0].value
  11586. };
  11587. this._keys.splice(0, 0, newKey);
  11588. }
  11589. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11590. from = this._keys[0].frame;
  11591. }
  11592. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11593. to = this._keys[this._keys.length - 1].frame;
  11594. }
  11595. var range = to - from;
  11596. var offsetValue;
  11597. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11598. if (ratio > range && !loop) {
  11599. returnValue = false;
  11600. highLimitValue = this._keys[this._keys.length - 1].value;
  11601. } else {
  11602. var highLimitValue = 0;
  11603. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11604. var keyOffset = to.toString() + from.toString();
  11605. if (!this._offsetsCache[keyOffset]) {
  11606. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11607. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11608. switch (this.dataType) {
  11609. case Animation.ANIMATIONTYPE_FLOAT:
  11610. this._offsetsCache[keyOffset] = toValue - fromValue;
  11611. break;
  11612. case Animation.ANIMATIONTYPE_QUATERNION:
  11613. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11614. break;
  11615. case Animation.ANIMATIONTYPE_VECTOR3:
  11616. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11617. case Animation.ANIMATIONTYPE_COLOR3:
  11618. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11619. default:
  11620. break;
  11621. }
  11622. this._highLimitsCache[keyOffset] = toValue;
  11623. }
  11624. highLimitValue = this._highLimitsCache[keyOffset];
  11625. offsetValue = this._offsetsCache[keyOffset];
  11626. }
  11627. }
  11628. if (offsetValue === undefined) {
  11629. switch (this.dataType) {
  11630. case Animation.ANIMATIONTYPE_FLOAT:
  11631. offsetValue = 0;
  11632. break;
  11633. case Animation.ANIMATIONTYPE_QUATERNION:
  11634. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11635. break;
  11636. case Animation.ANIMATIONTYPE_VECTOR3:
  11637. offsetValue = BABYLON.Vector3.Zero();
  11638. break;
  11639. case Animation.ANIMATIONTYPE_COLOR3:
  11640. offsetValue = BABYLON.Color3.Black();
  11641. }
  11642. }
  11643. var repeatCount = (ratio / range) >> 0;
  11644. var currentFrame = returnValue ? from + ratio % range : to;
  11645. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11646. if (this.targetPropertyPath.length > 1) {
  11647. var property = this._target[this.targetPropertyPath[0]];
  11648. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11649. property = property[this.targetPropertyPath[index]];
  11650. }
  11651. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11652. } else {
  11653. this._target[this.targetPropertyPath[0]] = currentValue;
  11654. }
  11655. if (this._target.markAsDirty) {
  11656. this._target.markAsDirty(this.targetProperty);
  11657. }
  11658. if (!returnValue) {
  11659. this._stopped = true;
  11660. }
  11661. return returnValue;
  11662. };
  11663. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11664. get: function () {
  11665. return Animation._ANIMATIONTYPE_FLOAT;
  11666. },
  11667. enumerable: true,
  11668. configurable: true
  11669. });
  11670. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11671. get: function () {
  11672. return Animation._ANIMATIONTYPE_VECTOR3;
  11673. },
  11674. enumerable: true,
  11675. configurable: true
  11676. });
  11677. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11678. get: function () {
  11679. return Animation._ANIMATIONTYPE_QUATERNION;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11685. get: function () {
  11686. return Animation._ANIMATIONTYPE_MATRIX;
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11692. get: function () {
  11693. return Animation._ANIMATIONTYPE_COLOR3;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11699. get: function () {
  11700. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11706. get: function () {
  11707. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11713. get: function () {
  11714. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Animation._ANIMATIONTYPE_FLOAT = 0;
  11720. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11721. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11722. Animation._ANIMATIONTYPE_MATRIX = 3;
  11723. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11724. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11725. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11726. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11727. return Animation;
  11728. })();
  11729. BABYLON.Animation = Animation;
  11730. })(BABYLON || (BABYLON = {}));
  11731. var BABYLON;
  11732. (function (BABYLON) {
  11733. var Animatable = (function () {
  11734. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11735. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11736. if (typeof toFrame === "undefined") { toFrame = 100; }
  11737. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11738. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11739. this.target = target;
  11740. this.fromFrame = fromFrame;
  11741. this.toFrame = toFrame;
  11742. this.loopAnimation = loopAnimation;
  11743. this.speedRatio = speedRatio;
  11744. this.onAnimationEnd = onAnimationEnd;
  11745. this._animations = new Array();
  11746. this._paused = false;
  11747. this.animationStarted = false;
  11748. if (animations) {
  11749. this.appendAnimations(target, animations);
  11750. }
  11751. this._scene = scene;
  11752. scene._activeAnimatables.push(this);
  11753. }
  11754. Animatable.prototype.appendAnimations = function (target, animations) {
  11755. for (var index = 0; index < animations.length; index++) {
  11756. var animation = animations[index];
  11757. animation._target = target;
  11758. this._animations.push(animation);
  11759. }
  11760. };
  11761. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11762. var animations = this._animations;
  11763. for (var index = 0; index < animations.length; index++) {
  11764. if (animations[index].targetProperty === property) {
  11765. return animations[index];
  11766. }
  11767. }
  11768. return null;
  11769. };
  11770. Animatable.prototype.pause = function () {
  11771. this._paused = true;
  11772. };
  11773. Animatable.prototype.restart = function () {
  11774. this._paused = false;
  11775. };
  11776. Animatable.prototype.stop = function () {
  11777. var index = this._scene._activeAnimatables.indexOf(this);
  11778. if (index > -1) {
  11779. this._scene._activeAnimatables.splice(index, 1);
  11780. }
  11781. if (this.onAnimationEnd) {
  11782. this.onAnimationEnd();
  11783. }
  11784. };
  11785. Animatable.prototype._animate = function (delay) {
  11786. if (this._paused) {
  11787. return true;
  11788. }
  11789. if (!this._localDelayOffset) {
  11790. this._localDelayOffset = delay;
  11791. }
  11792. var running = false;
  11793. var animations = this._animations;
  11794. for (var index = 0; index < animations.length; index++) {
  11795. var animation = animations[index];
  11796. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11797. running = running || isRunning;
  11798. }
  11799. if (!running && this.onAnimationEnd) {
  11800. this.onAnimationEnd();
  11801. }
  11802. return running;
  11803. };
  11804. return Animatable;
  11805. })();
  11806. BABYLON.Animatable = Animatable;
  11807. })(BABYLON || (BABYLON = {}));
  11808. var BABYLON;
  11809. (function (BABYLON) {
  11810. var Octree = (function () {
  11811. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11812. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11813. this.maxDepth = maxDepth;
  11814. this.dynamicContent = new Array();
  11815. this._maxBlockCapacity = maxBlockCapacity || 64;
  11816. this._selectionContent = new BABYLON.SmartArray(1024);
  11817. this._creationFunc = creationFunc;
  11818. }
  11819. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11820. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11821. };
  11822. Octree.prototype.addMesh = function (entry) {
  11823. for (var index = 0; index < this.blocks.length; index++) {
  11824. var block = this.blocks[index];
  11825. block.addEntry(entry);
  11826. }
  11827. };
  11828. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11829. this._selectionContent.reset();
  11830. for (var index = 0; index < this.blocks.length; index++) {
  11831. var block = this.blocks[index];
  11832. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11833. }
  11834. if (allowDuplicate) {
  11835. this._selectionContent.concat(this.dynamicContent);
  11836. } else {
  11837. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11838. }
  11839. return this._selectionContent;
  11840. };
  11841. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11842. this._selectionContent.reset();
  11843. for (var index = 0; index < this.blocks.length; index++) {
  11844. var block = this.blocks[index];
  11845. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11846. }
  11847. if (allowDuplicate) {
  11848. this._selectionContent.concat(this.dynamicContent);
  11849. } else {
  11850. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11851. }
  11852. return this._selectionContent;
  11853. };
  11854. Octree.prototype.intersectsRay = function (ray) {
  11855. this._selectionContent.reset();
  11856. for (var index = 0; index < this.blocks.length; index++) {
  11857. var block = this.blocks[index];
  11858. block.intersectsRay(ray, this._selectionContent);
  11859. }
  11860. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11861. return this._selectionContent;
  11862. };
  11863. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11864. target.blocks = new Array();
  11865. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11866. for (var x = 0; x < 2; x++) {
  11867. for (var y = 0; y < 2; y++) {
  11868. for (var z = 0; z < 2; z++) {
  11869. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11870. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11871. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11872. block.addEntries(entries);
  11873. target.blocks.push(block);
  11874. }
  11875. }
  11876. }
  11877. };
  11878. Octree.CreationFuncForMeshes = function (entry, block) {
  11879. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11880. block.entries.push(entry);
  11881. }
  11882. };
  11883. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11884. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11885. block.entries.push(entry);
  11886. }
  11887. };
  11888. return Octree;
  11889. })();
  11890. BABYLON.Octree = Octree;
  11891. })(BABYLON || (BABYLON = {}));
  11892. var BABYLON;
  11893. (function (BABYLON) {
  11894. var OctreeBlock = (function () {
  11895. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11896. this.entries = new Array();
  11897. this._boundingVectors = new Array();
  11898. this._capacity = capacity;
  11899. this._depth = depth;
  11900. this._maxDepth = maxDepth;
  11901. this._creationFunc = creationFunc;
  11902. this._minPoint = minPoint;
  11903. this._maxPoint = maxPoint;
  11904. this._boundingVectors.push(minPoint.clone());
  11905. this._boundingVectors.push(maxPoint.clone());
  11906. this._boundingVectors.push(minPoint.clone());
  11907. this._boundingVectors[2].x = maxPoint.x;
  11908. this._boundingVectors.push(minPoint.clone());
  11909. this._boundingVectors[3].y = maxPoint.y;
  11910. this._boundingVectors.push(minPoint.clone());
  11911. this._boundingVectors[4].z = maxPoint.z;
  11912. this._boundingVectors.push(maxPoint.clone());
  11913. this._boundingVectors[5].z = minPoint.z;
  11914. this._boundingVectors.push(maxPoint.clone());
  11915. this._boundingVectors[6].x = minPoint.x;
  11916. this._boundingVectors.push(maxPoint.clone());
  11917. this._boundingVectors[7].y = minPoint.y;
  11918. }
  11919. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  11920. get: function () {
  11921. return this._capacity;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  11927. get: function () {
  11928. return this._minPoint;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  11934. get: function () {
  11935. return this._maxPoint;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. OctreeBlock.prototype.addEntry = function (entry) {
  11941. if (this.blocks) {
  11942. for (var index = 0; index < this.blocks.length; index++) {
  11943. var block = this.blocks[index];
  11944. block.addEntry(entry);
  11945. }
  11946. return;
  11947. }
  11948. this._creationFunc(entry, this);
  11949. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  11950. this.createInnerBlocks();
  11951. }
  11952. };
  11953. OctreeBlock.prototype.addEntries = function (entries) {
  11954. for (var index = 0; index < entries.length; index++) {
  11955. var mesh = entries[index];
  11956. this.addEntry(mesh);
  11957. }
  11958. };
  11959. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  11960. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  11961. if (this.blocks) {
  11962. for (var index = 0; index < this.blocks.length; index++) {
  11963. var block = this.blocks[index];
  11964. block.select(frustumPlanes, selection, allowDuplicate);
  11965. }
  11966. return;
  11967. }
  11968. if (allowDuplicate) {
  11969. selection.concat(this.entries);
  11970. } else {
  11971. selection.concatWithNoDuplicate(this.entries);
  11972. }
  11973. }
  11974. };
  11975. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  11976. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  11977. if (this.blocks) {
  11978. for (var index = 0; index < this.blocks.length; index++) {
  11979. var block = this.blocks[index];
  11980. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  11981. }
  11982. return;
  11983. }
  11984. if (allowDuplicate) {
  11985. selection.concat(this.entries);
  11986. } else {
  11987. selection.concatWithNoDuplicate(this.entries);
  11988. }
  11989. }
  11990. };
  11991. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  11992. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  11993. if (this.blocks) {
  11994. for (var index = 0; index < this.blocks.length; index++) {
  11995. var block = this.blocks[index];
  11996. block.intersectsRay(ray, selection);
  11997. }
  11998. return;
  11999. }
  12000. selection.concatWithNoDuplicate(this.entries);
  12001. }
  12002. };
  12003. OctreeBlock.prototype.createInnerBlocks = function () {
  12004. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12005. };
  12006. return OctreeBlock;
  12007. })();
  12008. BABYLON.OctreeBlock = OctreeBlock;
  12009. })(BABYLON || (BABYLON = {}));
  12010. var BABYLON;
  12011. (function (BABYLON) {
  12012. var Bone = (function () {
  12013. function Bone(name, skeleton, parentBone, matrix) {
  12014. this.name = name;
  12015. this.children = new Array();
  12016. this.animations = new Array();
  12017. this._worldTransform = new BABYLON.Matrix();
  12018. this._absoluteTransform = new BABYLON.Matrix();
  12019. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12020. this._skeleton = skeleton;
  12021. this._matrix = matrix;
  12022. this._baseMatrix = matrix;
  12023. skeleton.bones.push(this);
  12024. if (parentBone) {
  12025. this._parent = parentBone;
  12026. parentBone.children.push(this);
  12027. } else {
  12028. this._parent = null;
  12029. }
  12030. this._updateDifferenceMatrix();
  12031. }
  12032. Bone.prototype.getParent = function () {
  12033. return this._parent;
  12034. };
  12035. Bone.prototype.getLocalMatrix = function () {
  12036. return this._matrix;
  12037. };
  12038. Bone.prototype.getBaseMatrix = function () {
  12039. return this._baseMatrix;
  12040. };
  12041. Bone.prototype.getWorldMatrix = function () {
  12042. return this._worldTransform;
  12043. };
  12044. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12045. return this._invertedAbsoluteTransform;
  12046. };
  12047. Bone.prototype.getAbsoluteMatrix = function () {
  12048. var matrix = this._matrix.clone();
  12049. var parent = this._parent;
  12050. while (parent) {
  12051. matrix = matrix.multiply(parent.getLocalMatrix());
  12052. parent = parent.getParent();
  12053. }
  12054. return matrix;
  12055. };
  12056. Bone.prototype.updateMatrix = function (matrix) {
  12057. this._matrix = matrix;
  12058. this._skeleton._markAsDirty();
  12059. this._updateDifferenceMatrix();
  12060. };
  12061. Bone.prototype._updateDifferenceMatrix = function () {
  12062. if (this._parent) {
  12063. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12064. } else {
  12065. this._absoluteTransform.copyFrom(this._matrix);
  12066. }
  12067. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12068. for (var index = 0; index < this.children.length; index++) {
  12069. this.children[index]._updateDifferenceMatrix();
  12070. }
  12071. };
  12072. Bone.prototype.markAsDirty = function () {
  12073. this._skeleton._markAsDirty();
  12074. };
  12075. return Bone;
  12076. })();
  12077. BABYLON.Bone = Bone;
  12078. })(BABYLON || (BABYLON = {}));
  12079. var BABYLON;
  12080. (function (BABYLON) {
  12081. var Skeleton = (function () {
  12082. function Skeleton(name, id, scene) {
  12083. this.name = name;
  12084. this.id = id;
  12085. this.bones = new Array();
  12086. this._isDirty = true;
  12087. this._identity = BABYLON.Matrix.Identity();
  12088. this.bones = [];
  12089. this._scene = scene;
  12090. scene.skeletons.push(this);
  12091. }
  12092. Skeleton.prototype.getTransformMatrices = function () {
  12093. return this._transformMatrices;
  12094. };
  12095. Skeleton.prototype._markAsDirty = function () {
  12096. this._isDirty = true;
  12097. };
  12098. Skeleton.prototype.prepare = function () {
  12099. if (!this._isDirty) {
  12100. return;
  12101. }
  12102. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12103. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12104. }
  12105. for (var index = 0; index < this.bones.length; index++) {
  12106. var bone = this.bones[index];
  12107. var parentBone = bone.getParent();
  12108. if (parentBone) {
  12109. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12110. } else {
  12111. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12112. }
  12113. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12114. }
  12115. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12116. this._isDirty = false;
  12117. };
  12118. Skeleton.prototype.getAnimatables = function () {
  12119. if (!this._animatables || this._animatables.length != this.bones.length) {
  12120. this._animatables = [];
  12121. for (var index = 0; index < this.bones.length; index++) {
  12122. this._animatables.push(this.bones[index]);
  12123. }
  12124. }
  12125. return this._animatables;
  12126. };
  12127. Skeleton.prototype.clone = function (name, id) {
  12128. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12129. for (var index = 0; index < this.bones.length; index++) {
  12130. var source = this.bones[index];
  12131. var parentBone = null;
  12132. if (source.getParent()) {
  12133. var parentIndex = this.bones.indexOf(source.getParent());
  12134. parentBone = result.bones[parentIndex];
  12135. }
  12136. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12137. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12138. }
  12139. return result;
  12140. };
  12141. return Skeleton;
  12142. })();
  12143. BABYLON.Skeleton = Skeleton;
  12144. })(BABYLON || (BABYLON = {}));
  12145. var BABYLON;
  12146. (function (BABYLON) {
  12147. var PostProcess = (function () {
  12148. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12149. this.name = name;
  12150. this.width = -1;
  12151. this.height = -1;
  12152. this._reusable = false;
  12153. this._textures = new BABYLON.SmartArray(2);
  12154. this._currentRenderTextureInd = 0;
  12155. if (camera != null) {
  12156. this._camera = camera;
  12157. this._scene = camera.getScene();
  12158. camera.attachPostProcess(this);
  12159. this._engine = this._scene.getEngine();
  12160. } else {
  12161. this._engine = engine;
  12162. }
  12163. this._renderRatio = ratio;
  12164. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12165. this._reusable = reusable || false;
  12166. samplers = samplers || [];
  12167. samplers.push("textureSampler");
  12168. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12169. }
  12170. PostProcess.prototype.isReusable = function () {
  12171. return this._reusable;
  12172. };
  12173. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12174. camera = camera || this._camera;
  12175. var scene = camera.getScene();
  12176. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12177. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12178. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12179. if (this._textures.length > 0) {
  12180. for (var i = 0; i < this._textures.length; i++) {
  12181. this._engine._releaseTexture(this._textures.data[i]);
  12182. }
  12183. this._textures.reset();
  12184. }
  12185. this.width = desiredWidth;
  12186. this.height = desiredHeight;
  12187. 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 }));
  12188. if (this._reusable) {
  12189. 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 }));
  12190. }
  12191. if (this.onSizeChanged) {
  12192. this.onSizeChanged();
  12193. }
  12194. }
  12195. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12196. if (this.onActivate) {
  12197. this.onActivate(camera);
  12198. }
  12199. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12200. if (this._reusable) {
  12201. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12202. }
  12203. };
  12204. PostProcess.prototype.apply = function () {
  12205. if (!this._effect.isReady())
  12206. return null;
  12207. this._engine.enableEffect(this._effect);
  12208. this._engine.setState(false);
  12209. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12210. this._engine.setDepthBuffer(false);
  12211. this._engine.setDepthWrite(false);
  12212. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12213. if (this.onApply) {
  12214. this.onApply(this._effect);
  12215. }
  12216. return this._effect;
  12217. };
  12218. PostProcess.prototype.dispose = function (camera) {
  12219. camera = camera || this._camera;
  12220. if (this._textures.length > 0) {
  12221. for (var i = 0; i < this._textures.length; i++) {
  12222. this._engine._releaseTexture(this._textures.data[i]);
  12223. }
  12224. this._textures.reset();
  12225. }
  12226. camera.detachPostProcess(this);
  12227. var index = camera._postProcesses.indexOf(this);
  12228. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12229. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12230. }
  12231. };
  12232. return PostProcess;
  12233. })();
  12234. BABYLON.PostProcess = PostProcess;
  12235. })(BABYLON || (BABYLON = {}));
  12236. var BABYLON;
  12237. (function (BABYLON) {
  12238. var PostProcessManager = (function () {
  12239. function PostProcessManager(scene) {
  12240. this._vertexDeclaration = [2];
  12241. this._vertexStrideSize = 2 * 4;
  12242. this._scene = scene;
  12243. var vertices = [];
  12244. vertices.push(1, 1);
  12245. vertices.push(-1, 1);
  12246. vertices.push(-1, -1);
  12247. vertices.push(1, -1);
  12248. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12249. var indices = [];
  12250. indices.push(0);
  12251. indices.push(1);
  12252. indices.push(2);
  12253. indices.push(0);
  12254. indices.push(2);
  12255. indices.push(3);
  12256. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12257. }
  12258. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12259. var postProcesses = this._scene.activeCamera._postProcesses;
  12260. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12261. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12262. return false;
  12263. }
  12264. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12265. return true;
  12266. };
  12267. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12268. var postProcesses = this._scene.activeCamera._postProcesses;
  12269. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12270. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12271. return;
  12272. }
  12273. var engine = this._scene.getEngine();
  12274. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12275. if (index < postProcessesTakenIndices.length - 1) {
  12276. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12277. } else {
  12278. if (targetTexture) {
  12279. engine.bindFramebuffer(targetTexture);
  12280. } else {
  12281. engine.restoreDefaultFramebuffer();
  12282. }
  12283. }
  12284. if (doNotPresent) {
  12285. break;
  12286. }
  12287. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12288. if (effect) {
  12289. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12290. engine.draw(true, 0, 6);
  12291. }
  12292. }
  12293. engine.setDepthBuffer(true);
  12294. engine.setDepthWrite(true);
  12295. };
  12296. PostProcessManager.prototype.dispose = function () {
  12297. if (this._vertexBuffer) {
  12298. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12299. this._vertexBuffer = null;
  12300. }
  12301. if (this._indexBuffer) {
  12302. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12303. this._indexBuffer = null;
  12304. }
  12305. };
  12306. return PostProcessManager;
  12307. })();
  12308. BABYLON.PostProcessManager = PostProcessManager;
  12309. })(BABYLON || (BABYLON = {}));
  12310. var __extends = this.__extends || function (d, b) {
  12311. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12312. function __() { this.constructor = d; }
  12313. __.prototype = b.prototype;
  12314. d.prototype = new __();
  12315. };
  12316. var BABYLON;
  12317. (function (BABYLON) {
  12318. var PassPostProcess = (function (_super) {
  12319. __extends(PassPostProcess, _super);
  12320. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12321. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12322. }
  12323. return PassPostProcess;
  12324. })(BABYLON.PostProcess);
  12325. BABYLON.PassPostProcess = PassPostProcess;
  12326. })(BABYLON || (BABYLON = {}));
  12327. var __extends = this.__extends || function (d, b) {
  12328. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12329. function __() { this.constructor = d; }
  12330. __.prototype = b.prototype;
  12331. d.prototype = new __();
  12332. };
  12333. var BABYLON;
  12334. (function (BABYLON) {
  12335. var BlurPostProcess = (function (_super) {
  12336. __extends(BlurPostProcess, _super);
  12337. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12338. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12339. var _this = this;
  12340. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12341. this.direction = direction;
  12342. this.blurWidth = blurWidth;
  12343. this.onApply = function (effect) {
  12344. effect.setFloat2("screenSize", _this.width, _this.height);
  12345. effect.setVector2("direction", _this.direction);
  12346. effect.setFloat("blurWidth", _this.blurWidth);
  12347. };
  12348. }
  12349. return BlurPostProcess;
  12350. })(BABYLON.PostProcess);
  12351. BABYLON.BlurPostProcess = BlurPostProcess;
  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 FilterPostProcess = (function (_super) {
  12362. __extends(FilterPostProcess, _super);
  12363. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12364. var _this = this;
  12365. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12366. this.kernelMatrix = kernelMatrix;
  12367. this.onApply = function (effect) {
  12368. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12369. };
  12370. }
  12371. return FilterPostProcess;
  12372. })(BABYLON.PostProcess);
  12373. BABYLON.FilterPostProcess = FilterPostProcess;
  12374. })(BABYLON || (BABYLON = {}));
  12375. var __extends = this.__extends || function (d, b) {
  12376. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12377. function __() { this.constructor = d; }
  12378. __.prototype = b.prototype;
  12379. d.prototype = new __();
  12380. };
  12381. var BABYLON;
  12382. (function (BABYLON) {
  12383. var RefractionPostProcess = (function (_super) {
  12384. __extends(RefractionPostProcess, _super);
  12385. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12386. var _this = this;
  12387. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12388. this.color = color;
  12389. this.depth = depth;
  12390. this.colorLevel = colorLevel;
  12391. this.onActivate = function (cam) {
  12392. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12393. };
  12394. this.onApply = function (effect) {
  12395. effect.setColor3("baseColor", _this.color);
  12396. effect.setFloat("depth", _this.depth);
  12397. effect.setFloat("colorLevel", _this.colorLevel);
  12398. effect.setTexture("refractionSampler", _this._refRexture);
  12399. };
  12400. }
  12401. RefractionPostProcess.prototype.dispose = function (camera) {
  12402. if (this._refRexture) {
  12403. this._refRexture.dispose();
  12404. }
  12405. _super.prototype.dispose.call(this, camera);
  12406. };
  12407. return RefractionPostProcess;
  12408. })(BABYLON.PostProcess);
  12409. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12410. })(BABYLON || (BABYLON = {}));
  12411. var __extends = this.__extends || function (d, b) {
  12412. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12413. function __() { this.constructor = d; }
  12414. __.prototype = b.prototype;
  12415. d.prototype = new __();
  12416. };
  12417. var BABYLON;
  12418. (function (BABYLON) {
  12419. var BlackAndWhitePostProcess = (function (_super) {
  12420. __extends(BlackAndWhitePostProcess, _super);
  12421. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12422. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12423. }
  12424. return BlackAndWhitePostProcess;
  12425. })(BABYLON.PostProcess);
  12426. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12427. })(BABYLON || (BABYLON = {}));
  12428. var __extends = this.__extends || function (d, b) {
  12429. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12430. function __() { this.constructor = d; }
  12431. __.prototype = b.prototype;
  12432. d.prototype = new __();
  12433. };
  12434. var BABYLON;
  12435. (function (BABYLON) {
  12436. var ConvolutionPostProcess = (function (_super) {
  12437. __extends(ConvolutionPostProcess, _super);
  12438. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12439. var _this = this;
  12440. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12441. this.kernel = kernel;
  12442. this.onApply = function (effect) {
  12443. effect.setFloat2("screenSize", _this.width, _this.height);
  12444. effect.setArray("kernel", _this.kernel);
  12445. };
  12446. }
  12447. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12448. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12449. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12450. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12451. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12452. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12453. return ConvolutionPostProcess;
  12454. })(BABYLON.PostProcess);
  12455. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12456. })(BABYLON || (BABYLON = {}));
  12457. var __extends = this.__extends || function (d, b) {
  12458. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12459. function __() { this.constructor = d; }
  12460. __.prototype = b.prototype;
  12461. d.prototype = new __();
  12462. };
  12463. var BABYLON;
  12464. (function (BABYLON) {
  12465. var FxaaPostProcess = (function (_super) {
  12466. __extends(FxaaPostProcess, _super);
  12467. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12468. var _this = this;
  12469. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12470. this.onSizeChanged = function () {
  12471. _this.texelWidth = 1.0 / _this.width;
  12472. _this.texelHeight = 1.0 / _this.height;
  12473. };
  12474. this.onApply = function (effect) {
  12475. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12476. };
  12477. }
  12478. return FxaaPostProcess;
  12479. })(BABYLON.PostProcess);
  12480. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12481. })(BABYLON || (BABYLON = {}));
  12482. var BABYLON;
  12483. (function (BABYLON) {
  12484. var LensFlare = (function () {
  12485. function LensFlare(size, position, color, imgUrl, system) {
  12486. this.size = size;
  12487. this.position = position;
  12488. this.dispose = function () {
  12489. if (this.texture) {
  12490. this.texture.dispose();
  12491. }
  12492. var index = this._system.lensFlares.indexOf(this);
  12493. this._system.lensFlares.splice(index, 1);
  12494. };
  12495. this.color = color || new BABYLON.Color3(1, 1, 1);
  12496. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12497. this._system = system;
  12498. system.lensFlares.push(this);
  12499. }
  12500. return LensFlare;
  12501. })();
  12502. BABYLON.LensFlare = LensFlare;
  12503. })(BABYLON || (BABYLON = {}));
  12504. var BABYLON;
  12505. (function (BABYLON) {
  12506. var LensFlareSystem = (function () {
  12507. function LensFlareSystem(name, emitter, scene) {
  12508. this.name = name;
  12509. this.lensFlares = new Array();
  12510. this.borderLimit = 300;
  12511. this._vertexDeclaration = [2];
  12512. this._vertexStrideSize = 2 * 4;
  12513. this._isEnabled = true;
  12514. this._scene = scene;
  12515. this._emitter = emitter;
  12516. scene.lensFlareSystems.push(this);
  12517. this.meshesSelectionPredicate = function (m) {
  12518. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12519. };
  12520. var vertices = [];
  12521. vertices.push(1, 1);
  12522. vertices.push(-1, 1);
  12523. vertices.push(-1, -1);
  12524. vertices.push(1, -1);
  12525. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12526. var indices = [];
  12527. indices.push(0);
  12528. indices.push(1);
  12529. indices.push(2);
  12530. indices.push(0);
  12531. indices.push(2);
  12532. indices.push(3);
  12533. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12534. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12535. }
  12536. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12537. get: function () {
  12538. return this._isEnabled;
  12539. },
  12540. set: function (value) {
  12541. this._isEnabled = value;
  12542. },
  12543. enumerable: true,
  12544. configurable: true
  12545. });
  12546. LensFlareSystem.prototype.getScene = function () {
  12547. return this._scene;
  12548. };
  12549. LensFlareSystem.prototype.getEmitter = function () {
  12550. return this._emitter;
  12551. };
  12552. LensFlareSystem.prototype.getEmitterPosition = function () {
  12553. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12554. };
  12555. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12556. var position = this.getEmitterPosition();
  12557. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12558. this._positionX = position.x;
  12559. this._positionY = position.y;
  12560. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12561. if (position.z > 0) {
  12562. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12563. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12564. return true;
  12565. }
  12566. }
  12567. return false;
  12568. };
  12569. LensFlareSystem.prototype._isVisible = function () {
  12570. if (!this._isEnabled) {
  12571. return false;
  12572. }
  12573. var emitterPosition = this.getEmitterPosition();
  12574. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12575. var distance = direction.length();
  12576. direction.normalize();
  12577. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12578. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12579. return !pickInfo.hit || pickInfo.distance > distance;
  12580. };
  12581. LensFlareSystem.prototype.render = function () {
  12582. if (!this._effect.isReady())
  12583. return false;
  12584. var engine = this._scene.getEngine();
  12585. var viewport = this._scene.activeCamera.viewport;
  12586. var globalViewport = viewport.toGlobal(engine);
  12587. if (!this.computeEffectivePosition(globalViewport)) {
  12588. return false;
  12589. }
  12590. if (!this._isVisible()) {
  12591. return false;
  12592. }
  12593. var awayX;
  12594. var awayY;
  12595. if (this._positionX < this.borderLimit + globalViewport.x) {
  12596. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12597. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12598. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12599. } else {
  12600. awayX = 0;
  12601. }
  12602. if (this._positionY < this.borderLimit + globalViewport.y) {
  12603. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12604. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12605. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12606. } else {
  12607. awayY = 0;
  12608. }
  12609. var away = (awayX > awayY) ? awayX : awayY;
  12610. if (away > this.borderLimit) {
  12611. away = this.borderLimit;
  12612. }
  12613. var intensity = 1.0 - (away / this.borderLimit);
  12614. if (intensity < 0) {
  12615. return false;
  12616. }
  12617. if (intensity > 1.0) {
  12618. intensity = 1.0;
  12619. }
  12620. var centerX = globalViewport.x + globalViewport.width / 2;
  12621. var centerY = globalViewport.y + globalViewport.height / 2;
  12622. var distX = centerX - this._positionX;
  12623. var distY = centerY - this._positionY;
  12624. engine.enableEffect(this._effect);
  12625. engine.setState(false);
  12626. engine.setDepthBuffer(false);
  12627. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12628. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12629. for (var index = 0; index < this.lensFlares.length; index++) {
  12630. var flare = this.lensFlares[index];
  12631. var x = centerX - (distX * flare.position);
  12632. var y = centerY - (distY * flare.position);
  12633. var cw = flare.size;
  12634. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12635. var cx = 2 * (x / globalViewport.width) - 1.0;
  12636. var cy = 1.0 - 2 * (y / globalViewport.height);
  12637. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12638. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12639. this._effect.setTexture("textureSampler", flare.texture);
  12640. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12641. engine.draw(true, 0, 6);
  12642. }
  12643. engine.setDepthBuffer(true);
  12644. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12645. return true;
  12646. };
  12647. LensFlareSystem.prototype.dispose = function () {
  12648. if (this._vertexBuffer) {
  12649. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12650. this._vertexBuffer = null;
  12651. }
  12652. if (this._indexBuffer) {
  12653. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12654. this._indexBuffer = null;
  12655. }
  12656. while (this.lensFlares.length) {
  12657. this.lensFlares[0].dispose();
  12658. }
  12659. var index = this._scene.lensFlareSystems.indexOf(this);
  12660. this._scene.lensFlareSystems.splice(index, 1);
  12661. };
  12662. return LensFlareSystem;
  12663. })();
  12664. BABYLON.LensFlareSystem = LensFlareSystem;
  12665. })(BABYLON || (BABYLON = {}));
  12666. var BABYLON;
  12667. (function (BABYLON) {
  12668. var IntersectionInfo = (function () {
  12669. function IntersectionInfo(bu, bv, distance) {
  12670. this.bu = bu;
  12671. this.bv = bv;
  12672. this.distance = distance;
  12673. this.faceId = 0;
  12674. }
  12675. return IntersectionInfo;
  12676. })();
  12677. BABYLON.IntersectionInfo = IntersectionInfo;
  12678. var PickingInfo = (function () {
  12679. function PickingInfo() {
  12680. this.hit = false;
  12681. this.distance = 0;
  12682. this.pickedPoint = null;
  12683. this.pickedMesh = null;
  12684. this.bu = 0;
  12685. this.bv = 0;
  12686. this.faceId = -1;
  12687. }
  12688. PickingInfo.prototype.getNormal = function () {
  12689. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12690. return null;
  12691. }
  12692. var indices = this.pickedMesh.getIndices();
  12693. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12694. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12695. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12696. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12697. normal0 = normal0.scale(this.bu);
  12698. normal1 = normal1.scale(this.bv);
  12699. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12700. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12701. };
  12702. PickingInfo.prototype.getTextureCoordinates = function () {
  12703. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12704. return null;
  12705. }
  12706. var indices = this.pickedMesh.getIndices();
  12707. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12708. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12709. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12710. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12711. uv0 = uv0.scale(this.bu);
  12712. uv1 = uv1.scale(this.bv);
  12713. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12714. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12715. };
  12716. return PickingInfo;
  12717. })();
  12718. BABYLON.PickingInfo = PickingInfo;
  12719. })(BABYLON || (BABYLON = {}));
  12720. var BABYLON;
  12721. (function (BABYLON) {
  12722. var FilesInput = (function () {
  12723. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12724. this.engine = p_engine;
  12725. this.canvas = p_canvas;
  12726. this.currentScene = p_scene;
  12727. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12728. this.progressCallback = p_progressCallback;
  12729. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12730. this.textureLoadingCallback = p_textureLoadingCallback;
  12731. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12732. }
  12733. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12734. var _this = this;
  12735. if (p_elementToMonitor) {
  12736. this.elementToMonitor = p_elementToMonitor;
  12737. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12738. _this.drag(e);
  12739. }, false);
  12740. this.elementToMonitor.addEventListener("dragover", function (e) {
  12741. _this.drag(e);
  12742. }, false);
  12743. this.elementToMonitor.addEventListener("drop", function (e) {
  12744. _this.drop(e);
  12745. }, false);
  12746. }
  12747. };
  12748. FilesInput.prototype.renderFunction = function () {
  12749. if (this.additionnalRenderLoopLogicCallback) {
  12750. this.additionnalRenderLoopLogicCallback();
  12751. }
  12752. if (this.currentScene) {
  12753. if (this.textureLoadingCallback) {
  12754. var remaining = this.currentScene.getWaitingItemsCount();
  12755. if (remaining > 0) {
  12756. this.textureLoadingCallback(remaining);
  12757. }
  12758. }
  12759. this.currentScene.render();
  12760. }
  12761. };
  12762. FilesInput.prototype.drag = function (e) {
  12763. e.stopPropagation();
  12764. e.preventDefault();
  12765. };
  12766. FilesInput.prototype.drop = function (eventDrop) {
  12767. eventDrop.stopPropagation();
  12768. eventDrop.preventDefault();
  12769. this.loadFiles(eventDrop);
  12770. };
  12771. FilesInput.prototype.loadFiles = function (event) {
  12772. var _this = this;
  12773. var that = this;
  12774. if (this.startingProcessingFilesCallback)
  12775. this.startingProcessingFilesCallback();
  12776. var sceneFileToLoad;
  12777. var filesToLoad;
  12778. if (event && event.dataTransfer && event.dataTransfer.files) {
  12779. filesToLoad = event.dataTransfer.files;
  12780. }
  12781. if (event && event.target && event.target.files) {
  12782. filesToLoad = event.target.files;
  12783. }
  12784. if (filesToLoad && filesToLoad.length > 0) {
  12785. for (var i = 0; i < filesToLoad.length; i++) {
  12786. switch (filesToLoad[i].type) {
  12787. case "image/jpeg":
  12788. case "image/png":
  12789. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12790. break;
  12791. case "image/targa":
  12792. case "image/vnd.ms-dds":
  12793. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12794. break;
  12795. default:
  12796. 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) {
  12797. sceneFileToLoad = filesToLoad[i];
  12798. }
  12799. break;
  12800. }
  12801. }
  12802. if (sceneFileToLoad) {
  12803. if (this.currentScene) {
  12804. this.engine.stopRenderLoop();
  12805. this.currentScene.dispose();
  12806. }
  12807. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12808. that.currentScene = newScene;
  12809. that.currentScene.executeWhenReady(function () {
  12810. if (that.currentScene.activeCamera) {
  12811. that.currentScene.activeCamera.attachControl(that.canvas);
  12812. }
  12813. if (that.sceneLoadedCallback) {
  12814. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12815. }
  12816. that.engine.runRenderLoop(function () {
  12817. that.renderFunction();
  12818. });
  12819. });
  12820. }, function (progress) {
  12821. if (_this.progressCallback) {
  12822. _this.progressCallback(progress);
  12823. }
  12824. });
  12825. } else {
  12826. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12827. }
  12828. }
  12829. };
  12830. FilesInput.FilesTextures = new Array();
  12831. FilesInput.FilesToLoad = new Array();
  12832. return FilesInput;
  12833. })();
  12834. BABYLON.FilesInput = FilesInput;
  12835. })(BABYLON || (BABYLON = {}));
  12836. var BABYLON;
  12837. (function (BABYLON) {
  12838. var OimoJSPlugin = (function () {
  12839. function OimoJSPlugin() {
  12840. this._registeredMeshes = [];
  12841. /**
  12842. * Update the body position according to the mesh position
  12843. * @param mesh
  12844. */
  12845. this.updateBodyPosition = function (mesh) {
  12846. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12847. var registeredMesh = this._registeredMeshes[index];
  12848. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12849. var body = registeredMesh.body.body;
  12850. var center = mesh.getBoundingInfo().boundingBox.center;
  12851. body.setPosition(center.x, center.y, center.z);
  12852. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12853. return;
  12854. }
  12855. if (registeredMesh.mesh.parent === mesh) {
  12856. mesh.computeWorldMatrix(true);
  12857. registeredMesh.mesh.computeWorldMatrix(true);
  12858. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12859. var absoluteRotation = mesh.rotation;
  12860. body = registeredMesh.body.body;
  12861. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12862. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12863. return;
  12864. }
  12865. }
  12866. };
  12867. }
  12868. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12869. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12870. };
  12871. OimoJSPlugin.prototype.initialize = function (iterations) {
  12872. this._world = new OIMO.World();
  12873. this._world.clear();
  12874. };
  12875. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12876. this._world.gravity = gravity;
  12877. };
  12878. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12879. var body = null;
  12880. this.unregisterMesh(mesh);
  12881. mesh.computeWorldMatrix(true);
  12882. switch (impostor) {
  12883. case BABYLON.PhysicsEngine.SphereImpostor:
  12884. var bbox = mesh.getBoundingInfo().boundingBox;
  12885. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12886. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12887. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12888. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12889. var deltaPosition = mesh.position.subtract(bbox.center);
  12890. body = new OIMO.Body({
  12891. type: 'sphere',
  12892. size: [size],
  12893. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12894. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12895. move: options.mass != 0,
  12896. config: [options.mass, options.friction, options.restitution],
  12897. world: this._world
  12898. });
  12899. this._registeredMeshes.push({
  12900. mesh: mesh,
  12901. body: body,
  12902. delta: deltaPosition
  12903. });
  12904. break;
  12905. case BABYLON.PhysicsEngine.PlaneImpostor:
  12906. case BABYLON.PhysicsEngine.BoxImpostor:
  12907. bbox = mesh.getBoundingInfo().boundingBox;
  12908. var min = bbox.minimumWorld;
  12909. var max = bbox.maximumWorld;
  12910. var box = max.subtract(min);
  12911. var sizeX = this._checkWithEpsilon(box.x);
  12912. var sizeY = this._checkWithEpsilon(box.y);
  12913. var sizeZ = this._checkWithEpsilon(box.z);
  12914. var deltaPosition = mesh.position.subtract(bbox.center);
  12915. body = new OIMO.Body({
  12916. type: 'box',
  12917. size: [sizeX, sizeY, sizeZ],
  12918. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12919. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12920. move: options.mass != 0,
  12921. config: [options.mass, options.friction, options.restitution],
  12922. world: this._world
  12923. });
  12924. this._registeredMeshes.push({
  12925. mesh: mesh,
  12926. body: body,
  12927. delta: deltaPosition
  12928. });
  12929. break;
  12930. }
  12931. return body;
  12932. };
  12933. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  12934. var types = [], sizes = [], positions = [], rotations = [];
  12935. var initialMesh = parts[0].mesh;
  12936. for (var index = 0; index < parts.length; index++) {
  12937. var part = parts[index];
  12938. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  12939. types.push(bodyParameters.type);
  12940. sizes.push.apply(sizes, bodyParameters.size);
  12941. positions.push.apply(positions, bodyParameters.pos);
  12942. rotations.push.apply(rotations, bodyParameters.rot);
  12943. }
  12944. var body = new OIMO.Body({
  12945. type: types,
  12946. size: sizes,
  12947. pos: positions,
  12948. rot: rotations,
  12949. move: options.mass != 0,
  12950. config: [options.mass, options.friction, options.restitution],
  12951. world: this._world
  12952. });
  12953. this._registeredMeshes.push({
  12954. mesh: initialMesh,
  12955. body: body
  12956. });
  12957. return body;
  12958. };
  12959. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  12960. var bodyParameters = null;
  12961. var mesh = part.mesh;
  12962. switch (part.impostor) {
  12963. case BABYLON.PhysicsEngine.SphereImpostor:
  12964. var bbox = mesh.getBoundingInfo().boundingBox;
  12965. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12966. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12967. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12968. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12969. bodyParameters = {
  12970. type: 'sphere',
  12971. /* bug with oimo : sphere needs 3 sizes in this case */
  12972. size: [size, -1, -1],
  12973. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  12974. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12975. };
  12976. break;
  12977. case BABYLON.PhysicsEngine.PlaneImpostor:
  12978. case BABYLON.PhysicsEngine.BoxImpostor:
  12979. bbox = mesh.getBoundingInfo().boundingBox;
  12980. var min = bbox.minimumWorld;
  12981. var max = bbox.maximumWorld;
  12982. var box = max.subtract(min);
  12983. var sizeX = this._checkWithEpsilon(box.x);
  12984. var sizeY = this._checkWithEpsilon(box.y);
  12985. var sizeZ = this._checkWithEpsilon(box.z);
  12986. var relativePosition = mesh.position;
  12987. bodyParameters = {
  12988. type: 'box',
  12989. size: [sizeX, sizeY, sizeZ],
  12990. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  12991. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12992. };
  12993. break;
  12994. }
  12995. return bodyParameters;
  12996. };
  12997. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  12998. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12999. var registeredMesh = this._registeredMeshes[index];
  13000. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13001. if (registeredMesh.body) {
  13002. this._world.removeRigidBody(registeredMesh.body.body);
  13003. this._unbindBody(registeredMesh.body);
  13004. }
  13005. this._registeredMeshes.splice(index, 1);
  13006. return;
  13007. }
  13008. }
  13009. };
  13010. OimoJSPlugin.prototype._unbindBody = function (body) {
  13011. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13012. var registeredMesh = this._registeredMeshes[index];
  13013. if (registeredMesh.body === body) {
  13014. registeredMesh.body = null;
  13015. }
  13016. }
  13017. };
  13018. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13019. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13020. var registeredMesh = this._registeredMeshes[index];
  13021. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13022. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE));
  13023. return;
  13024. }
  13025. }
  13026. };
  13027. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13028. var body1 = null, body2 = null;
  13029. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13030. var registeredMesh = this._registeredMeshes[index];
  13031. if (registeredMesh.mesh === mesh1) {
  13032. body1 = registeredMesh.body.body;
  13033. } else if (registeredMesh.mesh === mesh2) {
  13034. body2 = registeredMesh.body.body;
  13035. }
  13036. }
  13037. if (!body1 || !body2) {
  13038. return false;
  13039. }
  13040. if (!options) {
  13041. options = {};
  13042. }
  13043. new OIMO.Link({
  13044. type: options.type,
  13045. body1: body1,
  13046. body2: body2,
  13047. min: options.min,
  13048. max: options.max,
  13049. axe1: options.axe1,
  13050. axe2: options.axe2,
  13051. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13052. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13053. collision: options.collision,
  13054. spring: options.spring,
  13055. world: this._world
  13056. });
  13057. return true;
  13058. };
  13059. OimoJSPlugin.prototype.dispose = function () {
  13060. this._world.clear();
  13061. while (this._registeredMeshes.length) {
  13062. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13063. }
  13064. };
  13065. OimoJSPlugin.prototype.isSupported = function () {
  13066. return OIMO !== undefined;
  13067. };
  13068. OimoJSPlugin.prototype._getLastShape = function (body) {
  13069. var lastShape = body.shapes;
  13070. while (lastShape.next) {
  13071. lastShape = lastShape.next;
  13072. }
  13073. return lastShape;
  13074. };
  13075. OimoJSPlugin.prototype.runOneStep = function (time) {
  13076. this._world.step();
  13077. var i = this._registeredMeshes.length;
  13078. var m;
  13079. while (i--) {
  13080. var body = this._registeredMeshes[i].body.body;
  13081. var mesh = this._registeredMeshes[i].mesh;
  13082. var delta = this._registeredMeshes[i].delta;
  13083. if (!body.sleeping) {
  13084. if (body.shapes.next) {
  13085. var parentShape = this._getLastShape(body);
  13086. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13087. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13088. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13089. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13090. if (!mesh.rotationQuaternion) {
  13091. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13092. }
  13093. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13094. } else {
  13095. m = body.getMatrix();
  13096. mtx = BABYLON.Matrix.FromArray(m);
  13097. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13098. if (!delta) {
  13099. mesh.position.x = bodyX;
  13100. mesh.position.y = bodyY;
  13101. mesh.position.z = bodyZ;
  13102. } else {
  13103. mesh.position.x = bodyX + delta.x;
  13104. mesh.position.y = bodyY + delta.y;
  13105. mesh.position.z = bodyZ + delta.z;
  13106. }
  13107. if (!mesh.rotationQuaternion) {
  13108. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13109. }
  13110. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13111. }
  13112. }
  13113. }
  13114. };
  13115. return OimoJSPlugin;
  13116. })();
  13117. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13118. })(BABYLON || (BABYLON = {}));
  13119. var BABYLON;
  13120. (function (BABYLON) {
  13121. var PhysicsEngine = (function () {
  13122. function PhysicsEngine(plugin) {
  13123. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13124. }
  13125. PhysicsEngine.prototype._initialize = function (gravity) {
  13126. this._currentPlugin.initialize();
  13127. this._setGravity(gravity);
  13128. };
  13129. PhysicsEngine.prototype._runOneStep = function (delta) {
  13130. if (delta > 0.1) {
  13131. delta = 0.1;
  13132. } else if (delta <= 0) {
  13133. delta = 1.0 / 60.0;
  13134. }
  13135. this._currentPlugin.runOneStep(delta);
  13136. };
  13137. PhysicsEngine.prototype._setGravity = function (gravity) {
  13138. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13139. this._currentPlugin.setGravity(this.gravity);
  13140. };
  13141. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13142. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13143. };
  13144. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13145. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13146. };
  13147. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13148. this._currentPlugin.unregisterMesh(mesh);
  13149. };
  13150. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13151. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13152. };
  13153. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13154. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13155. };
  13156. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13157. this._currentPlugin.updateBodyPosition(mesh);
  13158. };
  13159. PhysicsEngine.prototype.dispose = function () {
  13160. this._currentPlugin.dispose();
  13161. };
  13162. PhysicsEngine.prototype.isSupported = function () {
  13163. return this._currentPlugin.isSupported();
  13164. };
  13165. PhysicsEngine.NoImpostor = 0;
  13166. PhysicsEngine.SphereImpostor = 1;
  13167. PhysicsEngine.BoxImpostor = 2;
  13168. PhysicsEngine.PlaneImpostor = 3;
  13169. PhysicsEngine.CompoundImpostor = 4;
  13170. PhysicsEngine.MeshImpostor = 4;
  13171. PhysicsEngine.CapsuleImpostor = 5;
  13172. PhysicsEngine.ConeImpostor = 6;
  13173. PhysicsEngine.CylinderImpostor = 7;
  13174. PhysicsEngine.ConvexHullImpostor = 8;
  13175. PhysicsEngine.Epsilon = 0.001;
  13176. return PhysicsEngine;
  13177. })();
  13178. BABYLON.PhysicsEngine = PhysicsEngine;
  13179. })(BABYLON || (BABYLON = {}));
  13180. var BABYLON;
  13181. (function (BABYLON) {
  13182. var serializeLight = function (light) {
  13183. var serializationObject = {};
  13184. serializationObject.name = light.name;
  13185. serializationObject.id = light.id;
  13186. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13187. if (light instanceof BABYLON.PointLight) {
  13188. serializationObject.type = 0;
  13189. serializationObject.position = light.position.asArray();
  13190. } else if (light instanceof BABYLON.DirectionalLight) {
  13191. serializationObject.type = 1;
  13192. var directionalLight = light;
  13193. serializationObject.position = directionalLight.position.asArray();
  13194. serializationObject.direction = directionalLight.direction.asArray();
  13195. } else if (light instanceof BABYLON.SpotLight) {
  13196. serializationObject.type = 2;
  13197. var spotLight = light;
  13198. serializationObject.position = spotLight.position.asArray();
  13199. serializationObject.direction = spotLight.position.asArray();
  13200. serializationObject.angle = spotLight.angle;
  13201. serializationObject.exponent = spotLight.exponent;
  13202. } else if (light instanceof BABYLON.HemisphericLight) {
  13203. serializationObject.type = 3;
  13204. var hemisphericLight = light;
  13205. serializationObject.direction = hemisphericLight.direction.asArray();
  13206. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13207. }
  13208. if (light.intensity) {
  13209. serializationObject.intensity = light.intensity;
  13210. }
  13211. serializationObject.range = light.range;
  13212. serializationObject.diffuse = light.diffuse.asArray();
  13213. serializationObject.specular = light.specular.asArray();
  13214. return serializationObject;
  13215. };
  13216. var serializeFresnelParameter = function (fresnelParameter) {
  13217. var serializationObject = {};
  13218. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13219. serializationObject.leftColor = fresnelParameter.leftColor;
  13220. serializationObject.rightColor = fresnelParameter.rightColor;
  13221. serializationObject.bias = fresnelParameter.bias;
  13222. serializationObject.power = fresnelParameter.power;
  13223. return serializationObject;
  13224. };
  13225. var serializeCamera = function (camera) {
  13226. var serializationObject = {};
  13227. serializationObject.name = camera.name;
  13228. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13229. serializationObject.id = camera.id;
  13230. serializationObject.position = camera.position.asArray();
  13231. if (camera.parent) {
  13232. serializationObject.parentId = camera.parent.id;
  13233. }
  13234. serializationObject.rotation = camera.rotation.asArray();
  13235. if (camera.lockedTarget && camera.lockedTarget.id) {
  13236. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13237. }
  13238. serializationObject.fov = camera.fov;
  13239. serializationObject.minZ = camera.minZ;
  13240. serializationObject.maxZ = camera.maxZ;
  13241. serializationObject.speed = camera.speed;
  13242. serializationObject.inertia = camera.inertia;
  13243. serializationObject.checkCollisions = camera.checkCollisions;
  13244. serializationObject.applyGravity = camera.applyGravity;
  13245. if (camera.ellipsoid) {
  13246. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13247. }
  13248. appendAnimations(camera, serializationObject);
  13249. serializationObject.layerMask = camera.layerMask;
  13250. return serializationObject;
  13251. };
  13252. var appendAnimations = function (source, destination) {
  13253. if (source.animations) {
  13254. destination.animations = [];
  13255. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13256. var animation = source.animations[animationIndex];
  13257. destination.animations.push(serializeAnimation(animation));
  13258. }
  13259. }
  13260. };
  13261. var serializeAnimation = function (animation) {
  13262. var serializationObject = {};
  13263. serializationObject.name = animation.name;
  13264. serializationObject.property = animation.targetProperty;
  13265. serializationObject.framePerSecond = animation.framePerSecond;
  13266. serializationObject.dataType = animation.dataType;
  13267. serializationObject.loopBehavior = animation.loopMode;
  13268. var dataType = animation.dataType;
  13269. serializationObject.keys = [];
  13270. var keys = animation.getKeys();
  13271. for (var index = 0; index < keys.length; index++) {
  13272. var animationKey = keys[index];
  13273. var key = {};
  13274. key.frame = animationKey.frame;
  13275. switch (dataType) {
  13276. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13277. key.values = [animationKey.value];
  13278. break;
  13279. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13280. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13281. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13282. key.values = animationKey.value.asArray();
  13283. break;
  13284. }
  13285. serializationObject.keys.push(key);
  13286. }
  13287. return serializationObject;
  13288. };
  13289. var serializeMultiMaterial = function (material) {
  13290. var serializationObject = {};
  13291. serializationObject.name = material.name;
  13292. serializationObject.id = material.id;
  13293. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13294. serializationObject.materials = [];
  13295. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13296. var subMat = material.subMaterials[matIndex];
  13297. if (subMat) {
  13298. serializationObject.materials.push(subMat.id);
  13299. } else {
  13300. serializationObject.materials.push(null);
  13301. }
  13302. }
  13303. return serializationObject;
  13304. };
  13305. var serializeMaterial = function (material) {
  13306. var serializationObject = {};
  13307. serializationObject.name = material.name;
  13308. serializationObject.ambient = material.ambientColor.asArray();
  13309. serializationObject.diffuse = material.diffuseColor.asArray();
  13310. serializationObject.specular = material.specularColor.asArray();
  13311. serializationObject.specularPower = material.specularPower;
  13312. serializationObject.emissive = material.emissiveColor.asArray();
  13313. serializationObject.alpha = material.alpha;
  13314. serializationObject.id = material.id;
  13315. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13316. serializationObject.backFaceCulling = material.backFaceCulling;
  13317. if (material.diffuseTexture) {
  13318. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13319. }
  13320. if (material.diffuseFresnelParameters) {
  13321. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13322. }
  13323. if (material.ambientTexture) {
  13324. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13325. }
  13326. if (material.opacityTexture) {
  13327. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13328. }
  13329. if (material.opacityFresnelParameters) {
  13330. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13331. }
  13332. if (material.reflectionTexture) {
  13333. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13334. }
  13335. if (material.reflectionFresnelParameters) {
  13336. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13337. }
  13338. if (material.emissiveTexture) {
  13339. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13340. }
  13341. if (material.emissiveFresnelParameters) {
  13342. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13343. }
  13344. if (material.specularTexture) {
  13345. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13346. }
  13347. if (material.bumpTexture) {
  13348. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13349. }
  13350. return serializationObject;
  13351. };
  13352. var serializeTexture = function (texture) {
  13353. var serializationObject = {};
  13354. if (!texture.name) {
  13355. return null;
  13356. }
  13357. if (texture instanceof BABYLON.CubeTexture) {
  13358. serializationObject.name = texture.name;
  13359. serializationObject.hasAlpha = texture.hasAlpha;
  13360. serializationObject.level = texture.level;
  13361. serializationObject.coordinatesMode = texture.coordinatesMode;
  13362. return serializationObject;
  13363. }
  13364. if (texture instanceof BABYLON.MirrorTexture) {
  13365. var mirrorTexture = texture;
  13366. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13367. serializationObject.renderList = [];
  13368. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13369. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13370. }
  13371. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13372. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13373. var renderTargetTexture = texture;
  13374. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13375. serializationObject.renderList = [];
  13376. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13377. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13378. }
  13379. }
  13380. var regularTexture = texture;
  13381. serializationObject.name = texture.name;
  13382. serializationObject.hasAlpha = texture.hasAlpha;
  13383. serializationObject.level = texture.level;
  13384. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13385. serializationObject.coordinatesMode = texture.coordinatesMode;
  13386. serializationObject.uOffset = regularTexture.uOffset;
  13387. serializationObject.vOffset = regularTexture.vOffset;
  13388. serializationObject.uScale = regularTexture.uScale;
  13389. serializationObject.vScale = regularTexture.vScale;
  13390. serializationObject.uAng = regularTexture.uAng;
  13391. serializationObject.vAng = regularTexture.vAng;
  13392. serializationObject.wAng = regularTexture.wAng;
  13393. serializationObject.wrapU = texture.wrapU;
  13394. serializationObject.wrapV = texture.wrapV;
  13395. appendAnimations(texture, serializationObject);
  13396. return serializationObject;
  13397. };
  13398. var serializeSkeleton = function (skeleton) {
  13399. var serializationObject = {};
  13400. serializationObject.name = skeleton.name;
  13401. serializationObject.id = skeleton.id;
  13402. serializationObject.bones = [];
  13403. for (var index = 0; index < skeleton.bones.length; index++) {
  13404. var bone = skeleton.bones[index];
  13405. var serializedBone = {
  13406. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13407. name: bone.name,
  13408. matrix: bone.getLocalMatrix().toArray()
  13409. };
  13410. serializationObject.bones.push(serializedBone);
  13411. if (bone.animations && bone.animations.length > 0) {
  13412. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13413. }
  13414. }
  13415. return serializationObject;
  13416. };
  13417. var serializeParticleSystem = function (particleSystem) {
  13418. var serializationObject = {};
  13419. serializationObject.emitterId = particleSystem.emitter.id;
  13420. serializationObject.capacity = particleSystem.getCapacity();
  13421. if (particleSystem.particleTexture) {
  13422. serializationObject.textureName = particleSystem.particleTexture.name;
  13423. }
  13424. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13425. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13426. serializationObject.minSize = particleSystem.minSize;
  13427. serializationObject.maxSize = particleSystem.maxSize;
  13428. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13429. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13430. serializationObject.emitRate = particleSystem.emitRate;
  13431. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13432. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13433. serializationObject.gravity = particleSystem.gravity.asArray();
  13434. serializationObject.direction1 = particleSystem.direction1.asArray();
  13435. serializationObject.direction2 = particleSystem.direction2.asArray();
  13436. serializationObject.color1 = particleSystem.color1.asArray();
  13437. serializationObject.color2 = particleSystem.color2.asArray();
  13438. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13439. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13440. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13441. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13442. serializationObject.blendMode = particleSystem.blendMode;
  13443. return serializationObject;
  13444. };
  13445. var serializeLensFlareSystem = function (lensFlareSystem) {
  13446. var serializationObject = {};
  13447. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13448. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13449. serializationObject.flares = [];
  13450. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13451. var flare = lensFlareSystem.lensFlares[index];
  13452. serializationObject.flares.push({
  13453. size: flare.size,
  13454. position: flare.position,
  13455. color: flare.color.asArray(),
  13456. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13457. });
  13458. }
  13459. return serializationObject;
  13460. };
  13461. var serializeShadowGenerator = function (light) {
  13462. var serializationObject = {};
  13463. var shadowGenerator = light.getShadowGenerator();
  13464. serializationObject.lightId = light.id;
  13465. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13466. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13467. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13468. serializationObject.renderList = [];
  13469. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13470. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13471. serializationObject.renderList.push(mesh.id);
  13472. }
  13473. return serializationObject;
  13474. };
  13475. var serializedGeometries = [];
  13476. var serializeGeometry = function (geometry, serializationGeometries) {
  13477. if (serializedGeometries[geometry.id]) {
  13478. return;
  13479. }
  13480. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13481. serializationGeometries.boxes.push(serializeBox(geometry));
  13482. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13483. serializationGeometries.spheres.push(serializeSphere(geometry));
  13484. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13485. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13486. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13487. serializationGeometries.toruses.push(serializeTorus(geometry));
  13488. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13489. serializationGeometries.grounds.push(serializeGround(geometry));
  13490. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13491. serializationGeometries.planes.push(serializePlane(geometry));
  13492. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13493. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13494. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13495. throw new Error("Unknow primitive type");
  13496. } else {
  13497. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13498. }
  13499. serializedGeometries[geometry.id] = true;
  13500. };
  13501. var serializeGeometryBase = function (geometry) {
  13502. var serializationObject = {};
  13503. serializationObject.id = geometry.id;
  13504. if (BABYLON.Tags.HasTags(geometry)) {
  13505. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13506. }
  13507. return serializationObject;
  13508. };
  13509. var serializeVertexData = function (vertexData) {
  13510. var serializationObject = serializeGeometryBase(vertexData);
  13511. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13512. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13513. }
  13514. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13515. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13516. }
  13517. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13518. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13519. }
  13520. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13521. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13522. }
  13523. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13524. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13525. }
  13526. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13527. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13528. serializationObject.matricesIndices._isExpanded = true;
  13529. }
  13530. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13531. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13532. }
  13533. serializationObject.indices = vertexData.getIndices();
  13534. return serializationObject;
  13535. };
  13536. var serializePrimitive = function (primitive) {
  13537. var serializationObject = serializeGeometryBase(primitive);
  13538. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13539. return serializationObject;
  13540. };
  13541. var serializeBox = function (box) {
  13542. var serializationObject = serializePrimitive(box);
  13543. serializationObject.size = box.size;
  13544. return serializationObject;
  13545. };
  13546. var serializeSphere = function (sphere) {
  13547. var serializationObject = serializePrimitive(sphere);
  13548. serializationObject.segments = sphere.segments;
  13549. serializationObject.diameter = sphere.diameter;
  13550. return serializationObject;
  13551. };
  13552. var serializeCylinder = function (cylinder) {
  13553. var serializationObject = serializePrimitive(cylinder);
  13554. serializationObject.height = cylinder.height;
  13555. serializationObject.diameterTop = cylinder.diameterTop;
  13556. serializationObject.diameterBottom = cylinder.diameterBottom;
  13557. serializationObject.tessellation = cylinder.tessellation;
  13558. return serializationObject;
  13559. };
  13560. var serializeTorus = function (torus) {
  13561. var serializationObject = serializePrimitive(torus);
  13562. serializationObject.diameter = torus.diameter;
  13563. serializationObject.thickness = torus.thickness;
  13564. serializationObject.tessellation = torus.tessellation;
  13565. return serializationObject;
  13566. };
  13567. var serializeGround = function (ground) {
  13568. var serializationObject = serializePrimitive(ground);
  13569. serializationObject.width = ground.width;
  13570. serializationObject.height = ground.height;
  13571. serializationObject.subdivisions = ground.subdivisions;
  13572. return serializationObject;
  13573. };
  13574. var serializePlane = function (plane) {
  13575. var serializationObject = serializePrimitive(plane);
  13576. serializationObject.size = plane.size;
  13577. return serializationObject;
  13578. };
  13579. var serializeTorusKnot = function (torusKnot) {
  13580. var serializationObject = serializePrimitive(torusKnot);
  13581. serializationObject.radius = torusKnot.radius;
  13582. serializationObject.tube = torusKnot.tube;
  13583. serializationObject.radialSegments = torusKnot.radialSegments;
  13584. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13585. serializationObject.p = torusKnot.p;
  13586. serializationObject.q = torusKnot.q;
  13587. return serializationObject;
  13588. };
  13589. var serializeMesh = function (mesh, serializationScene) {
  13590. var serializationObject = {};
  13591. serializationObject.name = mesh.name;
  13592. serializationObject.id = mesh.id;
  13593. if (BABYLON.Tags.HasTags(mesh)) {
  13594. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13595. }
  13596. serializationObject.position = mesh.position.asArray();
  13597. if (mesh.rotationQuaternion) {
  13598. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13599. } else if (mesh.rotation) {
  13600. serializationObject.rotation = mesh.rotation.asArray();
  13601. }
  13602. serializationObject.scaling = mesh.scaling.asArray();
  13603. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13604. serializationObject.isEnabled = mesh.isEnabled();
  13605. serializationObject.isVisible = mesh.isVisible;
  13606. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13607. serializationObject.pickable = mesh.isPickable;
  13608. serializationObject.receiveShadows = mesh.receiveShadows;
  13609. serializationObject.billboardMode = mesh.billboardMode;
  13610. serializationObject.visibility = mesh.visibility;
  13611. serializationObject.checkCollisions = mesh.checkCollisions;
  13612. if (mesh.parent) {
  13613. serializationObject.parentId = mesh.parent.id;
  13614. }
  13615. var geometry = mesh._geometry;
  13616. if (geometry) {
  13617. var geometryId = geometry.id;
  13618. serializationObject.geometryId = geometryId;
  13619. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13620. serializeGeometry(geometry, serializationScene.geometries);
  13621. }
  13622. serializationObject.subMeshes = [];
  13623. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13624. var subMesh = mesh.subMeshes[subIndex];
  13625. serializationObject.subMeshes.push({
  13626. materialIndex: subMesh.materialIndex,
  13627. verticesStart: subMesh.verticesStart,
  13628. verticesCount: subMesh.verticesCount,
  13629. indexStart: subMesh.indexStart,
  13630. indexCount: subMesh.indexCount
  13631. });
  13632. }
  13633. }
  13634. if (mesh.material) {
  13635. serializationObject.materialId = mesh.material.id;
  13636. } else {
  13637. mesh.material = null;
  13638. }
  13639. if (mesh.skeleton) {
  13640. serializationObject.skeletonId = mesh.skeleton.id;
  13641. }
  13642. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13643. serializationObject.physicsMass = mesh.getPhysicsMass();
  13644. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13645. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13646. switch (mesh.getPhysicsImpostor()) {
  13647. case BABYLON.PhysicsEngine.BoxImpostor:
  13648. serializationObject.physicsImpostor = 1;
  13649. break;
  13650. case BABYLON.PhysicsEngine.SphereImpostor:
  13651. serializationObject.physicsImpostor = 2;
  13652. break;
  13653. }
  13654. }
  13655. serializationObject.instances = [];
  13656. for (var index = 0; index < mesh.instances.length; index++) {
  13657. var instance = mesh.instances[index];
  13658. var serializationInstance = {
  13659. name: instance.name,
  13660. position: instance.position,
  13661. rotation: instance.rotation,
  13662. rotationQuaternion: instance.rotationQuaternion,
  13663. scaling: instance.scaling
  13664. };
  13665. serializationObject.instances.push(serializationInstance);
  13666. appendAnimations(instance, serializationInstance);
  13667. }
  13668. appendAnimations(mesh, serializationObject);
  13669. serializationObject.layerMask = mesh.layerMask;
  13670. return serializationObject;
  13671. };
  13672. var SceneSerializer = (function () {
  13673. function SceneSerializer() {
  13674. }
  13675. SceneSerializer.Serialize = function (scene) {
  13676. var serializationObject = {};
  13677. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13678. serializationObject.autoClear = scene.autoClear;
  13679. serializationObject.clearColor = scene.clearColor.asArray();
  13680. serializationObject.ambientColor = scene.ambientColor.asArray();
  13681. serializationObject.gravity = scene.gravity.asArray();
  13682. if (scene.fogMode && scene.fogMode !== 0) {
  13683. serializationObject.fogMode = scene.fogMode;
  13684. serializationObject.fogColor = scene.fogColor.asArray();
  13685. serializationObject.fogStart = scene.fogStart;
  13686. serializationObject.fogEnd = scene.fogEnd;
  13687. serializationObject.fogDensity = scene.fogDensity;
  13688. }
  13689. serializationObject.lights = [];
  13690. for (var index = 0; index < scene.lights.length; index++) {
  13691. var light = scene.lights[index];
  13692. serializationObject.lights.push(serializeLight(light));
  13693. }
  13694. serializationObject.cameras = [];
  13695. for (index = 0; index < scene.cameras.length; index++) {
  13696. var camera = scene.cameras[index];
  13697. if (camera instanceof BABYLON.FreeCamera) {
  13698. serializationObject.cameras.push(serializeCamera(camera));
  13699. }
  13700. }
  13701. if (scene.activeCamera) {
  13702. serializationObject.activeCameraID = scene.activeCamera.id;
  13703. }
  13704. serializationObject.materials = [];
  13705. serializationObject.multiMaterials = [];
  13706. for (index = 0; index < scene.materials.length; index++) {
  13707. var material = scene.materials[index];
  13708. if (material instanceof BABYLON.StandardMaterial) {
  13709. serializationObject.materials.push(serializeMaterial(material));
  13710. } else if (material instanceof BABYLON.MultiMaterial) {
  13711. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13712. }
  13713. }
  13714. serializationObject.skeletons = [];
  13715. for (index = 0; index < scene.skeletons.length; index++) {
  13716. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13717. }
  13718. serializationObject.geometries = {};
  13719. serializationObject.geometries.boxes = [];
  13720. serializationObject.geometries.spheres = [];
  13721. serializationObject.geometries.cylinders = [];
  13722. serializationObject.geometries.toruses = [];
  13723. serializationObject.geometries.grounds = [];
  13724. serializationObject.geometries.planes = [];
  13725. serializationObject.geometries.torusKnots = [];
  13726. serializationObject.geometries.vertexData = [];
  13727. serializedGeometries = [];
  13728. var geometries = scene.getGeometries();
  13729. for (var index = 0; index < geometries.length; index++) {
  13730. var geometry = geometries[index];
  13731. if (geometry.isReady()) {
  13732. serializeGeometry(geometry, serializationObject.geometries);
  13733. }
  13734. }
  13735. serializationObject.meshes = [];
  13736. for (index = 0; index < scene.meshes.length; index++) {
  13737. var abstractMesh = scene.meshes[index];
  13738. if (abstractMesh instanceof BABYLON.Mesh) {
  13739. var mesh = abstractMesh;
  13740. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13741. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13742. }
  13743. }
  13744. }
  13745. serializationObject.particleSystems = [];
  13746. for (index = 0; index < scene.particleSystems.length; index++) {
  13747. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13748. }
  13749. serializationObject.lensFlareSystems = [];
  13750. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13751. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13752. }
  13753. serializationObject.shadowGenerators = [];
  13754. for (index = 0; index < scene.lights.length; index++) {
  13755. light = scene.lights[index];
  13756. if (light.getShadowGenerator()) {
  13757. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13758. }
  13759. }
  13760. return serializationObject;
  13761. };
  13762. return SceneSerializer;
  13763. })();
  13764. BABYLON.SceneSerializer = SceneSerializer;
  13765. })(BABYLON || (BABYLON = {}));
  13766. var BABYLON;
  13767. (function (BABYLON) {
  13768. var SceneLoader = (function () {
  13769. function SceneLoader() {
  13770. }
  13771. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13772. get: function () {
  13773. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13774. },
  13775. set: function (value) {
  13776. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13777. },
  13778. enumerable: true,
  13779. configurable: true
  13780. });
  13781. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13782. get: function () {
  13783. return SceneLoader._ShowLoadingScreen;
  13784. },
  13785. set: function (value) {
  13786. SceneLoader._ShowLoadingScreen = value;
  13787. },
  13788. enumerable: true,
  13789. configurable: true
  13790. });
  13791. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13792. var dotPosition = sceneFilename.lastIndexOf(".");
  13793. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13794. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13795. var plugin = this._registeredPlugins[index];
  13796. if (plugin.extensions.indexOf(extension) !== -1) {
  13797. return plugin;
  13798. }
  13799. }
  13800. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13801. };
  13802. SceneLoader.RegisterPlugin = function (plugin) {
  13803. plugin.extensions = plugin.extensions.toLowerCase();
  13804. SceneLoader._registeredPlugins.push(plugin);
  13805. };
  13806. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13807. var _this = this;
  13808. var manifestChecked = function (success) {
  13809. scene.database = database;
  13810. var plugin = _this._getPluginForFilename(sceneFilename);
  13811. var importMeshFromData = function (data) {
  13812. var meshes = [];
  13813. var particleSystems = [];
  13814. var skeletons = [];
  13815. try {
  13816. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13817. if (onerror) {
  13818. onerror(scene);
  13819. }
  13820. return;
  13821. }
  13822. } catch (e) {
  13823. if (onerror) {
  13824. onerror(scene);
  13825. }
  13826. return;
  13827. }
  13828. if (onsuccess) {
  13829. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13830. onsuccess(meshes, particleSystems, skeletons);
  13831. }
  13832. };
  13833. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13834. importMeshFromData(sceneFilename.substr(5));
  13835. return;
  13836. }
  13837. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13838. importMeshFromData(data);
  13839. }, progressCallBack, database);
  13840. };
  13841. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13842. };
  13843. /**
  13844. * Load a scene
  13845. * @param rootUrl a string that defines the root url for scene and resources
  13846. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13847. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13848. */
  13849. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13850. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13851. };
  13852. /**
  13853. * Append a scene
  13854. * @param rootUrl a string that defines the root url for scene and resources
  13855. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13856. * @param scene is the instance of BABYLON.Scene to append to
  13857. */
  13858. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13859. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13860. var database;
  13861. if (SceneLoader.ShowLoadingScreen) {
  13862. scene.getEngine().displayLoadingUI();
  13863. }
  13864. var loadSceneFromData = function (data) {
  13865. scene.database = database;
  13866. if (!plugin.load(scene, data, rootUrl)) {
  13867. if (onerror) {
  13868. onerror(scene);
  13869. }
  13870. scene.getEngine().hideLoadingUI();
  13871. return;
  13872. }
  13873. if (onsuccess) {
  13874. onsuccess(scene);
  13875. }
  13876. if (SceneLoader.ShowLoadingScreen) {
  13877. scene.executeWhenReady(function () {
  13878. scene.getEngine().hideLoadingUI();
  13879. });
  13880. }
  13881. };
  13882. var manifestChecked = function (success) {
  13883. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13884. };
  13885. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13886. loadSceneFromData(sceneFilename.substr(5));
  13887. return;
  13888. }
  13889. if (rootUrl.indexOf("file:") === -1) {
  13890. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13891. } else {
  13892. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13893. }
  13894. };
  13895. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13896. SceneLoader._ShowLoadingScreen = true;
  13897. SceneLoader._registeredPlugins = new Array();
  13898. return SceneLoader;
  13899. })();
  13900. BABYLON.SceneLoader = SceneLoader;
  13901. ;
  13902. })(BABYLON || (BABYLON = {}));
  13903. var BABYLON;
  13904. (function (BABYLON) {
  13905. (function (Internals) {
  13906. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13907. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13908. texture.name = parsedTexture.name;
  13909. texture.hasAlpha = parsedTexture.hasAlpha;
  13910. texture.level = parsedTexture.level;
  13911. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13912. return texture;
  13913. };
  13914. var loadTexture = function (rootUrl, parsedTexture, scene) {
  13915. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  13916. return null;
  13917. }
  13918. if (parsedTexture.isCube) {
  13919. return loadCubeTexture(rootUrl, parsedTexture, scene);
  13920. }
  13921. var texture;
  13922. if (parsedTexture.mirrorPlane) {
  13923. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13924. texture._waitingRenderList = parsedTexture.renderList;
  13925. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  13926. } else if (parsedTexture.isRenderTarget) {
  13927. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13928. texture._waitingRenderList = parsedTexture.renderList;
  13929. } else {
  13930. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  13931. }
  13932. texture.name = parsedTexture.name;
  13933. texture.hasAlpha = parsedTexture.hasAlpha;
  13934. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  13935. texture.level = parsedTexture.level;
  13936. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  13937. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13938. texture.uOffset = parsedTexture.uOffset;
  13939. texture.vOffset = parsedTexture.vOffset;
  13940. texture.uScale = parsedTexture.uScale;
  13941. texture.vScale = parsedTexture.vScale;
  13942. texture.uAng = parsedTexture.uAng;
  13943. texture.vAng = parsedTexture.vAng;
  13944. texture.wAng = parsedTexture.wAng;
  13945. texture.wrapU = parsedTexture.wrapU;
  13946. texture.wrapV = parsedTexture.wrapV;
  13947. if (parsedTexture.animations) {
  13948. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  13949. var parsedAnimation = parsedTexture.animations[animationIndex];
  13950. texture.animations.push(parseAnimation(parsedAnimation));
  13951. }
  13952. }
  13953. return texture;
  13954. };
  13955. var parseSkeleton = function (parsedSkeleton, scene) {
  13956. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  13957. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  13958. var parsedBone = parsedSkeleton.bones[index];
  13959. var parentBone = null;
  13960. if (parsedBone.parentBoneIndex > -1) {
  13961. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  13962. }
  13963. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  13964. if (parsedBone.animation) {
  13965. bone.animations.push(parseAnimation(parsedBone.animation));
  13966. }
  13967. }
  13968. return skeleton;
  13969. };
  13970. var parseFresnelParameters = function (parsedFresnelParameters) {
  13971. var fresnelParameters = new BABYLON.FresnelParameters();
  13972. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  13973. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  13974. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  13975. fresnelParameters.bias = parsedFresnelParameters.bias;
  13976. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  13977. return fresnelParameters;
  13978. };
  13979. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  13980. var material;
  13981. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  13982. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  13983. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  13984. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  13985. material.specularPower = parsedMaterial.specularPower;
  13986. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  13987. material.alpha = parsedMaterial.alpha;
  13988. material.id = parsedMaterial.id;
  13989. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  13990. material.backFaceCulling = parsedMaterial.backFaceCulling;
  13991. material.wireframe = parsedMaterial.wireframe;
  13992. if (parsedMaterial.diffuseTexture) {
  13993. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  13994. }
  13995. if (parsedMaterial.diffuseFresnelParameters) {
  13996. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  13997. }
  13998. if (parsedMaterial.ambientTexture) {
  13999. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14000. }
  14001. if (parsedMaterial.opacityTexture) {
  14002. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14003. }
  14004. if (parsedMaterial.opacityFresnelParameters) {
  14005. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14006. }
  14007. if (parsedMaterial.reflectionTexture) {
  14008. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14009. }
  14010. if (parsedMaterial.reflectionFresnelParameters) {
  14011. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14012. }
  14013. if (parsedMaterial.emissiveTexture) {
  14014. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14015. }
  14016. if (parsedMaterial.emissiveFresnelParameters) {
  14017. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14018. }
  14019. if (parsedMaterial.specularTexture) {
  14020. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14021. }
  14022. if (parsedMaterial.bumpTexture) {
  14023. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14024. }
  14025. return material;
  14026. };
  14027. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14028. for (var index = 0; index < parsedData.materials.length; index++) {
  14029. var parsedMaterial = parsedData.materials[index];
  14030. if (parsedMaterial.id === id) {
  14031. return parseMaterial(parsedMaterial, scene, rootUrl);
  14032. }
  14033. }
  14034. return null;
  14035. };
  14036. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14037. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14038. multiMaterial.id = parsedMultiMaterial.id;
  14039. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14040. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14041. var subMatId = parsedMultiMaterial.materials[matIndex];
  14042. if (subMatId) {
  14043. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14044. } else {
  14045. multiMaterial.subMaterials.push(null);
  14046. }
  14047. }
  14048. return multiMaterial;
  14049. };
  14050. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14051. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14052. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14053. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14054. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14055. var parsedFlare = parsedLensFlareSystem.flares[index];
  14056. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14057. }
  14058. return lensFlareSystem;
  14059. };
  14060. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14061. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14062. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14063. if (parsedParticleSystem.textureName) {
  14064. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14065. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14066. }
  14067. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14068. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14069. particleSystem.minSize = parsedParticleSystem.minSize;
  14070. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14071. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14072. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14073. particleSystem.emitter = emitter;
  14074. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14075. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14076. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14077. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14078. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14079. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14080. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14081. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14082. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14083. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14084. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14085. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14086. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14087. particleSystem.start();
  14088. return particleSystem;
  14089. };
  14090. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14091. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14092. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14093. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14094. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14095. shadowGenerator.getShadowMap().renderList.push(mesh);
  14096. }
  14097. if (parsedShadowGenerator.usePoissonSampling) {
  14098. shadowGenerator.usePoissonSampling = true;
  14099. } else {
  14100. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14101. }
  14102. return shadowGenerator;
  14103. };
  14104. var parseAnimation = function (parsedAnimation) {
  14105. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14106. var dataType = parsedAnimation.dataType;
  14107. var keys = [];
  14108. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14109. var key = parsedAnimation.keys[index];
  14110. var data;
  14111. switch (dataType) {
  14112. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14113. data = key.values[0];
  14114. break;
  14115. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14116. data = BABYLON.Quaternion.FromArray(key.values);
  14117. break;
  14118. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14119. data = BABYLON.Matrix.FromArray(key.values);
  14120. break;
  14121. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14122. default:
  14123. data = BABYLON.Vector3.FromArray(key.values);
  14124. break;
  14125. }
  14126. keys.push({
  14127. frame: key.frame,
  14128. value: data
  14129. });
  14130. }
  14131. animation.setKeys(keys);
  14132. return animation;
  14133. };
  14134. var parseLight = function (parsedLight, scene) {
  14135. var light;
  14136. switch (parsedLight.type) {
  14137. case 0:
  14138. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14139. break;
  14140. case 1:
  14141. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14142. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14143. break;
  14144. case 2:
  14145. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14146. break;
  14147. case 3:
  14148. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14149. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14150. break;
  14151. }
  14152. light.id = parsedLight.id;
  14153. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14154. if (parsedLight.intensity !== undefined) {
  14155. light.intensity = parsedLight.intensity;
  14156. }
  14157. if (parsedLight.range) {
  14158. light.range = parsedLight.range;
  14159. }
  14160. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14161. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14162. if (parsedLight.excludedMeshesIds) {
  14163. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14164. }
  14165. if (parsedLight.includedOnlyMeshesIds) {
  14166. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14167. }
  14168. if (parsedLight.animations) {
  14169. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14170. var parsedAnimation = parsedLight.animations[animationIndex];
  14171. light.animations.push(parseAnimation(parsedAnimation));
  14172. }
  14173. }
  14174. if (parsedLight.autoAnimate) {
  14175. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14176. }
  14177. };
  14178. var parseCamera = function (parsedCamera, scene) {
  14179. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14180. camera.id = parsedCamera.id;
  14181. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14182. if (parsedCamera.parentId) {
  14183. camera._waitingParentId = parsedCamera.parentId;
  14184. }
  14185. if (parsedCamera.target) {
  14186. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14187. } else {
  14188. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14189. }
  14190. if (parsedCamera.lockedTargetId) {
  14191. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14192. }
  14193. camera.fov = parsedCamera.fov;
  14194. camera.minZ = parsedCamera.minZ;
  14195. camera.maxZ = parsedCamera.maxZ;
  14196. camera.speed = parsedCamera.speed;
  14197. camera.inertia = parsedCamera.inertia;
  14198. camera.checkCollisions = parsedCamera.checkCollisions;
  14199. camera.applyGravity = parsedCamera.applyGravity;
  14200. if (parsedCamera.ellipsoid) {
  14201. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14202. }
  14203. if (parsedCamera.animations) {
  14204. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14205. var parsedAnimation = parsedCamera.animations[animationIndex];
  14206. camera.animations.push(parseAnimation(parsedAnimation));
  14207. }
  14208. }
  14209. if (parsedCamera.autoAnimate) {
  14210. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14211. }
  14212. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14213. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14214. } else {
  14215. camera.layerMask = 0xFFFFFFFF;
  14216. }
  14217. return camera;
  14218. };
  14219. var parseGeometry = function (parsedGeometry, scene) {
  14220. var id = parsedGeometry.id;
  14221. return scene.getGeometryByID(id);
  14222. };
  14223. var parseBox = function (parsedBox, scene) {
  14224. if (parseGeometry(parsedBox, scene)) {
  14225. return null;
  14226. }
  14227. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14228. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14229. scene.pushGeometry(box, true);
  14230. return box;
  14231. };
  14232. var parseSphere = function (parsedSphere, scene) {
  14233. if (parseGeometry(parsedSphere, scene)) {
  14234. return null;
  14235. }
  14236. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14237. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14238. scene.pushGeometry(sphere, true);
  14239. return sphere;
  14240. };
  14241. var parseCylinder = function (parsedCylinder, scene) {
  14242. if (parseGeometry(parsedCylinder, scene)) {
  14243. return null;
  14244. }
  14245. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14246. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14247. scene.pushGeometry(cylinder, true);
  14248. return cylinder;
  14249. };
  14250. var parseTorus = function (parsedTorus, scene) {
  14251. if (parseGeometry(parsedTorus, scene)) {
  14252. return null;
  14253. }
  14254. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14255. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14256. scene.pushGeometry(torus, true);
  14257. return torus;
  14258. };
  14259. var parseGround = function (parsedGround, scene) {
  14260. if (parseGeometry(parsedGround, scene)) {
  14261. return null;
  14262. }
  14263. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14264. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14265. scene.pushGeometry(ground, true);
  14266. return ground;
  14267. };
  14268. var parsePlane = function (parsedPlane, scene) {
  14269. if (parseGeometry(parsedPlane, scene)) {
  14270. return null;
  14271. }
  14272. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14273. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14274. scene.pushGeometry(plane, true);
  14275. return plane;
  14276. };
  14277. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14278. if (parseGeometry(parsedTorusKnot, scene)) {
  14279. return null;
  14280. }
  14281. 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);
  14282. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14283. scene.pushGeometry(torusKnot, true);
  14284. return torusKnot;
  14285. };
  14286. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14287. if (parseGeometry(parsedVertexData, scene)) {
  14288. return null;
  14289. }
  14290. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14291. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14292. if (parsedVertexData.delayLoadingFile) {
  14293. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14294. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14295. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14296. geometry._delayInfo = [];
  14297. if (parsedVertexData.hasUVs) {
  14298. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14299. }
  14300. if (parsedVertexData.hasUVs2) {
  14301. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14302. }
  14303. if (parsedVertexData.hasColors) {
  14304. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14305. }
  14306. if (parsedVertexData.hasMatricesIndices) {
  14307. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14308. }
  14309. if (parsedVertexData.hasMatricesWeights) {
  14310. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14311. }
  14312. geometry._delayLoadingFunction = importVertexData;
  14313. } else {
  14314. importVertexData(parsedVertexData, geometry);
  14315. }
  14316. scene.pushGeometry(geometry, true);
  14317. return geometry;
  14318. };
  14319. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14320. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14321. mesh.id = parsedMesh.id;
  14322. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14323. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14324. if (parsedMesh.rotationQuaternion) {
  14325. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14326. } else if (parsedMesh.rotation) {
  14327. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14328. }
  14329. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14330. if (parsedMesh.localMatrix) {
  14331. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14332. } else if (parsedMesh.pivotMatrix) {
  14333. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14334. }
  14335. mesh.setEnabled(parsedMesh.isEnabled);
  14336. mesh.isVisible = parsedMesh.isVisible;
  14337. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14338. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14339. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14340. if (parsedMesh.pickable !== undefined) {
  14341. mesh.isPickable = parsedMesh.pickable;
  14342. }
  14343. mesh.receiveShadows = parsedMesh.receiveShadows;
  14344. mesh.billboardMode = parsedMesh.billboardMode;
  14345. if (parsedMesh.visibility !== undefined) {
  14346. mesh.visibility = parsedMesh.visibility;
  14347. }
  14348. mesh.checkCollisions = parsedMesh.checkCollisions;
  14349. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14350. if (parsedMesh.parentId) {
  14351. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14352. }
  14353. if (parsedMesh.delayLoadingFile) {
  14354. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14355. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14356. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14357. mesh._delayInfo = [];
  14358. if (parsedMesh.hasUVs) {
  14359. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14360. }
  14361. if (parsedMesh.hasUVs2) {
  14362. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14363. }
  14364. if (parsedMesh.hasColors) {
  14365. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14366. }
  14367. if (parsedMesh.hasMatricesIndices) {
  14368. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14369. }
  14370. if (parsedMesh.hasMatricesWeights) {
  14371. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14372. }
  14373. mesh._delayLoadingFunction = importGeometry;
  14374. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14375. mesh._checkDelayState();
  14376. }
  14377. } else {
  14378. importGeometry(parsedMesh, mesh);
  14379. }
  14380. if (parsedMesh.materialId) {
  14381. mesh.setMaterialByID(parsedMesh.materialId);
  14382. } else {
  14383. mesh.material = null;
  14384. }
  14385. if (parsedMesh.skeletonId > -1) {
  14386. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14387. }
  14388. if (parsedMesh.physicsImpostor) {
  14389. if (!scene.isPhysicsEnabled()) {
  14390. scene.enablePhysics();
  14391. }
  14392. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14393. }
  14394. if (parsedMesh.animations) {
  14395. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14396. var parsedAnimation = parsedMesh.animations[animationIndex];
  14397. mesh.animations.push(parseAnimation(parsedAnimation));
  14398. }
  14399. }
  14400. if (parsedMesh.autoAnimate) {
  14401. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14402. }
  14403. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14404. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14405. } else {
  14406. mesh.layerMask = 0xFFFFFFFF;
  14407. }
  14408. if (parsedMesh.instances) {
  14409. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14410. var parsedInstance = parsedMesh.instances[index];
  14411. var instance = mesh.createInstance(parsedInstance.name);
  14412. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14413. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14414. if (parsedInstance.rotationQuaternion) {
  14415. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14416. } else if (parsedInstance.rotation) {
  14417. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14418. }
  14419. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14420. instance.checkCollisions = mesh.checkCollisions;
  14421. if (parsedMesh.animations) {
  14422. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14423. parsedAnimation = parsedMesh.animations[animationIndex];
  14424. instance.animations.push(parseAnimation(parsedAnimation));
  14425. }
  14426. }
  14427. }
  14428. }
  14429. return mesh;
  14430. };
  14431. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14432. names = (names instanceof Array) ? names : [names];
  14433. for (var i in names) {
  14434. if (mesh.name === names[i]) {
  14435. hierarchyIds.push(mesh.id);
  14436. return true;
  14437. }
  14438. }
  14439. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14440. hierarchyIds.push(mesh.id);
  14441. return true;
  14442. }
  14443. return false;
  14444. };
  14445. var importVertexData = function (parsedVertexData, geometry) {
  14446. var vertexData = new BABYLON.VertexData();
  14447. var positions = parsedVertexData.positions;
  14448. if (positions) {
  14449. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14450. }
  14451. var normals = parsedVertexData.normals;
  14452. if (normals) {
  14453. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14454. }
  14455. var uvs = parsedVertexData.uvs;
  14456. if (uvs) {
  14457. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14458. }
  14459. var uv2s = parsedVertexData.uv2s;
  14460. if (uv2s) {
  14461. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14462. }
  14463. var colors = parsedVertexData.colors;
  14464. if (colors) {
  14465. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14466. }
  14467. var matricesIndices = parsedVertexData.matricesIndices;
  14468. if (matricesIndices) {
  14469. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14470. }
  14471. var matricesWeights = parsedVertexData.matricesWeights;
  14472. if (matricesWeights) {
  14473. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14474. }
  14475. var indices = parsedVertexData.indices;
  14476. if (indices) {
  14477. vertexData.indices = indices;
  14478. }
  14479. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14480. };
  14481. var importGeometry = function (parsedGeometry, mesh) {
  14482. var scene = mesh.getScene();
  14483. var geometryId = parsedGeometry.geometryId;
  14484. if (geometryId) {
  14485. var geometry = scene.getGeometryByID(geometryId);
  14486. if (geometry) {
  14487. geometry.applyToMesh(mesh);
  14488. }
  14489. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14490. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14491. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14492. if (parsedGeometry.uvs) {
  14493. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14494. }
  14495. if (parsedGeometry.uvs2) {
  14496. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14497. }
  14498. if (parsedGeometry.colors) {
  14499. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14500. }
  14501. if (parsedGeometry.matricesIndices) {
  14502. if (!parsedGeometry.matricesIndices._isExpanded) {
  14503. var floatIndices = [];
  14504. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14505. var matricesIndex = parsedGeometry.matricesIndices[i];
  14506. floatIndices.push(matricesIndex & 0x000000FF);
  14507. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14508. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14509. floatIndices.push(matricesIndex >> 24);
  14510. }
  14511. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14512. } else {
  14513. delete parsedGeometry.matricesIndices._isExpanded;
  14514. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14515. }
  14516. }
  14517. if (parsedGeometry.matricesWeights) {
  14518. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14519. }
  14520. mesh.setIndices(parsedGeometry.indices);
  14521. }
  14522. if (parsedGeometry.subMeshes) {
  14523. mesh.subMeshes = [];
  14524. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14525. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14526. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14527. }
  14528. }
  14529. if (mesh._shouldGenerateFlatShading) {
  14530. mesh.convertToFlatShadedMesh();
  14531. delete mesh._shouldGenerateFlatShading;
  14532. }
  14533. mesh.computeWorldMatrix(true);
  14534. if (scene._selectionOctree) {
  14535. scene._selectionOctree.addMesh(mesh);
  14536. }
  14537. };
  14538. BABYLON.SceneLoader.RegisterPlugin({
  14539. extensions: ".babylon",
  14540. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14541. var parsedData = JSON.parse(data);
  14542. var loadedSkeletonsIds = [];
  14543. var loadedMaterialsIds = [];
  14544. var hierarchyIds = [];
  14545. for (var index = 0; index < parsedData.meshes.length; index++) {
  14546. var parsedMesh = parsedData.meshes[index];
  14547. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14548. if (meshesNames instanceof Array) {
  14549. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14550. }
  14551. if (parsedMesh.materialId) {
  14552. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14553. if (!materialFound) {
  14554. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14555. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14556. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14557. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14558. var subMatId = parsedMultiMaterial.materials[matIndex];
  14559. loadedMaterialsIds.push(subMatId);
  14560. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14561. }
  14562. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14563. parseMultiMaterial(parsedMultiMaterial, scene);
  14564. materialFound = true;
  14565. break;
  14566. }
  14567. }
  14568. }
  14569. if (!materialFound) {
  14570. loadedMaterialsIds.push(parsedMesh.materialId);
  14571. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14572. }
  14573. }
  14574. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14575. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14576. if (!skeletonAlreadyLoaded) {
  14577. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14578. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14579. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14580. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14581. loadedSkeletonsIds.push(parsedSkeleton.id);
  14582. }
  14583. }
  14584. }
  14585. }
  14586. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14587. meshes.push(mesh);
  14588. }
  14589. }
  14590. if (parsedData.particleSystems) {
  14591. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14592. var parsedParticleSystem = parsedData.particleSystems[index];
  14593. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14594. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14595. }
  14596. }
  14597. }
  14598. return true;
  14599. },
  14600. load: function (scene, data, rootUrl) {
  14601. var parsedData = JSON.parse(data);
  14602. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14603. scene.autoClear = parsedData.autoClear;
  14604. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14605. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14606. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14607. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14608. scene.fogMode = parsedData.fogMode;
  14609. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14610. scene.fogStart = parsedData.fogStart;
  14611. scene.fogEnd = parsedData.fogEnd;
  14612. scene.fogDensity = parsedData.fogDensity;
  14613. }
  14614. for (var index = 0; index < parsedData.lights.length; index++) {
  14615. var parsedLight = parsedData.lights[index];
  14616. parseLight(parsedLight, scene);
  14617. }
  14618. for (index = 0; index < parsedData.cameras.length; index++) {
  14619. var parsedCamera = parsedData.cameras[index];
  14620. parseCamera(parsedCamera, scene);
  14621. }
  14622. if (parsedData.activeCameraID) {
  14623. scene.setActiveCameraByID(parsedData.activeCameraID);
  14624. }
  14625. if (parsedData.materials) {
  14626. for (index = 0; index < parsedData.materials.length; index++) {
  14627. var parsedMaterial = parsedData.materials[index];
  14628. parseMaterial(parsedMaterial, scene, rootUrl);
  14629. }
  14630. }
  14631. if (parsedData.multiMaterials) {
  14632. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14633. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14634. parseMultiMaterial(parsedMultiMaterial, scene);
  14635. }
  14636. }
  14637. if (parsedData.skeletons) {
  14638. for (index = 0; index < parsedData.skeletons.length; index++) {
  14639. var parsedSkeleton = parsedData.skeletons[index];
  14640. parseSkeleton(parsedSkeleton, scene);
  14641. }
  14642. }
  14643. var geometries = parsedData.geometries;
  14644. if (geometries) {
  14645. var boxes = geometries.boxes;
  14646. if (boxes) {
  14647. for (index = 0; index < boxes.length; index++) {
  14648. var parsedBox = boxes[index];
  14649. parseBox(parsedBox, scene);
  14650. }
  14651. }
  14652. var spheres = geometries.spheres;
  14653. if (spheres) {
  14654. for (index = 0; index < spheres.length; index++) {
  14655. var parsedSphere = spheres[index];
  14656. parseSphere(parsedSphere, scene);
  14657. }
  14658. }
  14659. var cylinders = geometries.cylinders;
  14660. if (cylinders) {
  14661. for (index = 0; index < cylinders.length; index++) {
  14662. var parsedCylinder = cylinders[index];
  14663. parseCylinder(parsedCylinder, scene);
  14664. }
  14665. }
  14666. var toruses = geometries.toruses;
  14667. if (toruses) {
  14668. for (index = 0; index < toruses.length; index++) {
  14669. var parsedTorus = toruses[index];
  14670. parseTorus(parsedTorus, scene);
  14671. }
  14672. }
  14673. var grounds = geometries.grounds;
  14674. if (grounds) {
  14675. for (index = 0; index < grounds.length; index++) {
  14676. var parsedGround = grounds[index];
  14677. parseGround(parsedGround, scene);
  14678. }
  14679. }
  14680. var planes = geometries.planes;
  14681. if (planes) {
  14682. for (index = 0; index < planes.length; index++) {
  14683. var parsedPlane = planes[index];
  14684. parsePlane(parsedPlane, scene);
  14685. }
  14686. }
  14687. var torusKnots = geometries.torusKnots;
  14688. if (torusKnots) {
  14689. for (index = 0; index < torusKnots.length; index++) {
  14690. var parsedTorusKnot = torusKnots[index];
  14691. parseTorusKnot(parsedTorusKnot, scene);
  14692. }
  14693. }
  14694. var vertexData = geometries.vertexData;
  14695. if (vertexData) {
  14696. for (index = 0; index < vertexData.length; index++) {
  14697. var parsedVertexData = vertexData[index];
  14698. parseVertexData(parsedVertexData, scene, rootUrl);
  14699. }
  14700. }
  14701. }
  14702. for (index = 0; index < parsedData.meshes.length; index++) {
  14703. var parsedMesh = parsedData.meshes[index];
  14704. parseMesh(parsedMesh, scene, rootUrl);
  14705. }
  14706. for (index = 0; index < scene.cameras.length; index++) {
  14707. var camera = scene.cameras[index];
  14708. if (camera._waitingParentId) {
  14709. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14710. delete camera._waitingParentId;
  14711. }
  14712. if (camera instanceof BABYLON.FreeCamera) {
  14713. var freecamera = camera;
  14714. if (freecamera._waitingLockedTargetId) {
  14715. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14716. delete freecamera._waitingLockedTargetId;
  14717. }
  14718. }
  14719. }
  14720. if (parsedData.particleSystems) {
  14721. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14722. var parsedParticleSystem = parsedData.particleSystems[index];
  14723. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14724. }
  14725. }
  14726. if (parsedData.lensFlareSystems) {
  14727. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14728. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14729. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14730. }
  14731. }
  14732. if (parsedData.shadowGenerators) {
  14733. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14734. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14735. parseShadowGenerator(parsedShadowGenerator, scene);
  14736. }
  14737. }
  14738. return true;
  14739. }
  14740. });
  14741. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14742. var Internals = BABYLON.Internals;
  14743. })(BABYLON || (BABYLON = {}));
  14744. var BABYLON;
  14745. (function (BABYLON) {
  14746. var currentCSGMeshId = 0;
  14747. var Vertex = (function () {
  14748. function Vertex(pos, normal, uv) {
  14749. this.pos = pos;
  14750. this.normal = normal;
  14751. this.uv = uv;
  14752. }
  14753. Vertex.prototype.clone = function () {
  14754. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14755. };
  14756. Vertex.prototype.flip = function () {
  14757. this.normal = this.normal.scale(-1);
  14758. };
  14759. Vertex.prototype.interpolate = function (other, t) {
  14760. 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));
  14761. };
  14762. return Vertex;
  14763. })();
  14764. var Plane = (function () {
  14765. function Plane(normal, w) {
  14766. this.normal = normal;
  14767. this.w = w;
  14768. }
  14769. Plane.FromPoints = function (a, b, c) {
  14770. var v0 = c.subtract(a);
  14771. var v1 = b.subtract(a);
  14772. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14773. return null;
  14774. }
  14775. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14776. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14777. };
  14778. Plane.prototype.clone = function () {
  14779. return new Plane(this.normal.clone(), this.w);
  14780. };
  14781. Plane.prototype.flip = function () {
  14782. this.normal.scaleInPlace(-1);
  14783. this.w = -this.w;
  14784. };
  14785. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14786. var COPLANAR = 0;
  14787. var FRONT = 1;
  14788. var BACK = 2;
  14789. var SPANNING = 3;
  14790. var polygonType = 0;
  14791. var types = [];
  14792. for (var i = 0; i < polygon.vertices.length; i++) {
  14793. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14794. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14795. polygonType |= type;
  14796. types.push(type);
  14797. }
  14798. switch (polygonType) {
  14799. case COPLANAR:
  14800. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14801. break;
  14802. case FRONT:
  14803. front.push(polygon);
  14804. break;
  14805. case BACK:
  14806. back.push(polygon);
  14807. break;
  14808. case SPANNING:
  14809. var f = [], b = [];
  14810. for (i = 0; i < polygon.vertices.length; i++) {
  14811. var j = (i + 1) % polygon.vertices.length;
  14812. var ti = types[i], tj = types[j];
  14813. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14814. if (ti != BACK)
  14815. f.push(vi);
  14816. if (ti != FRONT)
  14817. b.push(ti != BACK ? vi.clone() : vi);
  14818. if ((ti | tj) == SPANNING) {
  14819. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14820. var v = vi.interpolate(vj, t);
  14821. f.push(v);
  14822. b.push(v.clone());
  14823. }
  14824. }
  14825. if (f.length >= 3) {
  14826. var poly = new Polygon(f, polygon.shared);
  14827. if (poly.plane)
  14828. front.push(poly);
  14829. }
  14830. if (b.length >= 3) {
  14831. poly = new Polygon(b, polygon.shared);
  14832. if (poly.plane)
  14833. back.push(poly);
  14834. }
  14835. break;
  14836. }
  14837. };
  14838. Plane.EPSILON = 1e-5;
  14839. return Plane;
  14840. })();
  14841. var Polygon = (function () {
  14842. function Polygon(vertices, shared) {
  14843. this.vertices = vertices;
  14844. this.shared = shared;
  14845. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14846. }
  14847. Polygon.prototype.clone = function () {
  14848. var vertices = this.vertices.map(function (v) {
  14849. return v.clone();
  14850. });
  14851. return new Polygon(vertices, this.shared);
  14852. };
  14853. Polygon.prototype.flip = function () {
  14854. this.vertices.reverse().map(function (v) {
  14855. v.flip();
  14856. });
  14857. this.plane.flip();
  14858. };
  14859. return Polygon;
  14860. })();
  14861. var Node = (function () {
  14862. function Node(polygons) {
  14863. this.plane = null;
  14864. this.front = null;
  14865. this.back = null;
  14866. this.polygons = [];
  14867. if (polygons) {
  14868. this.build(polygons);
  14869. }
  14870. }
  14871. Node.prototype.clone = function () {
  14872. var node = new Node();
  14873. node.plane = this.plane && this.plane.clone();
  14874. node.front = this.front && this.front.clone();
  14875. node.back = this.back && this.back.clone();
  14876. node.polygons = this.polygons.map(function (p) {
  14877. return p.clone();
  14878. });
  14879. return node;
  14880. };
  14881. Node.prototype.invert = function () {
  14882. for (var i = 0; i < this.polygons.length; i++) {
  14883. this.polygons[i].flip();
  14884. }
  14885. if (this.plane) {
  14886. this.plane.flip();
  14887. }
  14888. if (this.front) {
  14889. this.front.invert();
  14890. }
  14891. if (this.back) {
  14892. this.back.invert();
  14893. }
  14894. var temp = this.front;
  14895. this.front = this.back;
  14896. this.back = temp;
  14897. };
  14898. Node.prototype.clipPolygons = function (polygons) {
  14899. if (!this.plane)
  14900. return polygons.slice();
  14901. var front = [], back = [];
  14902. for (var i = 0; i < polygons.length; i++) {
  14903. this.plane.splitPolygon(polygons[i], front, back, front, back);
  14904. }
  14905. if (this.front) {
  14906. front = this.front.clipPolygons(front);
  14907. }
  14908. if (this.back) {
  14909. back = this.back.clipPolygons(back);
  14910. } else {
  14911. back = [];
  14912. }
  14913. return front.concat(back);
  14914. };
  14915. Node.prototype.clipTo = function (bsp) {
  14916. this.polygons = bsp.clipPolygons(this.polygons);
  14917. if (this.front)
  14918. this.front.clipTo(bsp);
  14919. if (this.back)
  14920. this.back.clipTo(bsp);
  14921. };
  14922. Node.prototype.allPolygons = function () {
  14923. var polygons = this.polygons.slice();
  14924. if (this.front)
  14925. polygons = polygons.concat(this.front.allPolygons());
  14926. if (this.back)
  14927. polygons = polygons.concat(this.back.allPolygons());
  14928. return polygons;
  14929. };
  14930. Node.prototype.build = function (polygons) {
  14931. if (!polygons.length)
  14932. return;
  14933. if (!this.plane)
  14934. this.plane = polygons[0].plane.clone();
  14935. var front = [], back = [];
  14936. for (var i = 0; i < polygons.length; i++) {
  14937. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  14938. }
  14939. if (front.length) {
  14940. if (!this.front)
  14941. this.front = new Node();
  14942. this.front.build(front);
  14943. }
  14944. if (back.length) {
  14945. if (!this.back)
  14946. this.back = new Node();
  14947. this.back.build(back);
  14948. }
  14949. };
  14950. return Node;
  14951. })();
  14952. var CSG = (function () {
  14953. function CSG() {
  14954. this.polygons = new Array();
  14955. }
  14956. CSG.FromMesh = function (mesh) {
  14957. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  14958. if (mesh instanceof BABYLON.Mesh) {
  14959. mesh.computeWorldMatrix(true);
  14960. var matrix = mesh.getWorldMatrix();
  14961. var meshPosition = mesh.position.clone();
  14962. var meshRotation = mesh.rotation.clone();
  14963. var meshScaling = mesh.scaling.clone();
  14964. } else {
  14965. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  14966. }
  14967. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14968. var subMeshes = mesh.subMeshes;
  14969. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  14970. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  14971. vertices = [];
  14972. for (var j = 0; j < 3; j++) {
  14973. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  14974. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  14975. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  14976. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  14977. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  14978. vertex = new Vertex(position, normal, uv);
  14979. vertices.push(vertex);
  14980. }
  14981. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  14982. if (polygon.plane)
  14983. polygons.push(polygon);
  14984. }
  14985. }
  14986. var csg = CSG.FromPolygons(polygons);
  14987. csg.matrix = matrix;
  14988. csg.position = meshPosition;
  14989. csg.rotation = meshRotation;
  14990. csg.scaling = meshScaling;
  14991. currentCSGMeshId++;
  14992. return csg;
  14993. };
  14994. CSG.FromPolygons = function (polygons) {
  14995. var csg = new BABYLON.CSG();
  14996. csg.polygons = polygons;
  14997. return csg;
  14998. };
  14999. CSG.prototype.clone = function () {
  15000. var csg = new BABYLON.CSG();
  15001. csg.polygons = this.polygons.map(function (p) {
  15002. return p.clone();
  15003. });
  15004. csg.copyTransformAttributes(this);
  15005. return csg;
  15006. };
  15007. CSG.prototype.toPolygons = function () {
  15008. return this.polygons;
  15009. };
  15010. CSG.prototype.union = function (csg) {
  15011. var a = new Node(this.clone().polygons);
  15012. var b = new Node(csg.clone().polygons);
  15013. a.clipTo(b);
  15014. b.clipTo(a);
  15015. b.invert();
  15016. b.clipTo(a);
  15017. b.invert();
  15018. a.build(b.allPolygons());
  15019. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15020. };
  15021. CSG.prototype.unionInPlace = function (csg) {
  15022. var a = new Node(this.polygons);
  15023. var b = new Node(csg.polygons);
  15024. a.clipTo(b);
  15025. b.clipTo(a);
  15026. b.invert();
  15027. b.clipTo(a);
  15028. b.invert();
  15029. a.build(b.allPolygons());
  15030. this.polygons = a.allPolygons();
  15031. };
  15032. CSG.prototype.subtract = function (csg) {
  15033. var a = new Node(this.clone().polygons);
  15034. var b = new Node(csg.clone().polygons);
  15035. a.invert();
  15036. a.clipTo(b);
  15037. b.clipTo(a);
  15038. b.invert();
  15039. b.clipTo(a);
  15040. b.invert();
  15041. a.build(b.allPolygons());
  15042. a.invert();
  15043. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15044. };
  15045. CSG.prototype.subtractInPlace = function (csg) {
  15046. var a = new Node(this.polygons);
  15047. var b = new Node(csg.polygons);
  15048. a.invert();
  15049. a.clipTo(b);
  15050. b.clipTo(a);
  15051. b.invert();
  15052. b.clipTo(a);
  15053. b.invert();
  15054. a.build(b.allPolygons());
  15055. a.invert();
  15056. this.polygons = a.allPolygons();
  15057. };
  15058. CSG.prototype.intersect = function (csg) {
  15059. var a = new Node(this.clone().polygons);
  15060. var b = new Node(csg.clone().polygons);
  15061. a.invert();
  15062. b.clipTo(a);
  15063. b.invert();
  15064. a.clipTo(b);
  15065. b.clipTo(a);
  15066. a.build(b.allPolygons());
  15067. a.invert();
  15068. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15069. };
  15070. CSG.prototype.intersectInPlace = function (csg) {
  15071. var a = new Node(this.polygons);
  15072. var b = new Node(csg.polygons);
  15073. a.invert();
  15074. b.clipTo(a);
  15075. b.invert();
  15076. a.clipTo(b);
  15077. b.clipTo(a);
  15078. a.build(b.allPolygons());
  15079. a.invert();
  15080. this.polygons = a.allPolygons();
  15081. };
  15082. CSG.prototype.inverse = function () {
  15083. var csg = this.clone();
  15084. csg.inverseInPlace();
  15085. return csg;
  15086. };
  15087. CSG.prototype.inverseInPlace = function () {
  15088. this.polygons.map(function (p) {
  15089. p.flip();
  15090. });
  15091. };
  15092. CSG.prototype.copyTransformAttributes = function (csg) {
  15093. this.matrix = csg.matrix;
  15094. this.position = csg.position;
  15095. this.rotation = csg.rotation;
  15096. this.scaling = csg.scaling;
  15097. return this;
  15098. };
  15099. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15100. var matrix = this.matrix.clone();
  15101. matrix.invert();
  15102. 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;
  15103. if (keepSubMeshes) {
  15104. polygons.sort(function (a, b) {
  15105. if (a.shared.meshId === b.shared.meshId) {
  15106. return a.shared.subMeshId - b.shared.subMeshId;
  15107. } else {
  15108. return a.shared.meshId - b.shared.meshId;
  15109. }
  15110. });
  15111. }
  15112. for (var i = 0, il = polygons.length; i < il; i++) {
  15113. polygon = polygons[i];
  15114. if (!subMesh_dict[polygon.shared.meshId]) {
  15115. subMesh_dict[polygon.shared.meshId] = {};
  15116. }
  15117. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15118. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15119. indexStart: +Infinity,
  15120. indexEnd: -Infinity,
  15121. materialIndex: polygon.shared.materialIndex
  15122. };
  15123. }
  15124. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15125. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15126. polygonIndices[0] = 0;
  15127. polygonIndices[1] = j - 1;
  15128. polygonIndices[2] = j;
  15129. for (var k = 0; k < 3; k++) {
  15130. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15131. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15132. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15133. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15134. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15135. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15136. 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)) {
  15137. vertices.push(vertex.x, vertex.y, vertex.z);
  15138. uvs.push(uv.x, uv.y);
  15139. normals.push(normal.x, normal.y, normal.z);
  15140. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15141. }
  15142. indices.push(vertex_idx);
  15143. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15144. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15145. currentIndex++;
  15146. }
  15147. }
  15148. }
  15149. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15150. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15151. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15152. mesh.setIndices(indices);
  15153. if (keepSubMeshes) {
  15154. var materialIndexOffset = 0, materialMaxIndex;
  15155. mesh.subMeshes.length = 0;
  15156. for (var m in subMesh_dict) {
  15157. materialMaxIndex = -1;
  15158. for (var sm in subMesh_dict[m]) {
  15159. subMesh_obj = subMesh_dict[m][sm];
  15160. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15161. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15162. }
  15163. materialIndexOffset += ++materialMaxIndex;
  15164. }
  15165. }
  15166. return mesh;
  15167. };
  15168. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15169. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15170. mesh.material = material;
  15171. mesh.position.copyFrom(this.position);
  15172. mesh.rotation.copyFrom(this.rotation);
  15173. mesh.scaling.copyFrom(this.scaling);
  15174. mesh.computeWorldMatrix(true);
  15175. return mesh;
  15176. };
  15177. return CSG;
  15178. })();
  15179. BABYLON.CSG = CSG;
  15180. })(BABYLON || (BABYLON = {}));
  15181. var __extends = this.__extends || function (d, b) {
  15182. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15183. function __() { this.constructor = d; }
  15184. __.prototype = b.prototype;
  15185. d.prototype = new __();
  15186. };
  15187. var BABYLON;
  15188. (function (BABYLON) {
  15189. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15190. __extends(OculusDistortionCorrectionPostProcess, _super);
  15191. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15192. var _this = this;
  15193. _super.call(this, name, "oculusDistortionCorrection", [
  15194. 'LensCenter',
  15195. 'Scale',
  15196. 'ScaleIn',
  15197. 'HmdWarpParam'
  15198. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15199. this._isRightEye = isRightEye;
  15200. this._distortionFactors = cameraSettings.DistortionK;
  15201. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15202. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15203. this.onSizeChanged = function () {
  15204. _this.aspectRatio = _this.width * .5 / _this.height;
  15205. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15206. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15207. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15208. };
  15209. this.onApply = function (effect) {
  15210. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15211. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15212. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15213. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15214. };
  15215. }
  15216. return OculusDistortionCorrectionPostProcess;
  15217. })(BABYLON.PostProcess);
  15218. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15219. })(BABYLON || (BABYLON = {}));
  15220. var BABYLON;
  15221. (function (BABYLON) {
  15222. (function (JoystickAxis) {
  15223. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15224. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15225. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15226. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15227. var JoystickAxis = BABYLON.JoystickAxis;
  15228. var VirtualJoystick = (function () {
  15229. function VirtualJoystick(leftJoystick) {
  15230. var _this = this;
  15231. if (leftJoystick) {
  15232. this._leftJoystick = true;
  15233. } else {
  15234. this._leftJoystick = false;
  15235. }
  15236. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15237. VirtualJoystick._globalJoystickIndex++;
  15238. this._axisTargetedByLeftAndRight = 0 /* X */;
  15239. this._axisTargetedByUpAndDown = 1 /* Y */;
  15240. this.reverseLeftRight = false;
  15241. this.reverseUpDown = false;
  15242. this._touches = new BABYLON.VirtualJoystick.Collection();
  15243. this.deltaPosition = BABYLON.Vector3.Zero();
  15244. this._joystickSensibility = 25;
  15245. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15246. this._rotationSpeed = 25;
  15247. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15248. this._rotateOnAxisRelativeToMesh = false;
  15249. if (!VirtualJoystick.vjCanvas) {
  15250. window.addEventListener("resize", function () {
  15251. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15252. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15253. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15254. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15255. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15256. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15257. }, false);
  15258. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15259. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15260. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15261. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15262. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15263. VirtualJoystick.vjCanvas.style.width = "100%";
  15264. VirtualJoystick.vjCanvas.style.height = "100%";
  15265. VirtualJoystick.vjCanvas.style.position = "absolute";
  15266. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15267. VirtualJoystick.vjCanvas.style.top = "0px";
  15268. VirtualJoystick.vjCanvas.style.left = "0px";
  15269. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15270. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15271. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15272. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15273. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15274. document.body.appendChild(VirtualJoystick.vjCanvas);
  15275. }
  15276. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15277. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15278. this.pressed = false;
  15279. this._joystickColor = "cyan";
  15280. this._joystickPointerID = -1;
  15281. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15282. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15283. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15284. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15285. _this._onPointerDown(evt);
  15286. }, false);
  15287. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15288. _this._onPointerMove(evt);
  15289. }, false);
  15290. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15291. _this._onPointerUp(evt);
  15292. }, false);
  15293. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15294. _this._onPointerUp(evt);
  15295. }, false);
  15296. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15297. evt.preventDefault();
  15298. }, false);
  15299. requestAnimationFrame(function () {
  15300. _this._drawVirtualJoystick();
  15301. });
  15302. }
  15303. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15304. this._joystickSensibility = newJoystickSensibility;
  15305. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15306. };
  15307. VirtualJoystick.prototype._onPointerDown = function (e) {
  15308. var positionOnScreenCondition;
  15309. e.preventDefault();
  15310. if (this._leftJoystick === true) {
  15311. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15312. } else {
  15313. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15314. }
  15315. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15316. this._joystickPointerID = e.pointerId;
  15317. this._joystickPointerStartPos.x = e.clientX;
  15318. this._joystickPointerStartPos.y = e.clientY;
  15319. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15320. this._deltaJoystickVector.x = 0;
  15321. this._deltaJoystickVector.y = 0;
  15322. this.pressed = true;
  15323. this._touches.add(e.pointerId.toString(), e);
  15324. } else {
  15325. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15326. this._action();
  15327. this._touches.add(e.pointerId.toString(), e);
  15328. }
  15329. }
  15330. };
  15331. VirtualJoystick.prototype._onPointerMove = function (e) {
  15332. if (this._joystickPointerID == e.pointerId) {
  15333. this._joystickPointerPos.x = e.clientX;
  15334. this._joystickPointerPos.y = e.clientY;
  15335. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15336. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15337. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15338. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15339. switch (this._axisTargetedByLeftAndRight) {
  15340. case 0 /* X */:
  15341. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15342. break;
  15343. case 1 /* Y */:
  15344. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15345. break;
  15346. case 2 /* Z */:
  15347. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15348. break;
  15349. }
  15350. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15351. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15352. switch (this._axisTargetedByUpAndDown) {
  15353. case 0 /* X */:
  15354. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15355. break;
  15356. case 1 /* Y */:
  15357. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15358. break;
  15359. case 2 /* Z */:
  15360. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15361. break;
  15362. }
  15363. } else {
  15364. if (this._touches.item(e.pointerId.toString())) {
  15365. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15366. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15367. }
  15368. }
  15369. };
  15370. VirtualJoystick.prototype._onPointerUp = function (e) {
  15371. this._clearCanvas();
  15372. if (this._joystickPointerID == e.pointerId) {
  15373. this._joystickPointerID = -1;
  15374. this.pressed = false;
  15375. }
  15376. this._deltaJoystickVector.x = 0;
  15377. this._deltaJoystickVector.y = 0;
  15378. this._touches.remove(e.pointerId.toString());
  15379. };
  15380. /**
  15381. * Change the color of the virtual joystick
  15382. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15383. */
  15384. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15385. this._joystickColor = newColor;
  15386. };
  15387. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15388. this._action = action;
  15389. };
  15390. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15391. switch (axis) {
  15392. case 0 /* X */:
  15393. case 1 /* Y */:
  15394. case 2 /* Z */:
  15395. this._axisTargetedByLeftAndRight = axis;
  15396. break;
  15397. default:
  15398. this._axisTargetedByLeftAndRight = 0 /* X */;
  15399. break;
  15400. }
  15401. };
  15402. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15403. switch (axis) {
  15404. case 0 /* X */:
  15405. case 1 /* Y */:
  15406. case 2 /* Z */:
  15407. this._axisTargetedByUpAndDown = axis;
  15408. break;
  15409. default:
  15410. this._axisTargetedByUpAndDown = 1 /* Y */;
  15411. break;
  15412. }
  15413. };
  15414. VirtualJoystick.prototype._clearCanvas = function () {
  15415. if (this._leftJoystick) {
  15416. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15417. } else {
  15418. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15419. }
  15420. };
  15421. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15422. var _this = this;
  15423. if (this.pressed) {
  15424. this._clearCanvas();
  15425. this._touches.forEach(function (touch) {
  15426. if (touch.pointerId === _this._joystickPointerID) {
  15427. VirtualJoystick.vjCanvasContext.beginPath();
  15428. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15429. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15430. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15431. VirtualJoystick.vjCanvasContext.stroke();
  15432. VirtualJoystick.vjCanvasContext.beginPath();
  15433. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15434. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15435. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15436. VirtualJoystick.vjCanvasContext.stroke();
  15437. VirtualJoystick.vjCanvasContext.beginPath();
  15438. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15439. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15440. VirtualJoystick.vjCanvasContext.stroke();
  15441. } else {
  15442. VirtualJoystick.vjCanvasContext.beginPath();
  15443. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15444. VirtualJoystick.vjCanvasContext.beginPath();
  15445. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15446. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15447. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15448. VirtualJoystick.vjCanvasContext.stroke();
  15449. }
  15450. ;
  15451. });
  15452. }
  15453. requestAnimationFrame(function () {
  15454. _this._drawVirtualJoystick();
  15455. });
  15456. };
  15457. VirtualJoystick.prototype.releaseCanvas = function () {
  15458. if (VirtualJoystick.vjCanvas) {
  15459. document.body.removeChild(VirtualJoystick.vjCanvas);
  15460. VirtualJoystick.vjCanvas = null;
  15461. }
  15462. };
  15463. VirtualJoystick._globalJoystickIndex = 0;
  15464. return VirtualJoystick;
  15465. })();
  15466. BABYLON.VirtualJoystick = VirtualJoystick;
  15467. })(BABYLON || (BABYLON = {}));
  15468. var BABYLON;
  15469. (function (BABYLON) {
  15470. (function (VirtualJoystick) {
  15471. var Collection = (function () {
  15472. function Collection() {
  15473. this._count = 0;
  15474. this._collection = new Array();
  15475. }
  15476. Collection.prototype.Count = function () {
  15477. return this._count;
  15478. };
  15479. Collection.prototype.add = function (key, item) {
  15480. if (this._collection[key] != undefined) {
  15481. return undefined;
  15482. }
  15483. this._collection[key] = item;
  15484. return ++this._count;
  15485. };
  15486. Collection.prototype.remove = function (key) {
  15487. if (this._collection[key] == undefined) {
  15488. return undefined;
  15489. }
  15490. delete this._collection[key];
  15491. return --this._count;
  15492. };
  15493. Collection.prototype.item = function (key) {
  15494. return this._collection[key];
  15495. };
  15496. Collection.prototype.forEach = function (block) {
  15497. var key;
  15498. for (key in this._collection) {
  15499. if (this._collection.hasOwnProperty(key)) {
  15500. block(this._collection[key]);
  15501. }
  15502. }
  15503. };
  15504. return Collection;
  15505. })();
  15506. VirtualJoystick.Collection = Collection;
  15507. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15508. var VirtualJoystick = BABYLON.VirtualJoystick;
  15509. })(BABYLON || (BABYLON = {}));
  15510. var __extends = this.__extends || function (d, b) {
  15511. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15512. function __() { this.constructor = d; }
  15513. __.prototype = b.prototype;
  15514. d.prototype = new __();
  15515. };
  15516. var BABYLON;
  15517. (function (BABYLON) {
  15518. var OculusRiftDevKit2013_Metric = {
  15519. HResolution: 1280,
  15520. VResolution: 800,
  15521. HScreenSize: 0.149759993,
  15522. VScreenSize: 0.0935999975,
  15523. VScreenCenter: 0.0467999987,
  15524. EyeToScreenDistance: 0.0410000011,
  15525. LensSeparationDistance: 0.0635000020,
  15526. InterpupillaryDistance: 0.0640000030,
  15527. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15528. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15529. PostProcessScaleFactor: 1.714605507808412,
  15530. LensCenterOffset: 0.151976421
  15531. };
  15532. var _OculusInnerCamera = (function (_super) {
  15533. __extends(_OculusInnerCamera, _super);
  15534. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15535. _super.call(this, name, position, scene);
  15536. this._workMatrix = new BABYLON.Matrix();
  15537. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15538. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15539. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15540. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15541. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15542. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15543. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15544. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15545. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15546. }
  15547. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15548. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15549. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15550. return this._projectionMatrix;
  15551. };
  15552. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15553. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15554. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15555. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15556. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15557. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15558. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15559. return this._viewMatrix;
  15560. };
  15561. return _OculusInnerCamera;
  15562. })(BABYLON.FreeCamera);
  15563. var OculusCamera = (function (_super) {
  15564. __extends(OculusCamera, _super);
  15565. function OculusCamera(name, position, scene) {
  15566. _super.call(this, name, position, scene);
  15567. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15568. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15569. this.subCameras.push(this._leftCamera);
  15570. this.subCameras.push(this._rightCamera);
  15571. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15572. }
  15573. OculusCamera.prototype._update = function () {
  15574. this._leftCamera.position.copyFrom(this.position);
  15575. this._rightCamera.position.copyFrom(this.position);
  15576. this._updateCamera(this._leftCamera);
  15577. this._updateCamera(this._rightCamera);
  15578. _super.prototype._update.call(this);
  15579. };
  15580. OculusCamera.prototype._updateCamera = function (camera) {
  15581. camera.minZ = this.minZ;
  15582. camera.maxZ = this.maxZ;
  15583. camera.rotation.x = this.rotation.x;
  15584. camera.rotation.y = this.rotation.y;
  15585. camera.rotation.z = this.rotation.z;
  15586. };
  15587. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15588. var yaw = evt.alpha / 180 * Math.PI;
  15589. var pitch = evt.beta / 180 * Math.PI;
  15590. var roll = evt.gamma / 180 * Math.PI;
  15591. if (!this._offsetOrientation) {
  15592. this._offsetOrientation = {
  15593. yaw: yaw,
  15594. pitch: pitch,
  15595. roll: roll
  15596. };
  15597. return;
  15598. } else {
  15599. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15600. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15601. this.rotation.z += this._offsetOrientation.roll - roll;
  15602. this._offsetOrientation.yaw = yaw;
  15603. this._offsetOrientation.pitch = pitch;
  15604. this._offsetOrientation.roll = roll;
  15605. }
  15606. };
  15607. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15608. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15609. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15610. };
  15611. OculusCamera.prototype.detachControl = function (element) {
  15612. _super.prototype.detachControl.call(this, element);
  15613. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15614. };
  15615. return OculusCamera;
  15616. })(BABYLON.FreeCamera);
  15617. BABYLON.OculusCamera = OculusCamera;
  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 VirtualJoysticksCamera = (function (_super) {
  15628. __extends(VirtualJoysticksCamera, _super);
  15629. function VirtualJoysticksCamera(name, position, scene) {
  15630. _super.call(this, name, position, scene);
  15631. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15632. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15633. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15634. this._leftjoystick.setJoystickSensibility(0.15);
  15635. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15636. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15637. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15638. this._rightjoystick.reverseUpDown = true;
  15639. this._rightjoystick.setJoystickSensibility(0.05);
  15640. this._rightjoystick.setJoystickColor("yellow");
  15641. }
  15642. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15643. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15644. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15645. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15646. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15647. if (!this._leftjoystick.pressed) {
  15648. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15649. }
  15650. if (!this._rightjoystick.pressed) {
  15651. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15652. }
  15653. };
  15654. VirtualJoysticksCamera.prototype.dispose = function () {
  15655. this._leftjoystick.releaseCanvas();
  15656. _super.prototype.dispose.call(this);
  15657. };
  15658. return VirtualJoysticksCamera;
  15659. })(BABYLON.FreeCamera);
  15660. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15661. })(BABYLON || (BABYLON = {}));
  15662. var __extends = this.__extends || function (d, b) {
  15663. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15664. function __() { this.constructor = d; }
  15665. __.prototype = b.prototype;
  15666. d.prototype = new __();
  15667. };
  15668. var BABYLON;
  15669. (function (BABYLON) {
  15670. var ShaderMaterial = (function (_super) {
  15671. __extends(ShaderMaterial, _super);
  15672. function ShaderMaterial(name, scene, shaderPath, options) {
  15673. _super.call(this, name, scene);
  15674. this._textures = new Array();
  15675. this._floats = new Array();
  15676. this._floatsArrays = {};
  15677. this._colors3 = new Array();
  15678. this._colors4 = new Array();
  15679. this._vectors2 = new Array();
  15680. this._vectors3 = new Array();
  15681. this._matrices = new Array();
  15682. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15683. this._shaderPath = shaderPath;
  15684. options.needAlphaBlending = options.needAlphaBlending || false;
  15685. options.needAlphaTesting = options.needAlphaTesting || false;
  15686. options.attributes = options.attributes || ["position", "normal", "uv"];
  15687. options.uniforms = options.uniforms || ["worldViewProjection"];
  15688. options.samplers = options.samplers || [];
  15689. this._options = options;
  15690. }
  15691. ShaderMaterial.prototype.needAlphaBlending = function () {
  15692. return this._options.needAlphaBlending;
  15693. };
  15694. ShaderMaterial.prototype.needAlphaTesting = function () {
  15695. return this._options.needAlphaTesting;
  15696. };
  15697. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15698. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15699. this._options.uniforms.push(uniformName);
  15700. }
  15701. };
  15702. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15703. if (this._options.samplers.indexOf(name) === -1) {
  15704. this._options.samplers.push(name);
  15705. }
  15706. this._textures[name] = texture;
  15707. return this;
  15708. };
  15709. ShaderMaterial.prototype.setFloat = function (name, value) {
  15710. this._checkUniform(name);
  15711. this._floats[name] = value;
  15712. return this;
  15713. };
  15714. ShaderMaterial.prototype.setFloats = function (name, value) {
  15715. this._checkUniform(name);
  15716. this._floatsArrays[name] = value;
  15717. return this;
  15718. };
  15719. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15720. this._checkUniform(name);
  15721. this._colors3[name] = value;
  15722. return this;
  15723. };
  15724. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15725. this._checkUniform(name);
  15726. this._colors4[name] = value;
  15727. return this;
  15728. };
  15729. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15730. this._checkUniform(name);
  15731. this._vectors2[name] = value;
  15732. return this;
  15733. };
  15734. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15735. this._checkUniform(name);
  15736. this._vectors3[name] = value;
  15737. return this;
  15738. };
  15739. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15740. this._checkUniform(name);
  15741. this._matrices[name] = value;
  15742. return this;
  15743. };
  15744. ShaderMaterial.prototype.isReady = function () {
  15745. var engine = this.getScene().getEngine();
  15746. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15747. if (!this._effect.isReady()) {
  15748. return false;
  15749. }
  15750. return true;
  15751. };
  15752. ShaderMaterial.prototype.bind = function (world) {
  15753. if (this._options.uniforms.indexOf("world") !== -1) {
  15754. this._effect.setMatrix("world", world);
  15755. }
  15756. if (this._options.uniforms.indexOf("view") !== -1) {
  15757. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15758. }
  15759. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15760. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15761. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15762. }
  15763. if (this._options.uniforms.indexOf("projection") !== -1) {
  15764. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15765. }
  15766. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15767. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15768. }
  15769. for (var name in this._textures) {
  15770. this._effect.setTexture(name, this._textures[name]);
  15771. }
  15772. for (name in this._floats) {
  15773. this._effect.setFloat(name, this._floats[name]);
  15774. }
  15775. for (name in this._floatsArrays) {
  15776. this._effect.setArray(name, this._floatsArrays[name]);
  15777. }
  15778. for (name in this._colors3) {
  15779. this._effect.setColor3(name, this._colors3[name]);
  15780. }
  15781. for (name in this._colors4) {
  15782. var color = this._colors4[name];
  15783. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15784. }
  15785. for (name in this._vectors2) {
  15786. this._effect.setVector2(name, this._vectors2[name]);
  15787. }
  15788. for (name in this._vectors3) {
  15789. this._effect.setVector3(name, this._vectors3[name]);
  15790. }
  15791. for (name in this._matrices) {
  15792. this._effect.setMatrix(name, this._matrices[name]);
  15793. }
  15794. };
  15795. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15796. for (var name in this._textures) {
  15797. this._textures[name].dispose();
  15798. }
  15799. this._textures = [];
  15800. _super.prototype.dispose.call(this, forceDisposeEffect);
  15801. };
  15802. return ShaderMaterial;
  15803. })(BABYLON.Material);
  15804. BABYLON.ShaderMaterial = ShaderMaterial;
  15805. })(BABYLON || (BABYLON = {}));
  15806. var BABYLON;
  15807. (function (BABYLON) {
  15808. var VertexData = (function () {
  15809. function VertexData() {
  15810. }
  15811. VertexData.prototype.set = function (data, kind) {
  15812. switch (kind) {
  15813. case BABYLON.VertexBuffer.PositionKind:
  15814. this.positions = data;
  15815. break;
  15816. case BABYLON.VertexBuffer.NormalKind:
  15817. this.normals = data;
  15818. break;
  15819. case BABYLON.VertexBuffer.UVKind:
  15820. this.uvs = data;
  15821. break;
  15822. case BABYLON.VertexBuffer.UV2Kind:
  15823. this.uv2s = data;
  15824. break;
  15825. case BABYLON.VertexBuffer.ColorKind:
  15826. this.colors = data;
  15827. break;
  15828. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15829. this.matricesIndices = data;
  15830. break;
  15831. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15832. this.matricesWeights = data;
  15833. break;
  15834. }
  15835. };
  15836. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15837. this._applyTo(mesh, updatable);
  15838. };
  15839. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15840. this._applyTo(geometry, updatable);
  15841. };
  15842. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15843. this._update(mesh);
  15844. };
  15845. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15846. this._update(geometry);
  15847. };
  15848. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15849. if (this.positions) {
  15850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15851. }
  15852. if (this.normals) {
  15853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15854. }
  15855. if (this.uvs) {
  15856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15857. }
  15858. if (this.uv2s) {
  15859. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  15860. }
  15861. if (this.colors) {
  15862. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  15863. }
  15864. if (this.matricesIndices) {
  15865. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  15866. }
  15867. if (this.matricesWeights) {
  15868. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  15869. }
  15870. if (this.indices) {
  15871. meshOrGeometry.setIndices(this.indices);
  15872. }
  15873. };
  15874. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  15875. if (this.positions) {
  15876. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  15877. }
  15878. if (this.normals) {
  15879. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  15880. }
  15881. if (this.uvs) {
  15882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  15883. }
  15884. if (this.uv2s) {
  15885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  15886. }
  15887. if (this.colors) {
  15888. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  15889. }
  15890. if (this.matricesIndices) {
  15891. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  15892. }
  15893. if (this.matricesWeights) {
  15894. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  15895. }
  15896. if (this.indices) {
  15897. meshOrGeometry.setIndices(this.indices);
  15898. }
  15899. };
  15900. VertexData.prototype.transform = function (matrix) {
  15901. var transformed = BABYLON.Vector3.Zero();
  15902. if (this.positions) {
  15903. var position = BABYLON.Vector3.Zero();
  15904. for (var index = 0; index < this.positions.length; index += 3) {
  15905. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  15906. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  15907. this.positions[index] = transformed.x;
  15908. this.positions[index + 1] = transformed.y;
  15909. this.positions[index + 2] = transformed.z;
  15910. }
  15911. }
  15912. if (this.normals) {
  15913. var normal = BABYLON.Vector3.Zero();
  15914. for (index = 0; index < this.normals.length; index += 3) {
  15915. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  15916. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  15917. this.normals[index] = transformed.x;
  15918. this.normals[index + 1] = transformed.y;
  15919. this.normals[index + 2] = transformed.z;
  15920. }
  15921. }
  15922. };
  15923. VertexData.prototype.merge = function (other) {
  15924. if (other.indices) {
  15925. if (!this.indices) {
  15926. this.indices = [];
  15927. }
  15928. var offset = this.positions ? this.positions.length / 3 : 0;
  15929. for (var index = 0; index < other.indices.length; index++) {
  15930. this.indices.push(other.indices[index] + offset);
  15931. }
  15932. }
  15933. if (other.positions) {
  15934. if (!this.positions) {
  15935. this.positions = [];
  15936. }
  15937. for (index = 0; index < other.positions.length; index++) {
  15938. this.positions.push(other.positions[index]);
  15939. }
  15940. }
  15941. if (other.normals) {
  15942. if (!this.normals) {
  15943. this.normals = [];
  15944. }
  15945. for (index = 0; index < other.normals.length; index++) {
  15946. this.normals.push(other.normals[index]);
  15947. }
  15948. }
  15949. if (other.uvs) {
  15950. if (!this.uvs) {
  15951. this.uvs = [];
  15952. }
  15953. for (index = 0; index < other.uvs.length; index++) {
  15954. this.uvs.push(other.uvs[index]);
  15955. }
  15956. }
  15957. if (other.uv2s) {
  15958. if (!this.uv2s) {
  15959. this.uv2s = [];
  15960. }
  15961. for (index = 0; index < other.uv2s.length; index++) {
  15962. this.uv2s.push(other.uv2s[index]);
  15963. }
  15964. }
  15965. if (other.matricesIndices) {
  15966. if (!this.matricesIndices) {
  15967. this.matricesIndices = [];
  15968. }
  15969. for (index = 0; index < other.matricesIndices.length; index++) {
  15970. this.matricesIndices.push(other.matricesIndices[index]);
  15971. }
  15972. }
  15973. if (other.matricesWeights) {
  15974. if (!this.matricesWeights) {
  15975. this.matricesWeights = [];
  15976. }
  15977. for (index = 0; index < other.matricesWeights.length; index++) {
  15978. this.matricesWeights.push(other.matricesWeights[index]);
  15979. }
  15980. }
  15981. if (other.colors) {
  15982. if (!this.colors) {
  15983. this.colors = [];
  15984. }
  15985. for (index = 0; index < other.colors.length; index++) {
  15986. this.colors.push(other.colors[index]);
  15987. }
  15988. }
  15989. };
  15990. VertexData.ExtractFromMesh = function (mesh) {
  15991. return VertexData._ExtractFrom(mesh);
  15992. };
  15993. VertexData.ExtractFromGeometry = function (geometry) {
  15994. return VertexData._ExtractFrom(geometry);
  15995. };
  15996. VertexData._ExtractFrom = function (meshOrGeometry) {
  15997. var result = new BABYLON.VertexData();
  15998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15999. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16000. }
  16001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16002. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16003. }
  16004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16005. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16006. }
  16007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16008. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16009. }
  16010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16011. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16012. }
  16013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16014. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16015. }
  16016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16017. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16018. }
  16019. result.indices = meshOrGeometry.getIndices();
  16020. return result;
  16021. };
  16022. VertexData.CreateBox = function (size) {
  16023. var normalsSource = [
  16024. new BABYLON.Vector3(0, 0, 1),
  16025. new BABYLON.Vector3(0, 0, -1),
  16026. new BABYLON.Vector3(1, 0, 0),
  16027. new BABYLON.Vector3(-1, 0, 0),
  16028. new BABYLON.Vector3(0, 1, 0),
  16029. new BABYLON.Vector3(0, -1, 0)
  16030. ];
  16031. var indices = [];
  16032. var positions = [];
  16033. var normals = [];
  16034. var uvs = [];
  16035. size = size || 1;
  16036. for (var index = 0; index < normalsSource.length; index++) {
  16037. var normal = normalsSource[index];
  16038. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16039. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16040. var verticesLength = positions.length / 3;
  16041. indices.push(verticesLength);
  16042. indices.push(verticesLength + 1);
  16043. indices.push(verticesLength + 2);
  16044. indices.push(verticesLength);
  16045. indices.push(verticesLength + 2);
  16046. indices.push(verticesLength + 3);
  16047. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16048. positions.push(vertex.x, vertex.y, vertex.z);
  16049. normals.push(normal.x, normal.y, normal.z);
  16050. uvs.push(1.0, 1.0);
  16051. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16052. positions.push(vertex.x, vertex.y, vertex.z);
  16053. normals.push(normal.x, normal.y, normal.z);
  16054. uvs.push(0.0, 1.0);
  16055. vertex = normal.add(side1).add(side2).scale(size / 2);
  16056. positions.push(vertex.x, vertex.y, vertex.z);
  16057. normals.push(normal.x, normal.y, normal.z);
  16058. uvs.push(0.0, 0.0);
  16059. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16060. positions.push(vertex.x, vertex.y, vertex.z);
  16061. normals.push(normal.x, normal.y, normal.z);
  16062. uvs.push(1.0, 0.0);
  16063. }
  16064. var vertexData = new BABYLON.VertexData();
  16065. vertexData.indices = indices;
  16066. vertexData.positions = positions;
  16067. vertexData.normals = normals;
  16068. vertexData.uvs = uvs;
  16069. return vertexData;
  16070. };
  16071. VertexData.CreateSphere = function (segments, diameter) {
  16072. segments = segments || 32;
  16073. diameter = diameter || 1;
  16074. var radius = diameter / 2;
  16075. var totalZRotationSteps = 2 + segments;
  16076. var totalYRotationSteps = 2 * totalZRotationSteps;
  16077. var indices = [];
  16078. var positions = [];
  16079. var normals = [];
  16080. var uvs = [];
  16081. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16082. var normalizedZ = zRotationStep / totalZRotationSteps;
  16083. var angleZ = (normalizedZ * Math.PI);
  16084. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16085. var normalizedY = yRotationStep / totalYRotationSteps;
  16086. var angleY = normalizedY * Math.PI * 2;
  16087. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16088. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16089. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16090. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16091. var vertex = complete.scale(radius);
  16092. var normal = BABYLON.Vector3.Normalize(vertex);
  16093. positions.push(vertex.x, vertex.y, vertex.z);
  16094. normals.push(normal.x, normal.y, normal.z);
  16095. uvs.push(normalizedZ, normalizedY);
  16096. }
  16097. if (zRotationStep > 0) {
  16098. var verticesCount = positions.length / 3;
  16099. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16100. indices.push((firstIndex));
  16101. indices.push((firstIndex + 1));
  16102. indices.push(firstIndex + totalYRotationSteps + 1);
  16103. indices.push((firstIndex + totalYRotationSteps + 1));
  16104. indices.push((firstIndex + 1));
  16105. indices.push((firstIndex + totalYRotationSteps + 2));
  16106. }
  16107. }
  16108. }
  16109. var vertexData = new BABYLON.VertexData();
  16110. vertexData.indices = indices;
  16111. vertexData.positions = positions;
  16112. vertexData.normals = normals;
  16113. vertexData.uvs = uvs;
  16114. return vertexData;
  16115. };
  16116. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16117. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16118. var radiusTop = diameterTop / 2;
  16119. var radiusBottom = diameterBottom / 2;
  16120. var indices = [];
  16121. var positions = [];
  16122. var normals = [];
  16123. var uvs = [];
  16124. height = height || 1;
  16125. diameterTop = diameterTop || 0.5;
  16126. diameterBottom = diameterBottom || 1;
  16127. tessellation = tessellation || 16;
  16128. subdivisions = subdivisions || 1;
  16129. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16130. var getCircleVector = function (i) {
  16131. var angle = (i * 2.0 * Math.PI / tessellation);
  16132. var dx = Math.cos(angle);
  16133. var dz = Math.sin(angle);
  16134. return new BABYLON.Vector3(dx, 0, dz);
  16135. };
  16136. var createCylinderCap = function (isTop) {
  16137. var radius = isTop ? radiusTop : radiusBottom;
  16138. if (radius == 0) {
  16139. return;
  16140. }
  16141. var vbase = positions.length / 3;
  16142. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16143. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16144. if (!isTop) {
  16145. offset.scaleInPlace(-1);
  16146. textureScale.x = -textureScale.x;
  16147. }
  16148. for (i = 0; i < tessellation; i++) {
  16149. var circleVector = getCircleVector(i);
  16150. var position = circleVector.scale(radius).add(offset);
  16151. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16152. positions.push(position.x, position.y, position.z);
  16153. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16154. }
  16155. for (var i = 0; i < tessellation - 2; i++) {
  16156. if (!isTop) {
  16157. indices.push(vbase);
  16158. indices.push(vbase + (i + 2) % tessellation);
  16159. indices.push(vbase + (i + 1) % tessellation);
  16160. } else {
  16161. indices.push(vbase);
  16162. indices.push(vbase + (i + 1) % tessellation);
  16163. indices.push(vbase + (i + 2) % tessellation);
  16164. }
  16165. }
  16166. };
  16167. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16168. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16169. var stride = tessellation + 1;
  16170. for (var i = 0; i <= tessellation; i++) {
  16171. var circleVector = getCircleVector(i);
  16172. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16173. var position, radius = radiusBottom;
  16174. for (var s = 0; s <= subdivisions; s++) {
  16175. position = circleVector.scale(radius);
  16176. position.addInPlace(base.add(offset.scale(s)));
  16177. textureCoordinate.y += 1 / subdivisions;
  16178. radius += (radiusTop - radiusBottom) / subdivisions;
  16179. positions.push(position.x, position.y, position.z);
  16180. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16181. }
  16182. }
  16183. subdivisions += 1;
  16184. for (var s = 0; s < subdivisions - 1; s++) {
  16185. for (var i = 0; i <= tessellation; i++) {
  16186. indices.push(i * subdivisions + s);
  16187. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16188. indices.push(i * subdivisions + (s + 1));
  16189. indices.push(i * subdivisions + (s + 1));
  16190. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16191. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16192. }
  16193. }
  16194. createCylinderCap(true);
  16195. createCylinderCap(false);
  16196. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  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.CreateTorus = function (diameter, thickness, tessellation) {
  16205. var indices = [];
  16206. var positions = [];
  16207. var normals = [];
  16208. var uvs = [];
  16209. diameter = diameter || 1;
  16210. thickness = thickness || 0.5;
  16211. tessellation = tessellation || 16;
  16212. var stride = tessellation + 1;
  16213. for (var i = 0; i <= tessellation; i++) {
  16214. var u = i / tessellation;
  16215. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16216. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16217. for (var j = 0; j <= tessellation; j++) {
  16218. var v = 1 - j / tessellation;
  16219. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16220. var dx = Math.cos(innerAngle);
  16221. var dy = Math.sin(innerAngle);
  16222. var normal = new BABYLON.Vector3(dx, dy, 0);
  16223. var position = normal.scale(thickness / 2);
  16224. var textureCoordinate = new BABYLON.Vector2(u, v);
  16225. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16226. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16227. positions.push(position.x, position.y, position.z);
  16228. normals.push(normal.x, normal.y, normal.z);
  16229. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16230. var nextI = (i + 1) % stride;
  16231. var nextJ = (j + 1) % stride;
  16232. indices.push(i * stride + j);
  16233. indices.push(i * stride + nextJ);
  16234. indices.push(nextI * stride + j);
  16235. indices.push(i * stride + nextJ);
  16236. indices.push(nextI * stride + nextJ);
  16237. indices.push(nextI * stride + j);
  16238. }
  16239. }
  16240. var vertexData = new BABYLON.VertexData();
  16241. vertexData.indices = indices;
  16242. vertexData.positions = positions;
  16243. vertexData.normals = normals;
  16244. vertexData.uvs = uvs;
  16245. return vertexData;
  16246. };
  16247. VertexData.CreateLines = function (points) {
  16248. var indices = [];
  16249. var positions = [];
  16250. for (var index = 0; index < points.length; index++) {
  16251. positions.push(points[index].x, points[index].y, points[index].z);
  16252. if (index > 0) {
  16253. indices.push(index - 1);
  16254. indices.push(index);
  16255. }
  16256. }
  16257. var vertexData = new BABYLON.VertexData();
  16258. vertexData.indices = indices;
  16259. vertexData.positions = positions;
  16260. return vertexData;
  16261. };
  16262. VertexData.CreateGround = function (width, height, subdivisions) {
  16263. var indices = [];
  16264. var positions = [];
  16265. var normals = [];
  16266. var uvs = [];
  16267. var row, col;
  16268. width = width || 1;
  16269. height = height || 1;
  16270. subdivisions = subdivisions || 1;
  16271. for (row = 0; row <= subdivisions; row++) {
  16272. for (col = 0; col <= subdivisions; col++) {
  16273. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16274. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16275. positions.push(position.x, position.y, position.z);
  16276. normals.push(normal.x, normal.y, normal.z);
  16277. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16278. }
  16279. }
  16280. for (row = 0; row < subdivisions; row++) {
  16281. for (col = 0; col < subdivisions; col++) {
  16282. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16283. indices.push(col + 1 + row * (subdivisions + 1));
  16284. indices.push(col + row * (subdivisions + 1));
  16285. indices.push(col + (row + 1) * (subdivisions + 1));
  16286. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16287. indices.push(col + row * (subdivisions + 1));
  16288. }
  16289. }
  16290. var vertexData = new BABYLON.VertexData();
  16291. vertexData.indices = indices;
  16292. vertexData.positions = positions;
  16293. vertexData.normals = normals;
  16294. vertexData.uvs = uvs;
  16295. return vertexData;
  16296. };
  16297. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16298. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16299. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16300. var indices = [];
  16301. var positions = [];
  16302. var normals = [];
  16303. var uvs = [];
  16304. var row, col, tileRow, tileCol;
  16305. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16306. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16307. precision.w = (precision.w < 1) ? 1 : precision.w;
  16308. precision.h = (precision.h < 1) ? 1 : precision.h;
  16309. var tileSize = {
  16310. 'w': (xmax - xmin) / subdivisions.w,
  16311. 'h': (zmax - zmin) / subdivisions.h
  16312. };
  16313. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16314. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16315. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16316. }
  16317. }
  16318. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16319. var base = positions.length / 3;
  16320. var rowLength = precision.w + 1;
  16321. for (row = 0; row < precision.h; row++) {
  16322. for (col = 0; col < precision.w; col++) {
  16323. var square = [
  16324. base + col + row * rowLength,
  16325. base + (col + 1) + row * rowLength,
  16326. base + (col + 1) + (row + 1) * rowLength,
  16327. base + col + (row + 1) * rowLength
  16328. ];
  16329. indices.push(square[1]);
  16330. indices.push(square[2]);
  16331. indices.push(square[3]);
  16332. indices.push(square[0]);
  16333. indices.push(square[1]);
  16334. indices.push(square[3]);
  16335. }
  16336. }
  16337. var position = BABYLON.Vector3.Zero();
  16338. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16339. for (row = 0; row <= precision.h; row++) {
  16340. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16341. for (col = 0; col <= precision.w; col++) {
  16342. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16343. position.y = 0;
  16344. positions.push(position.x, position.y, position.z);
  16345. normals.push(normal.x, normal.y, normal.z);
  16346. uvs.push(col / precision.w, row / precision.h);
  16347. }
  16348. }
  16349. }
  16350. var vertexData = new BABYLON.VertexData();
  16351. vertexData.indices = indices;
  16352. vertexData.positions = positions;
  16353. vertexData.normals = normals;
  16354. vertexData.uvs = uvs;
  16355. return vertexData;
  16356. };
  16357. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16358. var indices = [];
  16359. var positions = [];
  16360. var normals = [];
  16361. var uvs = [];
  16362. var row, col;
  16363. for (row = 0; row <= subdivisions; row++) {
  16364. for (col = 0; col <= subdivisions; col++) {
  16365. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16366. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16367. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16368. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16369. var r = buffer[pos] / 255.0;
  16370. var g = buffer[pos + 1] / 255.0;
  16371. var b = buffer[pos + 2] / 255.0;
  16372. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16373. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16374. positions.push(position.x, position.y, position.z);
  16375. normals.push(0, 0, 0);
  16376. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16377. }
  16378. }
  16379. for (row = 0; row < subdivisions; row++) {
  16380. for (col = 0; col < subdivisions; col++) {
  16381. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16382. indices.push(col + 1 + row * (subdivisions + 1));
  16383. indices.push(col + row * (subdivisions + 1));
  16384. indices.push(col + (row + 1) * (subdivisions + 1));
  16385. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16386. indices.push(col + row * (subdivisions + 1));
  16387. }
  16388. }
  16389. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16390. var vertexData = new BABYLON.VertexData();
  16391. vertexData.indices = indices;
  16392. vertexData.positions = positions;
  16393. vertexData.normals = normals;
  16394. vertexData.uvs = uvs;
  16395. return vertexData;
  16396. };
  16397. VertexData.CreatePlane = function (size) {
  16398. var indices = [];
  16399. var positions = [];
  16400. var normals = [];
  16401. var uvs = [];
  16402. size = size || 1;
  16403. var halfSize = size / 2.0;
  16404. positions.push(-halfSize, -halfSize, 0);
  16405. normals.push(0, 0, -1.0);
  16406. uvs.push(0.0, 0.0);
  16407. positions.push(halfSize, -halfSize, 0);
  16408. normals.push(0, 0, -1.0);
  16409. uvs.push(1.0, 0.0);
  16410. positions.push(halfSize, halfSize, 0);
  16411. normals.push(0, 0, -1.0);
  16412. uvs.push(1.0, 1.0);
  16413. positions.push(-halfSize, halfSize, 0);
  16414. normals.push(0, 0, -1.0);
  16415. uvs.push(0.0, 1.0);
  16416. indices.push(0);
  16417. indices.push(1);
  16418. indices.push(2);
  16419. indices.push(0);
  16420. indices.push(2);
  16421. indices.push(3);
  16422. var vertexData = new BABYLON.VertexData();
  16423. vertexData.indices = indices;
  16424. vertexData.positions = positions;
  16425. vertexData.normals = normals;
  16426. vertexData.uvs = uvs;
  16427. return vertexData;
  16428. };
  16429. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16430. var indices = [];
  16431. var positions = [];
  16432. var normals = [];
  16433. var uvs = [];
  16434. radius = radius || 2;
  16435. tube = tube || 0.5;
  16436. radialSegments = radialSegments || 32;
  16437. tubularSegments = tubularSegments || 32;
  16438. p = p || 2;
  16439. q = q || 3;
  16440. var getPos = function (angle) {
  16441. var cu = Math.cos(angle);
  16442. var su = Math.sin(angle);
  16443. var quOverP = q / p * angle;
  16444. var cs = Math.cos(quOverP);
  16445. var tx = radius * (2 + cs) * 0.5 * cu;
  16446. var ty = radius * (2 + cs) * su * 0.5;
  16447. var tz = radius * Math.sin(quOverP) * 0.5;
  16448. return new BABYLON.Vector3(tx, ty, tz);
  16449. };
  16450. for (var i = 0; i <= radialSegments; i++) {
  16451. var modI = i % radialSegments;
  16452. var u = modI / radialSegments * 2 * p * Math.PI;
  16453. var p1 = getPos(u);
  16454. var p2 = getPos(u + 0.01);
  16455. var tang = p2.subtract(p1);
  16456. var n = p2.add(p1);
  16457. var bitan = BABYLON.Vector3.Cross(tang, n);
  16458. n = BABYLON.Vector3.Cross(bitan, tang);
  16459. bitan.normalize();
  16460. n.normalize();
  16461. for (var j = 0; j < tubularSegments; j++) {
  16462. var modJ = j % tubularSegments;
  16463. var v = modJ / tubularSegments * 2 * Math.PI;
  16464. var cx = -tube * Math.cos(v);
  16465. var cy = tube * Math.sin(v);
  16466. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16467. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16468. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16469. uvs.push(i / radialSegments);
  16470. uvs.push(j / tubularSegments);
  16471. }
  16472. }
  16473. for (i = 0; i < radialSegments; i++) {
  16474. for (j = 0; j < tubularSegments; j++) {
  16475. var jNext = (j + 1) % tubularSegments;
  16476. var a = i * tubularSegments + j;
  16477. var b = (i + 1) * tubularSegments + j;
  16478. var c = (i + 1) * tubularSegments + jNext;
  16479. var d = i * tubularSegments + jNext;
  16480. indices.push(d);
  16481. indices.push(b);
  16482. indices.push(a);
  16483. indices.push(d);
  16484. indices.push(c);
  16485. indices.push(b);
  16486. }
  16487. }
  16488. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16489. var vertexData = new BABYLON.VertexData();
  16490. vertexData.indices = indices;
  16491. vertexData.positions = positions;
  16492. vertexData.normals = normals;
  16493. vertexData.uvs = uvs;
  16494. return vertexData;
  16495. };
  16496. VertexData.ComputeNormals = function (positions, indices, normals) {
  16497. var positionVectors = [];
  16498. var facesOfVertices = [];
  16499. var index;
  16500. for (index = 0; index < positions.length; index += 3) {
  16501. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16502. positionVectors.push(vector3);
  16503. facesOfVertices.push([]);
  16504. }
  16505. var facesNormals = [];
  16506. for (index = 0; index < indices.length / 3; index++) {
  16507. var i1 = indices[index * 3];
  16508. var i2 = indices[index * 3 + 1];
  16509. var i3 = indices[index * 3 + 2];
  16510. var p1 = positionVectors[i1];
  16511. var p2 = positionVectors[i2];
  16512. var p3 = positionVectors[i3];
  16513. var p1p2 = p1.subtract(p2);
  16514. var p3p2 = p3.subtract(p2);
  16515. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16516. facesOfVertices[i1].push(index);
  16517. facesOfVertices[i2].push(index);
  16518. facesOfVertices[i3].push(index);
  16519. }
  16520. for (index = 0; index < positionVectors.length; index++) {
  16521. var faces = facesOfVertices[index];
  16522. var normal = BABYLON.Vector3.Zero();
  16523. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16524. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16525. }
  16526. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16527. normals[index * 3] = normal.x;
  16528. normals[index * 3 + 1] = normal.y;
  16529. normals[index * 3 + 2] = normal.z;
  16530. }
  16531. };
  16532. return VertexData;
  16533. })();
  16534. BABYLON.VertexData = VertexData;
  16535. })(BABYLON || (BABYLON = {}));
  16536. var __extends = this.__extends || function (d, b) {
  16537. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16538. function __() { this.constructor = d; }
  16539. __.prototype = b.prototype;
  16540. d.prototype = new __();
  16541. };
  16542. var BABYLON;
  16543. (function (BABYLON) {
  16544. var buildCamera = function (that, name) {
  16545. that._leftCamera.isIntermediate = true;
  16546. that.subCameras.push(that._leftCamera);
  16547. that.subCameras.push(that._rightCamera);
  16548. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16549. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16550. that._anaglyphPostProcess.onApply = function (effect) {
  16551. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16552. };
  16553. that._update();
  16554. };
  16555. var AnaglyphArcRotateCamera = (function (_super) {
  16556. __extends(AnaglyphArcRotateCamera, _super);
  16557. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16558. _super.call(this, name, alpha, beta, radius, target, scene);
  16559. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16560. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16561. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16562. buildCamera(this, name);
  16563. }
  16564. AnaglyphArcRotateCamera.prototype._update = function () {
  16565. this._updateCamera(this._leftCamera);
  16566. this._updateCamera(this._rightCamera);
  16567. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16568. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16569. _super.prototype._update.call(this);
  16570. };
  16571. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16572. camera.beta = this.beta;
  16573. camera.radius = this.radius;
  16574. camera.minZ = this.minZ;
  16575. camera.maxZ = this.maxZ;
  16576. camera.fov = this.fov;
  16577. camera.target = this.target;
  16578. };
  16579. return AnaglyphArcRotateCamera;
  16580. })(BABYLON.ArcRotateCamera);
  16581. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16582. var AnaglyphFreeCamera = (function (_super) {
  16583. __extends(AnaglyphFreeCamera, _super);
  16584. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16585. _super.call(this, name, position, scene);
  16586. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16587. this._transformMatrix = new BABYLON.Matrix();
  16588. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16589. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16590. buildCamera(this, name);
  16591. }
  16592. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16593. var target = this.getTarget();
  16594. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16595. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16596. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16597. };
  16598. AnaglyphFreeCamera.prototype._update = function () {
  16599. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16600. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16601. this._updateCamera(this._leftCamera);
  16602. this._updateCamera(this._rightCamera);
  16603. _super.prototype._update.call(this);
  16604. };
  16605. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16606. camera.minZ = this.minZ;
  16607. camera.maxZ = this.maxZ;
  16608. camera.fov = this.fov;
  16609. camera.viewport = this.viewport;
  16610. camera.setTarget(this.getTarget());
  16611. };
  16612. return AnaglyphFreeCamera;
  16613. })(BABYLON.FreeCamera);
  16614. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16615. })(BABYLON || (BABYLON = {}));
  16616. var __extends = this.__extends || function (d, b) {
  16617. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16618. function __() { this.constructor = d; }
  16619. __.prototype = b.prototype;
  16620. d.prototype = new __();
  16621. };
  16622. var BABYLON;
  16623. (function (BABYLON) {
  16624. var AnaglyphPostProcess = (function (_super) {
  16625. __extends(AnaglyphPostProcess, _super);
  16626. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16627. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16628. }
  16629. return AnaglyphPostProcess;
  16630. })(BABYLON.PostProcess);
  16631. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16632. })(BABYLON || (BABYLON = {}));
  16633. var BABYLON;
  16634. (function (BABYLON) {
  16635. var Tags = (function () {
  16636. function Tags() {
  16637. }
  16638. Tags.EnableFor = function (obj) {
  16639. obj._tags = obj._tags || {};
  16640. obj.hasTags = function () {
  16641. return Tags.HasTags(obj);
  16642. };
  16643. obj.addTags = function (tagsString) {
  16644. return Tags.AddTagsTo(obj, tagsString);
  16645. };
  16646. obj.removeTags = function (tagsString) {
  16647. return Tags.RemoveTagsFrom(obj, tagsString);
  16648. };
  16649. obj.matchesTagsQuery = function (tagsQuery) {
  16650. return Tags.MatchesQuery(obj, tagsQuery);
  16651. };
  16652. };
  16653. Tags.DisableFor = function (obj) {
  16654. delete obj._tags;
  16655. delete obj.hasTags;
  16656. delete obj.addTags;
  16657. delete obj.removeTags;
  16658. delete obj.matchesTagsQuery;
  16659. };
  16660. Tags.HasTags = function (obj) {
  16661. if (!obj._tags) {
  16662. return false;
  16663. }
  16664. return !BABYLON.Tools.IsEmpty(obj._tags);
  16665. };
  16666. Tags.GetTags = function (obj) {
  16667. if (!obj._tags) {
  16668. return null;
  16669. }
  16670. return obj._tags;
  16671. };
  16672. Tags.AddTagsTo = function (obj, tagsString) {
  16673. if (!tagsString) {
  16674. return;
  16675. }
  16676. var tags = tagsString.split(" ");
  16677. for (var t in tags) {
  16678. Tags._AddTagTo(obj, tags[t]);
  16679. }
  16680. };
  16681. Tags._AddTagTo = function (obj, tag) {
  16682. tag = tag.trim();
  16683. if (tag === "" || tag === "true" || tag === "false") {
  16684. return;
  16685. }
  16686. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16687. return;
  16688. }
  16689. Tags.EnableFor(obj);
  16690. obj._tags[tag] = true;
  16691. };
  16692. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16693. if (!Tags.HasTags(obj)) {
  16694. return;
  16695. }
  16696. var tags = tagsString.split(" ");
  16697. for (var t in tags) {
  16698. Tags._RemoveTagFrom(obj, tags[t]);
  16699. }
  16700. };
  16701. Tags._RemoveTagFrom = function (obj, tag) {
  16702. delete obj._tags[tag];
  16703. };
  16704. Tags.MatchesQuery = function (obj, tagsQuery) {
  16705. if (tagsQuery === undefined) {
  16706. return true;
  16707. }
  16708. if (tagsQuery === "") {
  16709. return Tags.HasTags(obj);
  16710. }
  16711. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16712. return Tags.HasTags(obj) && obj._tags[r];
  16713. });
  16714. };
  16715. return Tags;
  16716. })();
  16717. BABYLON.Tags = Tags;
  16718. })(BABYLON || (BABYLON = {}));
  16719. var BABYLON;
  16720. (function (BABYLON) {
  16721. (function (Internals) {
  16722. var AndOrNotEvaluator = (function () {
  16723. function AndOrNotEvaluator() {
  16724. }
  16725. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16726. if (!query.match(/\([^\(\)]*\)/g)) {
  16727. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16728. } else {
  16729. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16730. r = r.slice(1, r.length - 1);
  16731. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16732. });
  16733. }
  16734. if (query === "true") {
  16735. return true;
  16736. }
  16737. if (query === "false") {
  16738. return false;
  16739. }
  16740. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16741. };
  16742. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16743. evaluateCallback = evaluateCallback || (function (r) {
  16744. return r === "true" ? true : false;
  16745. });
  16746. var result;
  16747. var or = parenthesisContent.split("||");
  16748. for (var i in or) {
  16749. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16750. var and = ori.split("&&");
  16751. if (and.length > 1) {
  16752. for (var j = 0; j < and.length; ++j) {
  16753. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16754. if (andj !== "true" && andj !== "false") {
  16755. if (andj[0] === "!") {
  16756. result = !evaluateCallback(andj.substring(1));
  16757. } else {
  16758. result = evaluateCallback(andj);
  16759. }
  16760. } else {
  16761. result = andj === "true" ? true : false;
  16762. }
  16763. if (!result) {
  16764. ori = "false";
  16765. break;
  16766. }
  16767. }
  16768. }
  16769. if (result || ori === "true") {
  16770. result = true;
  16771. break;
  16772. }
  16773. if (ori !== "true" && ori !== "false") {
  16774. if (ori[0] === "!") {
  16775. result = !evaluateCallback(ori.substring(1));
  16776. } else {
  16777. result = evaluateCallback(ori);
  16778. }
  16779. } else {
  16780. result = ori === "true" ? true : false;
  16781. }
  16782. }
  16783. return result ? "true" : "false";
  16784. };
  16785. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16786. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16787. r = r.replace(/[\s]/g, function () {
  16788. return "";
  16789. });
  16790. return r.length % 2 ? "!" : "";
  16791. });
  16792. booleanString = booleanString.trim();
  16793. if (booleanString === "!true") {
  16794. booleanString = "false";
  16795. } else if (booleanString === "!false") {
  16796. booleanString = "true";
  16797. }
  16798. return booleanString;
  16799. };
  16800. return AndOrNotEvaluator;
  16801. })();
  16802. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16803. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16804. var Internals = BABYLON.Internals;
  16805. })(BABYLON || (BABYLON = {}));
  16806. var BABYLON;
  16807. (function (BABYLON) {
  16808. var PostProcessRenderPass = (function () {
  16809. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16810. this._enabled = true;
  16811. this._refCount = 0;
  16812. this._name = name;
  16813. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16814. this.setRenderList(renderList);
  16815. this._renderTexture.onBeforeRender = beforeRender;
  16816. this._renderTexture.onAfterRender = afterRender;
  16817. this._scene = scene;
  16818. }
  16819. PostProcessRenderPass.prototype._incRefCount = function () {
  16820. if (this._refCount === 0) {
  16821. this._scene.customRenderTargets.push(this._renderTexture);
  16822. }
  16823. return ++this._refCount;
  16824. };
  16825. PostProcessRenderPass.prototype._decRefCount = function () {
  16826. this._refCount--;
  16827. if (this._refCount <= 0) {
  16828. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16829. }
  16830. return this._refCount;
  16831. };
  16832. PostProcessRenderPass.prototype._update = function () {
  16833. this.setRenderList(this._renderList);
  16834. };
  16835. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16836. this._renderTexture.renderList = renderList;
  16837. };
  16838. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16839. return this._renderTexture;
  16840. };
  16841. return PostProcessRenderPass;
  16842. })();
  16843. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16844. })(BABYLON || (BABYLON = {}));
  16845. var BABYLON;
  16846. (function (BABYLON) {
  16847. var PostProcessRenderEffect = (function () {
  16848. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16849. this._engine = engine;
  16850. this._name = name;
  16851. this._postProcessType = postProcessType;
  16852. this._ratio = ratio || 1.0;
  16853. this._samplingMode = samplingMode || null;
  16854. this._singleInstance = singleInstance || true;
  16855. this._cameras = [];
  16856. this._postProcesses = [];
  16857. this._indicesForCamera = [];
  16858. this._renderPasses = [];
  16859. this._renderEffectAsPasses = [];
  16860. this.parameters = function (effect) {
  16861. };
  16862. }
  16863. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  16864. var postProcess;
  16865. var instance;
  16866. var args = [];
  16867. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  16868. for (var i = 0; i < parameters.length; i++) {
  16869. switch (parameters[i]) {
  16870. case "name":
  16871. args[i] = postProcessType.toString();
  16872. break;
  16873. case "ratio":
  16874. args[i] = ratio;
  16875. break;
  16876. case "camera":
  16877. args[i] = null;
  16878. break;
  16879. case "samplingMode":
  16880. args[i] = samplingMode;
  16881. break;
  16882. case "engine":
  16883. args[i] = engine;
  16884. break;
  16885. case "reusable":
  16886. args[i] = true;
  16887. break;
  16888. default:
  16889. args[i] = null;
  16890. break;
  16891. }
  16892. }
  16893. postProcess = function () {
  16894. };
  16895. postProcess.prototype = postProcessType.prototype;
  16896. instance = new postProcess();
  16897. postProcessType.apply(instance, args);
  16898. return instance;
  16899. };
  16900. PostProcessRenderEffect._GetParametersNames = function (func) {
  16901. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  16902. var functWithoutComments = func.toString().replace(commentsRegex, '');
  16903. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  16904. if (parameters === null)
  16905. parameters = [];
  16906. return parameters;
  16907. };
  16908. PostProcessRenderEffect.prototype._update = function () {
  16909. for (var renderPassName in this._renderPasses) {
  16910. this._renderPasses[renderPassName]._update();
  16911. }
  16912. };
  16913. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  16914. this._renderPasses[renderPass._name] = renderPass;
  16915. this._linkParameters();
  16916. };
  16917. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  16918. delete this._renderPasses[renderPass._name];
  16919. this._linkParameters();
  16920. };
  16921. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  16922. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  16923. this._linkParameters();
  16924. };
  16925. PostProcessRenderEffect.prototype.getPass = function (passName) {
  16926. for (var renderPassName in this._renderPasses) {
  16927. if (renderPassName === passName) {
  16928. return this._renderPasses[passName];
  16929. }
  16930. }
  16931. };
  16932. PostProcessRenderEffect.prototype.emptyPasses = function () {
  16933. this._renderPasses.length = 0;
  16934. this._linkParameters();
  16935. };
  16936. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  16937. var cameraKey;
  16938. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16939. for (var i = 0; i < _cam.length; i++) {
  16940. var camera = _cam[i];
  16941. var cameraName = camera.name;
  16942. if (this._singleInstance) {
  16943. cameraKey = 0;
  16944. } else {
  16945. cameraKey = cameraName;
  16946. }
  16947. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  16948. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  16949. if (this._indicesForCamera[cameraName] === null) {
  16950. this._indicesForCamera[cameraName] = [];
  16951. }
  16952. this._indicesForCamera[cameraName].push(index);
  16953. if (this._cameras.indexOf(camera) === -1) {
  16954. this._cameras[cameraName] = camera;
  16955. }
  16956. for (var passName in this._renderPasses) {
  16957. this._renderPasses[passName]._incRefCount();
  16958. }
  16959. }
  16960. this._linkParameters();
  16961. };
  16962. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  16963. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16964. for (var i = 0; i < _cam.length; i++) {
  16965. var camera = _cam[i];
  16966. var cameraName = camera.name;
  16967. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16968. var index = this._cameras.indexOf(cameraName);
  16969. this._indicesForCamera.splice(index, 1);
  16970. this._cameras.splice(index, 1);
  16971. for (var passName in this._renderPasses) {
  16972. this._renderPasses[passName]._decRefCount();
  16973. }
  16974. }
  16975. };
  16976. PostProcessRenderEffect.prototype._enable = function (cameras) {
  16977. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16978. for (var i = 0; i < _cam.length; i++) {
  16979. var camera = _cam[i];
  16980. var cameraName = camera.name;
  16981. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  16982. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  16983. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  16984. }
  16985. }
  16986. for (var passName in this._renderPasses) {
  16987. this._renderPasses[passName]._incRefCount();
  16988. }
  16989. }
  16990. };
  16991. PostProcessRenderEffect.prototype._disable = function (cameras) {
  16992. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16993. for (var i = 0; i < _cam.length; i++) {
  16994. var camera = _cam[i];
  16995. var cameraName = camera.Name;
  16996. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16997. for (var passName in this._renderPasses) {
  16998. this._renderPasses[passName]._decRefCount();
  16999. }
  17000. }
  17001. };
  17002. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17003. if (this._singleInstance) {
  17004. return this._postProcesses[0];
  17005. } else {
  17006. return this._postProcesses[camera.name];
  17007. }
  17008. };
  17009. PostProcessRenderEffect.prototype._linkParameters = function () {
  17010. var _this = this;
  17011. for (var index in this._postProcesses) {
  17012. this._postProcesses[index].onApply = function (effect) {
  17013. _this.parameters(effect);
  17014. _this._linkTextures(effect);
  17015. };
  17016. }
  17017. };
  17018. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17019. for (var renderPassName in this._renderPasses) {
  17020. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17021. }
  17022. for (var renderEffectName in this._renderEffectAsPasses) {
  17023. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17024. }
  17025. };
  17026. return PostProcessRenderEffect;
  17027. })();
  17028. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17029. })(BABYLON || (BABYLON = {}));
  17030. var BABYLON;
  17031. (function (BABYLON) {
  17032. var PostProcessRenderPipeline = (function () {
  17033. function PostProcessRenderPipeline(engine, name) {
  17034. this._engine = engine;
  17035. this._name = name;
  17036. this._renderEffects = [];
  17037. this._renderEffectsForIsolatedPass = [];
  17038. this._cameras = [];
  17039. }
  17040. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17041. this._renderEffects[renderEffect._name] = renderEffect;
  17042. };
  17043. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17044. var renderEffects = this._renderEffects[renderEffectName];
  17045. if (!renderEffects) {
  17046. return;
  17047. }
  17048. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17049. };
  17050. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17051. var renderEffects = this._renderEffects[renderEffectName];
  17052. if (!renderEffects) {
  17053. return;
  17054. }
  17055. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17056. };
  17057. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17058. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17059. var indicesToDelete = [];
  17060. for (var i = 0; i < _cam.length; i++) {
  17061. var camera = _cam[i];
  17062. var cameraName = camera.name;
  17063. if (this._cameras.indexOf(camera) === -1) {
  17064. this._cameras[cameraName] = camera;
  17065. } else if (unique) {
  17066. indicesToDelete.push(i);
  17067. }
  17068. }
  17069. for (var i = 0; i < indicesToDelete.length; i++) {
  17070. cameras.splice(indicesToDelete[i], 1);
  17071. }
  17072. for (var renderEffectName in this._renderEffects) {
  17073. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17074. }
  17075. };
  17076. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17077. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17078. for (var renderEffectName in this._renderEffects) {
  17079. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17080. }
  17081. for (var i = 0; i < _cam.length; i++) {
  17082. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17083. }
  17084. };
  17085. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17086. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17087. var pass = null;
  17088. for (var renderEffectName in this._renderEffects) {
  17089. pass = this._renderEffects[renderEffectName].getPass(passName);
  17090. if (pass != null) {
  17091. break;
  17092. }
  17093. }
  17094. if (pass === null) {
  17095. return;
  17096. }
  17097. for (var renderEffectName in this._renderEffects) {
  17098. this._renderEffects[renderEffectName]._disable(_cam);
  17099. }
  17100. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17101. for (var i = 0; i < _cam.length; i++) {
  17102. var camera = _cam[i];
  17103. var cameraName = camera.name;
  17104. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17105. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17106. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17107. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17108. }
  17109. };
  17110. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17111. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17112. for (var i = 0; i < _cam.length; i++) {
  17113. var camera = _cam[i];
  17114. var cameraName = camera.name;
  17115. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17116. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17117. }
  17118. for (var renderEffectName in this._renderEffects) {
  17119. this._renderEffects[renderEffectName]._enable(_cam);
  17120. }
  17121. };
  17122. PostProcessRenderPipeline.prototype._update = function () {
  17123. for (var renderEffectName in this._renderEffects) {
  17124. this._renderEffects[renderEffectName]._update();
  17125. }
  17126. for (var i = 0; i < this._cameras.length; i++) {
  17127. var cameraName = this._cameras[i].name;
  17128. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17129. this._renderEffectsForIsolatedPass[cameraName]._update();
  17130. }
  17131. }
  17132. };
  17133. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17134. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17135. return PostProcessRenderPipeline;
  17136. })();
  17137. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17138. })(BABYLON || (BABYLON = {}));
  17139. var BABYLON;
  17140. (function (BABYLON) {
  17141. var PostProcessRenderPipelineManager = (function () {
  17142. function PostProcessRenderPipelineManager() {
  17143. this._renderPipelines = [];
  17144. }
  17145. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17146. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17147. };
  17148. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17149. var renderPipeline = this._renderPipelines[renderPipelineName];
  17150. if (!renderPipeline) {
  17151. return;
  17152. }
  17153. renderPipeline.attachCameras(cameras, unique);
  17154. };
  17155. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17156. var renderPipeline = this._renderPipelines[renderPipelineName];
  17157. if (!renderPipeline) {
  17158. return;
  17159. }
  17160. renderPipeline.detachCameras(cameras);
  17161. };
  17162. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17163. var renderPipeline = this._renderPipelines[renderPipelineName];
  17164. if (!renderPipeline) {
  17165. return;
  17166. }
  17167. renderPipeline.enableEffect(renderEffectName, cameras);
  17168. };
  17169. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17170. var renderPipeline = this._renderPipelines[renderPipelineName];
  17171. if (!renderPipeline) {
  17172. return;
  17173. }
  17174. renderPipeline.disableEffect(renderEffectName, cameras);
  17175. };
  17176. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17177. var renderPipeline = this._renderPipelines[renderPipelineName];
  17178. if (!renderPipeline) {
  17179. return;
  17180. }
  17181. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17182. };
  17183. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17184. var renderPipeline = this._renderPipelines[renderPipelineName];
  17185. if (!renderPipeline) {
  17186. return;
  17187. }
  17188. renderPipeline.disableDisplayOnlyPass(cameras);
  17189. };
  17190. PostProcessRenderPipelineManager.prototype.update = function () {
  17191. for (var renderPipelineName in this._renderPipelines) {
  17192. this._renderPipelines[renderPipelineName]._update();
  17193. }
  17194. };
  17195. return PostProcessRenderPipelineManager;
  17196. })();
  17197. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17198. })(BABYLON || (BABYLON = {}));
  17199. var __extends = this.__extends || function (d, b) {
  17200. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17201. function __() { this.constructor = d; }
  17202. __.prototype = b.prototype;
  17203. d.prototype = new __();
  17204. };
  17205. var BABYLON;
  17206. (function (BABYLON) {
  17207. var DisplayPassPostProcess = (function (_super) {
  17208. __extends(DisplayPassPostProcess, _super);
  17209. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17210. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17211. }
  17212. return DisplayPassPostProcess;
  17213. })(BABYLON.PostProcess);
  17214. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17215. })(BABYLON || (BABYLON = {}));
  17216. var BABYLON;
  17217. (function (BABYLON) {
  17218. var BoundingBoxRenderer = (function () {
  17219. function BoundingBoxRenderer(scene) {
  17220. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17221. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17222. this.showBackLines = true;
  17223. this.renderList = new BABYLON.SmartArray(32);
  17224. this._scene = scene;
  17225. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17226. attributes: ["position"],
  17227. uniforms: ["worldViewProjection", "color"]
  17228. });
  17229. var engine = this._scene.getEngine();
  17230. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17231. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17232. 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]);
  17233. }
  17234. BoundingBoxRenderer.prototype.reset = function () {
  17235. this.renderList.reset();
  17236. };
  17237. BoundingBoxRenderer.prototype.render = function () {
  17238. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17239. return;
  17240. }
  17241. var engine = this._scene.getEngine();
  17242. engine.setDepthWrite(false);
  17243. this._colorShader._preBind();
  17244. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17245. var boundingBox = this.renderList.data[boundingBoxIndex];
  17246. var min = boundingBox.minimum;
  17247. var max = boundingBox.maximum;
  17248. var diff = max.subtract(min);
  17249. var median = min.add(diff.scale(0.5));
  17250. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17251. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17252. if (this.showBackLines) {
  17253. engine.setDepthFunctionToGreaterOrEqual();
  17254. this._colorShader.setColor4("color", this.backColor.toColor4());
  17255. this._colorShader.bind(worldMatrix);
  17256. engine.draw(false, 0, 24);
  17257. }
  17258. engine.setDepthFunctionToLess();
  17259. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17260. this._colorShader.bind(worldMatrix);
  17261. engine.draw(false, 0, 24);
  17262. }
  17263. this._colorShader.unbind();
  17264. engine.setDepthFunctionToLessOrEqual();
  17265. engine.setDepthWrite(true);
  17266. };
  17267. BoundingBoxRenderer.prototype.dispose = function () {
  17268. this._colorShader.dispose();
  17269. this._vb.dispose();
  17270. this._scene.getEngine()._releaseBuffer(this._ib);
  17271. };
  17272. return BoundingBoxRenderer;
  17273. })();
  17274. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17275. })(BABYLON || (BABYLON = {}));
  17276. /**
  17277. * Based on jsTGALoader - Javascript loader for TGA file
  17278. * By Vincent Thibault
  17279. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17280. */
  17281. var BABYLON;
  17282. (function (BABYLON) {
  17283. (function (Internals) {
  17284. var TGATools = (function () {
  17285. function TGATools() {
  17286. }
  17287. TGATools.GetTGAHeader = function (data) {
  17288. var offset = 0;
  17289. var header = {
  17290. id_length: data[offset++],
  17291. colormap_type: data[offset++],
  17292. image_type: data[offset++],
  17293. colormap_index: data[offset++] | data[offset++] << 8,
  17294. colormap_length: data[offset++] | data[offset++] << 8,
  17295. colormap_size: data[offset++],
  17296. origin: [
  17297. data[offset++] | data[offset++] << 8,
  17298. data[offset++] | data[offset++] << 8
  17299. ],
  17300. width: data[offset++] | data[offset++] << 8,
  17301. height: data[offset++] | data[offset++] << 8,
  17302. pixel_size: data[offset++],
  17303. flags: data[offset++]
  17304. };
  17305. return header;
  17306. };
  17307. TGATools.UploadContent = function (gl, data) {
  17308. if (data.length < 19) {
  17309. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17310. return;
  17311. }
  17312. var offset = 18;
  17313. var header = TGATools.GetTGAHeader(data);
  17314. if (header.id_length + offset > data.length) {
  17315. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17316. return;
  17317. }
  17318. offset += header.id_length;
  17319. var use_rle = false;
  17320. var use_pal = false;
  17321. var use_rgb = false;
  17322. var use_grey = false;
  17323. switch (header.image_type) {
  17324. case TGATools._TYPE_RLE_INDEXED:
  17325. use_rle = true;
  17326. case TGATools._TYPE_INDEXED:
  17327. use_pal = true;
  17328. break;
  17329. case TGATools._TYPE_RLE_RGB:
  17330. use_rle = true;
  17331. case TGATools._TYPE_RGB:
  17332. use_rgb = true;
  17333. break;
  17334. case TGATools._TYPE_RLE_GREY:
  17335. use_rle = true;
  17336. case TGATools._TYPE_GREY:
  17337. use_grey = true;
  17338. break;
  17339. }
  17340. var pixel_data;
  17341. var numAlphaBits = header.flags & 0xf;
  17342. var pixel_size = header.pixel_size >> 3;
  17343. var pixel_total = header.width * header.height * pixel_size;
  17344. var palettes;
  17345. if (use_pal) {
  17346. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17347. }
  17348. if (use_rle) {
  17349. pixel_data = new Uint8Array(pixel_total);
  17350. var c, count, i;
  17351. var localOffset = 0;
  17352. var pixels = new Uint8Array(pixel_size);
  17353. while (offset < pixel_total && localOffset < pixel_total) {
  17354. c = data[offset++];
  17355. count = (c & 0x7f) + 1;
  17356. if (c & 0x80) {
  17357. for (i = 0; i < pixel_size; ++i) {
  17358. pixels[i] = data[offset++];
  17359. }
  17360. for (i = 0; i < count; ++i) {
  17361. pixel_data.set(pixels, localOffset + i * pixel_size);
  17362. }
  17363. localOffset += pixel_size * count;
  17364. } else {
  17365. count *= pixel_size;
  17366. for (i = 0; i < count; ++i) {
  17367. pixel_data[localOffset + i] = data[offset++];
  17368. }
  17369. localOffset += count;
  17370. }
  17371. }
  17372. } else {
  17373. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17374. }
  17375. var x_start, y_start, x_step, y_step, y_end, x_end;
  17376. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17377. default:
  17378. case TGATools._ORIGIN_UL:
  17379. x_start = 0;
  17380. x_step = 1;
  17381. x_end = header.width;
  17382. y_start = 0;
  17383. y_step = 1;
  17384. y_end = header.height;
  17385. break;
  17386. case TGATools._ORIGIN_BL:
  17387. x_start = 0;
  17388. x_step = 1;
  17389. x_end = header.width;
  17390. y_start = header.height - 1;
  17391. y_step = -1;
  17392. y_end = -1;
  17393. break;
  17394. case TGATools._ORIGIN_UR:
  17395. x_start = header.width - 1;
  17396. x_step = -1;
  17397. x_end = -1;
  17398. y_start = 0;
  17399. y_step = 1;
  17400. y_end = header.height;
  17401. break;
  17402. case TGATools._ORIGIN_BR:
  17403. x_start = header.width - 1;
  17404. x_step = -1;
  17405. x_end = -1;
  17406. y_start = header.height - 1;
  17407. y_step = -1;
  17408. y_end = -1;
  17409. break;
  17410. }
  17411. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17412. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17413. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17414. };
  17415. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17416. var image = pixel_data, colormap = palettes;
  17417. var width = header.width, height = header.height;
  17418. var color, i = 0, x, y;
  17419. var imageData = new Uint8Array(width * height * 4);
  17420. for (y = y_start; y !== y_end; y += y_step) {
  17421. for (x = x_start; x !== x_end; x += x_step, i++) {
  17422. color = image[i];
  17423. imageData[(x + width * y) * 4 + 3] = 255;
  17424. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17425. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17426. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17427. }
  17428. }
  17429. return imageData;
  17430. };
  17431. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17432. var image = pixel_data;
  17433. var width = header.width, height = header.height;
  17434. var color, i = 0, x, y;
  17435. var imageData = new Uint8Array(width * height * 4);
  17436. for (y = y_start; y !== y_end; y += y_step) {
  17437. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17438. color = image[i + 0] + (image[i + 1] << 8);
  17439. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17440. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17441. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17442. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17443. }
  17444. }
  17445. return imageData;
  17446. };
  17447. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17448. var image = pixel_data;
  17449. var width = header.width, height = header.height;
  17450. var i = 0, x, y;
  17451. var imageData = new Uint8Array(width * height * 4);
  17452. for (y = y_start; y !== y_end; y += y_step) {
  17453. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17454. imageData[(x + width * y) * 4 + 3] = 255;
  17455. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17456. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17457. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17458. }
  17459. }
  17460. return imageData;
  17461. };
  17462. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17463. var image = pixel_data;
  17464. var width = header.width, height = header.height;
  17465. var i = 0, x, y;
  17466. var imageData = new Uint8Array(width * height * 4);
  17467. for (y = y_start; y !== y_end; y += y_step) {
  17468. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17469. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17470. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17471. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17472. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17473. }
  17474. }
  17475. return imageData;
  17476. };
  17477. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17478. var image = pixel_data;
  17479. var width = header.width, height = header.height;
  17480. var color, i = 0, x, y;
  17481. var imageData = new Uint8Array(width * height * 4);
  17482. for (y = y_start; y !== y_end; y += y_step) {
  17483. for (x = x_start; x !== x_end; x += x_step, i++) {
  17484. color = image[i];
  17485. imageData[(x + width * y) * 4 + 0] = color;
  17486. imageData[(x + width * y) * 4 + 1] = color;
  17487. imageData[(x + width * y) * 4 + 2] = color;
  17488. imageData[(x + width * y) * 4 + 3] = 255;
  17489. }
  17490. }
  17491. return imageData;
  17492. };
  17493. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17494. var image = pixel_data;
  17495. var width = header.width, height = header.height;
  17496. var i = 0, x, y;
  17497. var imageData = new Uint8Array(width * height * 4);
  17498. for (y = y_start; y !== y_end; y += y_step) {
  17499. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17500. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17501. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17502. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17503. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17504. }
  17505. }
  17506. return imageData;
  17507. };
  17508. TGATools._TYPE_NO_DATA = 0;
  17509. TGATools._TYPE_INDEXED = 1;
  17510. TGATools._TYPE_RGB = 2;
  17511. TGATools._TYPE_GREY = 3;
  17512. TGATools._TYPE_RLE_INDEXED = 9;
  17513. TGATools._TYPE_RLE_RGB = 10;
  17514. TGATools._TYPE_RLE_GREY = 11;
  17515. TGATools._ORIGIN_MASK = 0x30;
  17516. TGATools._ORIGIN_SHIFT = 0x04;
  17517. TGATools._ORIGIN_BL = 0x00;
  17518. TGATools._ORIGIN_BR = 0x01;
  17519. TGATools._ORIGIN_UL = 0x02;
  17520. TGATools._ORIGIN_UR = 0x03;
  17521. return TGATools;
  17522. })();
  17523. Internals.TGATools = TGATools;
  17524. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17525. var Internals = BABYLON.Internals;
  17526. })(BABYLON || (BABYLON = {}));
  17527. var BABYLON;
  17528. (function (BABYLON) {
  17529. (function (Internals) {
  17530. var DDS_MAGIC = 0x20534444;
  17531. 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;
  17532. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17533. 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;
  17534. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17535. function FourCCToInt32(value) {
  17536. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17537. }
  17538. function Int32ToFourCC(value) {
  17539. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17540. }
  17541. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17542. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17543. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17544. var headerLengthInt = 31;
  17545. var off_magic = 0;
  17546. var off_size = 1;
  17547. var off_flags = 2;
  17548. var off_height = 3;
  17549. var off_width = 4;
  17550. var off_mipmapCount = 7;
  17551. var off_pfFlags = 20;
  17552. var off_pfFourCC = 21;
  17553. var off_RGBbpp = 22;
  17554. var off_RMask = 23;
  17555. var off_GMask = 24;
  17556. var off_BMask = 25;
  17557. var off_AMask = 26;
  17558. var off_caps1 = 27;
  17559. var off_caps2 = 28;
  17560. ;
  17561. var DDSTools = (function () {
  17562. function DDSTools() {
  17563. }
  17564. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17565. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17566. var mipmapCount = 1;
  17567. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17568. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17569. }
  17570. return {
  17571. width: header[off_width],
  17572. height: header[off_height],
  17573. mipmapCount: mipmapCount,
  17574. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17575. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17576. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17577. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17578. };
  17579. };
  17580. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17581. var byteArray = new Uint8Array(dataLength);
  17582. var srcData = new Uint8Array(arrayBuffer);
  17583. var index = 0;
  17584. for (var y = height - 1; y >= 0; y--) {
  17585. for (var x = 0; x < width; x++) {
  17586. var srcPos = dataOffset + (x + y * width) * 4;
  17587. byteArray[index + 2] = srcData[srcPos];
  17588. byteArray[index + 1] = srcData[srcPos + 1];
  17589. byteArray[index] = srcData[srcPos + 2];
  17590. byteArray[index + 3] = srcData[srcPos + 3];
  17591. index += 4;
  17592. }
  17593. }
  17594. return byteArray;
  17595. };
  17596. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17597. var byteArray = new Uint8Array(dataLength);
  17598. var srcData = new Uint8Array(arrayBuffer);
  17599. var index = 0;
  17600. for (var y = height - 1; y >= 0; y--) {
  17601. for (var x = 0; x < width; x++) {
  17602. var srcPos = dataOffset + (x + y * width) * 3;
  17603. byteArray[index + 2] = srcData[srcPos];
  17604. byteArray[index + 1] = srcData[srcPos + 1];
  17605. byteArray[index] = srcData[srcPos + 2];
  17606. index += 3;
  17607. }
  17608. }
  17609. return byteArray;
  17610. };
  17611. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17612. var byteArray = new Uint8Array(dataLength);
  17613. var srcData = new Uint8Array(arrayBuffer);
  17614. var index = 0;
  17615. for (var y = height - 1; y >= 0; y--) {
  17616. for (var x = 0; x < width; x++) {
  17617. var srcPos = dataOffset + (x + y * width);
  17618. byteArray[index] = srcData[srcPos];
  17619. index++;
  17620. }
  17621. }
  17622. return byteArray;
  17623. };
  17624. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17625. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17626. if (header[off_magic] != DDS_MAGIC) {
  17627. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17628. return;
  17629. }
  17630. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17631. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17632. return;
  17633. }
  17634. if (info.isFourCC) {
  17635. fourCC = header[off_pfFourCC];
  17636. switch (fourCC) {
  17637. case FOURCC_DXT1:
  17638. blockBytes = 8;
  17639. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17640. break;
  17641. case FOURCC_DXT3:
  17642. blockBytes = 16;
  17643. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17644. break;
  17645. case FOURCC_DXT5:
  17646. blockBytes = 16;
  17647. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17648. break;
  17649. default:
  17650. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17651. return;
  17652. }
  17653. }
  17654. mipmapCount = 1;
  17655. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17656. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17657. }
  17658. var bpp = header[off_RGBbpp];
  17659. for (var face = 0; face < faces; face++) {
  17660. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17661. width = header[off_width];
  17662. height = header[off_height];
  17663. dataOffset = header[off_size] + 4;
  17664. for (i = 0; i < mipmapCount; ++i) {
  17665. if (info.isRGB) {
  17666. if (bpp == 24) {
  17667. dataLength = width * height * 3;
  17668. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17669. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17670. } else {
  17671. dataLength = width * height * 4;
  17672. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17673. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17674. }
  17675. } else if (info.isLuminance) {
  17676. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17677. var unpaddedRowSize = width;
  17678. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17679. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17680. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17681. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17682. } else {
  17683. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17684. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17685. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17686. }
  17687. dataOffset += dataLength;
  17688. width *= 0.5;
  17689. height *= 0.5;
  17690. width = Math.max(1.0, width);
  17691. height = Math.max(1.0, height);
  17692. }
  17693. }
  17694. };
  17695. return DDSTools;
  17696. })();
  17697. Internals.DDSTools = DDSTools;
  17698. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17699. var Internals = BABYLON.Internals;
  17700. })(BABYLON || (BABYLON = {}));
  17701. var BABYLON;
  17702. (function (BABYLON) {
  17703. var SmartArray = (function () {
  17704. function SmartArray(capacity) {
  17705. this.length = 0;
  17706. this._duplicateId = 0;
  17707. this.data = new Array(capacity);
  17708. this._id = SmartArray._GlobalId++;
  17709. }
  17710. SmartArray.prototype.push = function (value) {
  17711. this.data[this.length++] = value;
  17712. if (this.length > this.data.length) {
  17713. this.data.length *= 2;
  17714. }
  17715. if (!value.__smartArrayFlags) {
  17716. value.__smartArrayFlags = {};
  17717. }
  17718. value.__smartArrayFlags[this._id] = this._duplicateId;
  17719. };
  17720. SmartArray.prototype.pushNoDuplicate = function (value) {
  17721. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17722. return;
  17723. }
  17724. this.push(value);
  17725. };
  17726. SmartArray.prototype.sort = function (compareFn) {
  17727. this.data.sort(compareFn);
  17728. };
  17729. SmartArray.prototype.reset = function () {
  17730. this.length = 0;
  17731. this._duplicateId++;
  17732. };
  17733. SmartArray.prototype.concat = function (array) {
  17734. if (array.length === 0) {
  17735. return;
  17736. }
  17737. if (this.length + array.length > this.data.length) {
  17738. this.data.length = (this.length + array.length) * 2;
  17739. }
  17740. for (var index = 0; index < array.length; index++) {
  17741. this.data[this.length++] = (array.data || array)[index];
  17742. }
  17743. };
  17744. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17745. if (array.length === 0) {
  17746. return;
  17747. }
  17748. if (this.length + array.length > this.data.length) {
  17749. this.data.length = (this.length + array.length) * 2;
  17750. }
  17751. for (var index = 0; index < array.length; index++) {
  17752. var item = (array.data || array)[index];
  17753. this.pushNoDuplicate(item);
  17754. }
  17755. };
  17756. SmartArray.prototype.indexOf = function (value) {
  17757. var position = this.data.indexOf(value);
  17758. if (position >= this.length) {
  17759. return -1;
  17760. }
  17761. return position;
  17762. };
  17763. SmartArray._GlobalId = 0;
  17764. return SmartArray;
  17765. })();
  17766. BABYLON.SmartArray = SmartArray;
  17767. })(BABYLON || (BABYLON = {}));
  17768. var BABYLON;
  17769. (function (BABYLON) {
  17770. var CannonJSPlugin = (function () {
  17771. function CannonJSPlugin() {
  17772. this._registeredMeshes = [];
  17773. this._physicsMaterials = [];
  17774. this.updateBodyPosition = function (mesh) {
  17775. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17776. var registeredMesh = this._registeredMeshes[index];
  17777. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17778. var body = registeredMesh.body.body;
  17779. var center = mesh.getBoundingInfo().boundingBox.center;
  17780. body.position.set(center.x, center.z, center.y);
  17781. body.quaternion.x = mesh.rotationQuaternion.x;
  17782. body.quaternion.z = mesh.rotationQuaternion.y;
  17783. body.quaternion.y = mesh.rotationQuaternion.z;
  17784. body.quaternion.w = -mesh.rotationQuaternion.w;
  17785. return;
  17786. }
  17787. }
  17788. };
  17789. }
  17790. CannonJSPlugin.prototype.initialize = function (iterations) {
  17791. if (typeof iterations === "undefined") { iterations = 10; }
  17792. this._world = new CANNON.World();
  17793. this._world.broadphase = new CANNON.NaiveBroadphase();
  17794. this._world.solver.iterations = iterations;
  17795. };
  17796. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17797. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17798. };
  17799. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17800. this._world.step(delta);
  17801. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17802. var registeredMesh = this._registeredMeshes[index];
  17803. if (registeredMesh.isChild) {
  17804. continue;
  17805. }
  17806. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17807. var deltaPos = registeredMesh.delta;
  17808. if (deltaPos) {
  17809. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17810. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17811. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17812. } else {
  17813. registeredMesh.mesh.position.x = bodyX;
  17814. registeredMesh.mesh.position.y = bodyZ;
  17815. registeredMesh.mesh.position.z = bodyY;
  17816. }
  17817. if (!registeredMesh.mesh.rotationQuaternion) {
  17818. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17819. }
  17820. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17821. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17822. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17823. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17824. }
  17825. };
  17826. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17827. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17828. };
  17829. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17830. this.unregisterMesh(mesh);
  17831. mesh.computeWorldMatrix(true);
  17832. switch (impostor) {
  17833. case BABYLON.PhysicsEngine.SphereImpostor:
  17834. var bbox = mesh.getBoundingInfo().boundingBox;
  17835. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17836. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17837. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17838. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17839. case BABYLON.PhysicsEngine.BoxImpostor:
  17840. bbox = mesh.getBoundingInfo().boundingBox;
  17841. var min = bbox.minimumWorld;
  17842. var max = bbox.maximumWorld;
  17843. var box = max.subtract(min).scale(0.5);
  17844. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17845. case BABYLON.PhysicsEngine.PlaneImpostor:
  17846. return this._createPlane(mesh, options);
  17847. case BABYLON.PhysicsEngine.MeshImpostor:
  17848. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17849. var rawFaces = mesh.getIndices();
  17850. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17851. }
  17852. return null;
  17853. };
  17854. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17855. var shape = new CANNON.Sphere(radius);
  17856. if (!options) {
  17857. return shape;
  17858. }
  17859. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17860. };
  17861. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  17862. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  17863. if (!options) {
  17864. return shape;
  17865. }
  17866. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17867. };
  17868. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  17869. var shape = new CANNON.Plane();
  17870. if (!options) {
  17871. return shape;
  17872. }
  17873. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17874. };
  17875. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  17876. var verts = [], faces = [];
  17877. mesh.computeWorldMatrix(true);
  17878. for (var i = 0; i < rawVerts.length; i += 3) {
  17879. var transformed = BABYLON.Vector3.Zero();
  17880. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  17881. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  17882. }
  17883. for (var j = 0; j < rawFaces.length; j += 3) {
  17884. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  17885. }
  17886. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  17887. if (!options) {
  17888. return shape;
  17889. }
  17890. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17891. };
  17892. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  17893. var index;
  17894. var mat;
  17895. for (index = 0; index < this._physicsMaterials.length; index++) {
  17896. mat = this._physicsMaterials[index];
  17897. if (mat.friction === friction && mat.restitution === restitution) {
  17898. return mat;
  17899. }
  17900. }
  17901. var currentMat = new CANNON.Material();
  17902. currentMat.friction = friction;
  17903. currentMat.restitution = restitution;
  17904. this._physicsMaterials.push(currentMat);
  17905. for (index = 0; index < this._physicsMaterials.length; index++) {
  17906. mat = this._physicsMaterials[index];
  17907. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  17908. contactMaterial.contactEquationStiffness = 1e10;
  17909. contactMaterial.contactEquationRegularizationTime = 10;
  17910. this._world.addContactMaterial(contactMaterial);
  17911. }
  17912. return currentMat;
  17913. };
  17914. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  17915. var initialRotation = null;
  17916. if (mesh.rotationQuaternion) {
  17917. initialRotation = mesh.rotationQuaternion.clone();
  17918. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17919. }
  17920. var bbox = mesh.getBoundingInfo().boundingBox;
  17921. var deltaPosition = mesh.position.subtract(bbox.center);
  17922. var material = this._addMaterial(friction, restitution);
  17923. var body = new CANNON.RigidBody(mass, shape, material);
  17924. if (initialRotation) {
  17925. body.quaternion.x = initialRotation.x;
  17926. body.quaternion.z = initialRotation.y;
  17927. body.quaternion.y = initialRotation.z;
  17928. body.quaternion.w = -initialRotation.w;
  17929. }
  17930. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  17931. this._world.add(body);
  17932. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  17933. return body;
  17934. };
  17935. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17936. var compoundShape = new CANNON.Compound();
  17937. for (var index = 0; index < parts.length; index++) {
  17938. var mesh = parts[index].mesh;
  17939. var shape = this.registerMesh(mesh, parts[index].impostor);
  17940. if (index == 0) {
  17941. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  17942. } else {
  17943. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  17944. }
  17945. }
  17946. var initialMesh = parts[0].mesh;
  17947. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  17948. body.parts = parts;
  17949. return body;
  17950. };
  17951. CannonJSPlugin.prototype._unbindBody = function (body) {
  17952. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17953. var registeredMesh = this._registeredMeshes[index];
  17954. if (registeredMesh.body === body) {
  17955. registeredMesh.body = null;
  17956. registeredMesh.delta = 0;
  17957. }
  17958. }
  17959. };
  17960. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  17961. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17962. var registeredMesh = this._registeredMeshes[index];
  17963. if (registeredMesh.mesh === mesh) {
  17964. if (registeredMesh.body) {
  17965. this._world.remove(registeredMesh.body);
  17966. this._unbindBody(registeredMesh.body);
  17967. }
  17968. this._registeredMeshes.splice(index, 1);
  17969. return;
  17970. }
  17971. }
  17972. };
  17973. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17974. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  17975. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  17976. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17977. var registeredMesh = this._registeredMeshes[index];
  17978. if (registeredMesh.mesh === mesh) {
  17979. registeredMesh.body.applyImpulse(impulse, worldPoint);
  17980. return;
  17981. }
  17982. }
  17983. };
  17984. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  17985. var body1 = null, body2 = null;
  17986. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17987. var registeredMesh = this._registeredMeshes[index];
  17988. if (registeredMesh.mesh === mesh1) {
  17989. body1 = registeredMesh.body;
  17990. } else if (registeredMesh.mesh === mesh2) {
  17991. body2 = registeredMesh.body;
  17992. }
  17993. }
  17994. if (!body1 || !body2) {
  17995. return false;
  17996. }
  17997. 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));
  17998. this._world.addConstraint(constraint);
  17999. return true;
  18000. };
  18001. CannonJSPlugin.prototype.dispose = function () {
  18002. while (this._registeredMeshes.length) {
  18003. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18004. }
  18005. };
  18006. CannonJSPlugin.prototype.isSupported = function () {
  18007. return window.CANNON !== undefined;
  18008. };
  18009. return CannonJSPlugin;
  18010. })();
  18011. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18012. })(BABYLON || (BABYLON = {}));
  18013. var __extends = this.__extends || function (d, b) {
  18014. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18015. function __() { this.constructor = d; }
  18016. __.prototype = b.prototype;
  18017. d.prototype = new __();
  18018. };
  18019. var BABYLON;
  18020. (function (BABYLON) {
  18021. var Condition = (function () {
  18022. function Condition(actionManager) {
  18023. this._actionManager = actionManager;
  18024. }
  18025. Condition.prototype.isValid = function () {
  18026. return true;
  18027. };
  18028. Condition.prototype._getProperty = function (propertyPath) {
  18029. return this._actionManager._getProperty(propertyPath);
  18030. };
  18031. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18032. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18033. };
  18034. return Condition;
  18035. })();
  18036. BABYLON.Condition = Condition;
  18037. var ValueCondition = (function (_super) {
  18038. __extends(ValueCondition, _super);
  18039. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18040. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18041. _super.call(this, actionManager);
  18042. this.propertyPath = propertyPath;
  18043. this.value = value;
  18044. this.operator = operator;
  18045. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18046. this._property = this._getProperty(this.propertyPath);
  18047. }
  18048. Object.defineProperty(ValueCondition, "IsEqual", {
  18049. get: function () {
  18050. return ValueCondition._IsEqual;
  18051. },
  18052. enumerable: true,
  18053. configurable: true
  18054. });
  18055. Object.defineProperty(ValueCondition, "IsDifferent", {
  18056. get: function () {
  18057. return ValueCondition._IsDifferent;
  18058. },
  18059. enumerable: true,
  18060. configurable: true
  18061. });
  18062. Object.defineProperty(ValueCondition, "IsGreater", {
  18063. get: function () {
  18064. return ValueCondition._IsGreater;
  18065. },
  18066. enumerable: true,
  18067. configurable: true
  18068. });
  18069. Object.defineProperty(ValueCondition, "IsLesser", {
  18070. get: function () {
  18071. return ValueCondition._IsLesser;
  18072. },
  18073. enumerable: true,
  18074. configurable: true
  18075. });
  18076. ValueCondition.prototype.isValid = function () {
  18077. switch (this.operator) {
  18078. case ValueCondition.IsGreater:
  18079. return this._target[this._property] > this.value;
  18080. case ValueCondition.IsLesser:
  18081. return this._target[this._property] < this.value;
  18082. case ValueCondition.IsEqual:
  18083. case ValueCondition.IsDifferent:
  18084. var check;
  18085. if (this.value.equals) {
  18086. check = this.value.equals(this._target[this._property]);
  18087. } else {
  18088. check = this.value === this._target[this._property];
  18089. }
  18090. return this.operator === ValueCondition.IsEqual ? check : !check;
  18091. }
  18092. return false;
  18093. };
  18094. ValueCondition._IsEqual = 0;
  18095. ValueCondition._IsDifferent = 1;
  18096. ValueCondition._IsGreater = 2;
  18097. ValueCondition._IsLesser = 3;
  18098. return ValueCondition;
  18099. })(Condition);
  18100. BABYLON.ValueCondition = ValueCondition;
  18101. var PredicateCondition = (function (_super) {
  18102. __extends(PredicateCondition, _super);
  18103. function PredicateCondition(actionManager, predicate) {
  18104. _super.call(this, actionManager);
  18105. this.predicate = predicate;
  18106. }
  18107. PredicateCondition.prototype.isValid = function () {
  18108. return this.predicate();
  18109. };
  18110. return PredicateCondition;
  18111. })(Condition);
  18112. BABYLON.PredicateCondition = PredicateCondition;
  18113. var StateCondition = (function (_super) {
  18114. __extends(StateCondition, _super);
  18115. function StateCondition(actionManager, target, value) {
  18116. _super.call(this, actionManager);
  18117. this.value = value;
  18118. this._target = target;
  18119. }
  18120. StateCondition.prototype.isValid = function () {
  18121. return this._target.state === this.value;
  18122. };
  18123. return StateCondition;
  18124. })(Condition);
  18125. BABYLON.StateCondition = StateCondition;
  18126. })(BABYLON || (BABYLON = {}));
  18127. var BABYLON;
  18128. (function (BABYLON) {
  18129. var Action = (function () {
  18130. function Action(triggerOptions, condition) {
  18131. this.triggerOptions = triggerOptions;
  18132. if (triggerOptions.parameter) {
  18133. this.trigger = triggerOptions.trigger;
  18134. this._triggerParameter = triggerOptions.parameter;
  18135. } else {
  18136. this.trigger = triggerOptions;
  18137. }
  18138. this._nextActiveAction = this;
  18139. this._condition = condition;
  18140. }
  18141. Action.prototype._prepare = function () {
  18142. };
  18143. Action.prototype.getTriggerParameter = function () {
  18144. return this._triggerParameter;
  18145. };
  18146. Action.prototype._executeCurrent = function (evt) {
  18147. if (this._condition) {
  18148. var currentRenderId = this._actionManager.getScene().getRenderId();
  18149. if (this._condition._evaluationId === currentRenderId) {
  18150. if (!this._condition._currentResult) {
  18151. return;
  18152. }
  18153. } else {
  18154. this._condition._evaluationId = currentRenderId;
  18155. if (!this._condition.isValid()) {
  18156. this._condition._currentResult = false;
  18157. return;
  18158. }
  18159. this._condition._currentResult = true;
  18160. }
  18161. }
  18162. this._nextActiveAction.execute(evt);
  18163. if (this._nextActiveAction._child) {
  18164. this._nextActiveAction = this._nextActiveAction._child;
  18165. } else {
  18166. this._nextActiveAction = this;
  18167. }
  18168. };
  18169. Action.prototype.execute = function (evt) {
  18170. };
  18171. Action.prototype.then = function (action) {
  18172. this._child = action;
  18173. action._actionManager = this._actionManager;
  18174. action._prepare();
  18175. return action;
  18176. };
  18177. Action.prototype._getProperty = function (propertyPath) {
  18178. return this._actionManager._getProperty(propertyPath);
  18179. };
  18180. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18181. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18182. };
  18183. return Action;
  18184. })();
  18185. BABYLON.Action = Action;
  18186. })(BABYLON || (BABYLON = {}));
  18187. var BABYLON;
  18188. (function (BABYLON) {
  18189. var ActionEvent = (function () {
  18190. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18191. this.source = source;
  18192. this.pointerX = pointerX;
  18193. this.pointerY = pointerY;
  18194. this.meshUnderPointer = meshUnderPointer;
  18195. this.sourceEvent = sourceEvent;
  18196. }
  18197. ActionEvent.CreateNew = function (source) {
  18198. var scene = source.getScene();
  18199. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18200. };
  18201. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18202. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18203. };
  18204. return ActionEvent;
  18205. })();
  18206. BABYLON.ActionEvent = ActionEvent;
  18207. var ActionManager = (function () {
  18208. function ActionManager(scene) {
  18209. this.actions = new Array();
  18210. this._scene = scene;
  18211. scene._actionManagers.push(this);
  18212. }
  18213. Object.defineProperty(ActionManager, "NothingTrigger", {
  18214. get: function () {
  18215. return ActionManager._NothingTrigger;
  18216. },
  18217. enumerable: true,
  18218. configurable: true
  18219. });
  18220. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18221. get: function () {
  18222. return ActionManager._OnPickTrigger;
  18223. },
  18224. enumerable: true,
  18225. configurable: true
  18226. });
  18227. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18228. get: function () {
  18229. return ActionManager._OnLeftPickTrigger;
  18230. },
  18231. enumerable: true,
  18232. configurable: true
  18233. });
  18234. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18235. get: function () {
  18236. return ActionManager._OnRightPickTrigger;
  18237. },
  18238. enumerable: true,
  18239. configurable: true
  18240. });
  18241. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18242. get: function () {
  18243. return ActionManager._OnCenterPickTrigger;
  18244. },
  18245. enumerable: true,
  18246. configurable: true
  18247. });
  18248. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18249. get: function () {
  18250. return ActionManager._OnPointerOverTrigger;
  18251. },
  18252. enumerable: true,
  18253. configurable: true
  18254. });
  18255. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18256. get: function () {
  18257. return ActionManager._OnPointerOutTrigger;
  18258. },
  18259. enumerable: true,
  18260. configurable: true
  18261. });
  18262. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18263. get: function () {
  18264. return ActionManager._OnEveryFrameTrigger;
  18265. },
  18266. enumerable: true,
  18267. configurable: true
  18268. });
  18269. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18270. get: function () {
  18271. return ActionManager._OnIntersectionEnterTrigger;
  18272. },
  18273. enumerable: true,
  18274. configurable: true
  18275. });
  18276. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18277. get: function () {
  18278. return ActionManager._OnIntersectionExitTrigger;
  18279. },
  18280. enumerable: true,
  18281. configurable: true
  18282. });
  18283. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18284. get: function () {
  18285. return ActionManager._OnKeyDownTrigger;
  18286. },
  18287. enumerable: true,
  18288. configurable: true
  18289. });
  18290. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18291. get: function () {
  18292. return ActionManager._OnKeyUpTrigger;
  18293. },
  18294. enumerable: true,
  18295. configurable: true
  18296. });
  18297. ActionManager.prototype.dispose = function () {
  18298. var index = this._scene._actionManagers.indexOf(this);
  18299. if (index > -1) {
  18300. this._scene._actionManagers.splice(index, 1);
  18301. }
  18302. };
  18303. ActionManager.prototype.getScene = function () {
  18304. return this._scene;
  18305. };
  18306. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18307. for (var index = 0; index < this.actions.length; index++) {
  18308. var action = this.actions[index];
  18309. if (triggers.indexOf(action.trigger) > -1) {
  18310. return true;
  18311. }
  18312. }
  18313. return false;
  18314. };
  18315. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18316. get: function () {
  18317. for (var index = 0; index < this.actions.length; index++) {
  18318. var action = this.actions[index];
  18319. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18320. return true;
  18321. }
  18322. }
  18323. return false;
  18324. },
  18325. enumerable: true,
  18326. configurable: true
  18327. });
  18328. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18329. get: function () {
  18330. for (var index = 0; index < this.actions.length; index++) {
  18331. var action = this.actions[index];
  18332. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18333. return true;
  18334. }
  18335. }
  18336. return false;
  18337. },
  18338. enumerable: true,
  18339. configurable: true
  18340. });
  18341. ActionManager.prototype.registerAction = function (action) {
  18342. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18343. if (this.getScene().actionManager !== this) {
  18344. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18345. return null;
  18346. }
  18347. }
  18348. this.actions.push(action);
  18349. action._actionManager = this;
  18350. action._prepare();
  18351. return action;
  18352. };
  18353. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18354. for (var index = 0; index < this.actions.length; index++) {
  18355. var action = this.actions[index];
  18356. if (action.trigger === trigger) {
  18357. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18358. var parameter = action.getTriggerParameter();
  18359. if (parameter) {
  18360. if (evt.sourceEvent.key !== parameter) {
  18361. continue;
  18362. }
  18363. }
  18364. }
  18365. action._executeCurrent(evt);
  18366. }
  18367. }
  18368. };
  18369. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18370. var properties = propertyPath.split(".");
  18371. for (var index = 0; index < properties.length - 1; index++) {
  18372. target = target[properties[index]];
  18373. }
  18374. return target;
  18375. };
  18376. ActionManager.prototype._getProperty = function (propertyPath) {
  18377. var properties = propertyPath.split(".");
  18378. return properties[properties.length - 1];
  18379. };
  18380. ActionManager._NothingTrigger = 0;
  18381. ActionManager._OnPickTrigger = 1;
  18382. ActionManager._OnLeftPickTrigger = 2;
  18383. ActionManager._OnRightPickTrigger = 3;
  18384. ActionManager._OnCenterPickTrigger = 4;
  18385. ActionManager._OnPointerOverTrigger = 5;
  18386. ActionManager._OnPointerOutTrigger = 6;
  18387. ActionManager._OnEveryFrameTrigger = 7;
  18388. ActionManager._OnIntersectionEnterTrigger = 8;
  18389. ActionManager._OnIntersectionExitTrigger = 9;
  18390. ActionManager._OnKeyDownTrigger = 10;
  18391. ActionManager._OnKeyUpTrigger = 11;
  18392. return ActionManager;
  18393. })();
  18394. BABYLON.ActionManager = ActionManager;
  18395. })(BABYLON || (BABYLON = {}));
  18396. var __extends = this.__extends || function (d, b) {
  18397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18398. function __() { this.constructor = d; }
  18399. __.prototype = b.prototype;
  18400. d.prototype = new __();
  18401. };
  18402. var BABYLON;
  18403. (function (BABYLON) {
  18404. var InterpolateValueAction = (function (_super) {
  18405. __extends(InterpolateValueAction, _super);
  18406. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18407. if (typeof duration === "undefined") { duration = 1000; }
  18408. _super.call(this, triggerOptions, condition);
  18409. this.propertyPath = propertyPath;
  18410. this.value = value;
  18411. this.duration = duration;
  18412. this.stopOtherAnimations = stopOtherAnimations;
  18413. this._target = target;
  18414. }
  18415. InterpolateValueAction.prototype._prepare = function () {
  18416. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18417. this._property = this._getProperty(this.propertyPath);
  18418. };
  18419. InterpolateValueAction.prototype.execute = function () {
  18420. var scene = this._actionManager.getScene();
  18421. var keys = [
  18422. {
  18423. frame: 0,
  18424. value: this._target[this._property]
  18425. }, {
  18426. frame: 100,
  18427. value: this.value
  18428. }
  18429. ];
  18430. var dataType;
  18431. if (typeof this.value === "number") {
  18432. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18433. } else if (this.value instanceof BABYLON.Color3) {
  18434. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18435. } else if (this.value instanceof BABYLON.Vector3) {
  18436. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18437. } else if (this.value instanceof BABYLON.Matrix) {
  18438. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18439. } else if (this.value instanceof BABYLON.Quaternion) {
  18440. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18441. } else {
  18442. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18443. return;
  18444. }
  18445. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18446. animation.setKeys(keys);
  18447. if (this.stopOtherAnimations) {
  18448. scene.stopAnimation(this._target);
  18449. }
  18450. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18451. };
  18452. return InterpolateValueAction;
  18453. })(BABYLON.Action);
  18454. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18455. })(BABYLON || (BABYLON = {}));
  18456. var __extends = this.__extends || function (d, b) {
  18457. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18458. function __() { this.constructor = d; }
  18459. __.prototype = b.prototype;
  18460. d.prototype = new __();
  18461. };
  18462. var BABYLON;
  18463. (function (BABYLON) {
  18464. var SwitchBooleanAction = (function (_super) {
  18465. __extends(SwitchBooleanAction, _super);
  18466. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18467. _super.call(this, triggerOptions, condition);
  18468. this.propertyPath = propertyPath;
  18469. this._target = target;
  18470. }
  18471. SwitchBooleanAction.prototype._prepare = function () {
  18472. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18473. this._property = this._getProperty(this.propertyPath);
  18474. };
  18475. SwitchBooleanAction.prototype.execute = function () {
  18476. this._target[this._property] = !this._target[this._property];
  18477. };
  18478. return SwitchBooleanAction;
  18479. })(BABYLON.Action);
  18480. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18481. var SetStateAction = (function (_super) {
  18482. __extends(SetStateAction, _super);
  18483. function SetStateAction(triggerOptions, target, value, condition) {
  18484. _super.call(this, triggerOptions, condition);
  18485. this.value = value;
  18486. this._target = target;
  18487. }
  18488. SetStateAction.prototype.execute = function () {
  18489. this._target.state = this.value;
  18490. };
  18491. return SetStateAction;
  18492. })(BABYLON.Action);
  18493. BABYLON.SetStateAction = SetStateAction;
  18494. var SetValueAction = (function (_super) {
  18495. __extends(SetValueAction, _super);
  18496. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18497. _super.call(this, triggerOptions, condition);
  18498. this.propertyPath = propertyPath;
  18499. this.value = value;
  18500. this._target = target;
  18501. }
  18502. SetValueAction.prototype._prepare = function () {
  18503. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18504. this._property = this._getProperty(this.propertyPath);
  18505. };
  18506. SetValueAction.prototype.execute = function () {
  18507. this._target[this._property] = this.value;
  18508. };
  18509. return SetValueAction;
  18510. })(BABYLON.Action);
  18511. BABYLON.SetValueAction = SetValueAction;
  18512. var IncrementValueAction = (function (_super) {
  18513. __extends(IncrementValueAction, _super);
  18514. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18515. _super.call(this, triggerOptions, condition);
  18516. this.propertyPath = propertyPath;
  18517. this.value = value;
  18518. this._target = target;
  18519. }
  18520. IncrementValueAction.prototype._prepare = function () {
  18521. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18522. this._property = this._getProperty(this.propertyPath);
  18523. if (typeof this._target[this._property] !== "number") {
  18524. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18525. }
  18526. };
  18527. IncrementValueAction.prototype.execute = function () {
  18528. this._target[this._property] += this.value;
  18529. };
  18530. return IncrementValueAction;
  18531. })(BABYLON.Action);
  18532. BABYLON.IncrementValueAction = IncrementValueAction;
  18533. var PlayAnimationAction = (function (_super) {
  18534. __extends(PlayAnimationAction, _super);
  18535. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18536. _super.call(this, triggerOptions, condition);
  18537. this.from = from;
  18538. this.to = to;
  18539. this.loop = loop;
  18540. this._target = target;
  18541. }
  18542. PlayAnimationAction.prototype._prepare = function () {
  18543. };
  18544. PlayAnimationAction.prototype.execute = function () {
  18545. var scene = this._actionManager.getScene();
  18546. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18547. };
  18548. return PlayAnimationAction;
  18549. })(BABYLON.Action);
  18550. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18551. var StopAnimationAction = (function (_super) {
  18552. __extends(StopAnimationAction, _super);
  18553. function StopAnimationAction(triggerOptions, target, condition) {
  18554. _super.call(this, triggerOptions, condition);
  18555. this._target = target;
  18556. }
  18557. StopAnimationAction.prototype._prepare = function () {
  18558. };
  18559. StopAnimationAction.prototype.execute = function () {
  18560. var scene = this._actionManager.getScene();
  18561. scene.stopAnimation(this._target);
  18562. };
  18563. return StopAnimationAction;
  18564. })(BABYLON.Action);
  18565. BABYLON.StopAnimationAction = StopAnimationAction;
  18566. var DoNothingAction = (function (_super) {
  18567. __extends(DoNothingAction, _super);
  18568. function DoNothingAction(triggerOptions, condition) {
  18569. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18570. _super.call(this, triggerOptions, condition);
  18571. }
  18572. DoNothingAction.prototype.execute = function () {
  18573. };
  18574. return DoNothingAction;
  18575. })(BABYLON.Action);
  18576. BABYLON.DoNothingAction = DoNothingAction;
  18577. var CombineAction = (function (_super) {
  18578. __extends(CombineAction, _super);
  18579. function CombineAction(triggerOptions, children, condition) {
  18580. _super.call(this, triggerOptions, condition);
  18581. this.children = children;
  18582. }
  18583. CombineAction.prototype._prepare = function () {
  18584. for (var index = 0; index < this.children.length; index++) {
  18585. this.children[index]._actionManager = this._actionManager;
  18586. this.children[index]._prepare();
  18587. }
  18588. };
  18589. CombineAction.prototype.execute = function (evt) {
  18590. for (var index = 0; index < this.children.length; index++) {
  18591. this.children[index].execute(evt);
  18592. }
  18593. };
  18594. return CombineAction;
  18595. })(BABYLON.Action);
  18596. BABYLON.CombineAction = CombineAction;
  18597. var ExecuteCodeAction = (function (_super) {
  18598. __extends(ExecuteCodeAction, _super);
  18599. function ExecuteCodeAction(triggerOptions, func, condition) {
  18600. _super.call(this, triggerOptions, condition);
  18601. this.func = func;
  18602. }
  18603. ExecuteCodeAction.prototype.execute = function (evt) {
  18604. this.func(evt);
  18605. };
  18606. return ExecuteCodeAction;
  18607. })(BABYLON.Action);
  18608. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18609. var SetParentAction = (function (_super) {
  18610. __extends(SetParentAction, _super);
  18611. function SetParentAction(triggerOptions, target, parent, condition) {
  18612. _super.call(this, triggerOptions, condition);
  18613. this._target = target;
  18614. this._parent = parent;
  18615. }
  18616. SetParentAction.prototype._prepare = function () {
  18617. };
  18618. SetParentAction.prototype.execute = function () {
  18619. if (this._target.parent === this._parent) {
  18620. return;
  18621. }
  18622. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18623. invertParentWorldMatrix.invert();
  18624. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18625. this._target.parent = this._parent;
  18626. };
  18627. return SetParentAction;
  18628. })(BABYLON.Action);
  18629. BABYLON.SetParentAction = SetParentAction;
  18630. })(BABYLON || (BABYLON = {}));
  18631. var __extends = this.__extends || function (d, b) {
  18632. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18633. function __() { this.constructor = d; }
  18634. __.prototype = b.prototype;
  18635. d.prototype = new __();
  18636. };
  18637. var BABYLON;
  18638. (function (BABYLON) {
  18639. var Geometry = (function () {
  18640. function Geometry(id, scene, vertexData, updatable, mesh) {
  18641. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18642. this._totalVertices = 0;
  18643. this._indices = [];
  18644. this.id = id;
  18645. this._engine = scene.getEngine();
  18646. this._meshes = [];
  18647. this._scene = scene;
  18648. if (vertexData) {
  18649. this.setAllVerticesData(vertexData, updatable);
  18650. } else {
  18651. this._totalVertices = 0;
  18652. this._indices = [];
  18653. }
  18654. if (mesh) {
  18655. this.applyToMesh(mesh);
  18656. }
  18657. }
  18658. Geometry.prototype.getScene = function () {
  18659. return this._scene;
  18660. };
  18661. Geometry.prototype.getEngine = function () {
  18662. return this._engine;
  18663. };
  18664. Geometry.prototype.isReady = function () {
  18665. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18666. };
  18667. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18668. vertexData.applyToGeometry(this, updatable);
  18669. };
  18670. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18671. this._vertexBuffers = this._vertexBuffers || {};
  18672. if (this._vertexBuffers[kind]) {
  18673. this._vertexBuffers[kind].dispose();
  18674. }
  18675. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18676. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18677. var stride = this._vertexBuffers[kind].getStrideSize();
  18678. this._totalVertices = data.length / stride;
  18679. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18680. var meshes = this._meshes;
  18681. var numOfMeshes = meshes.length;
  18682. for (var index = 0; index < numOfMeshes; index++) {
  18683. var mesh = meshes[index];
  18684. mesh._resetPointsArrayCache();
  18685. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18686. mesh._createGlobalSubMesh();
  18687. mesh.computeWorldMatrix(true);
  18688. }
  18689. }
  18690. };
  18691. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18692. var vertexBuffer = this.getVertexBuffer(kind);
  18693. if (!vertexBuffer) {
  18694. return;
  18695. }
  18696. vertexBuffer.update(data);
  18697. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18698. var extend;
  18699. if (updateExtends) {
  18700. var stride = vertexBuffer.getStrideSize();
  18701. this._totalVertices = data.length / stride;
  18702. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18703. }
  18704. var meshes = this._meshes;
  18705. var numOfMeshes = meshes.length;
  18706. for (var index = 0; index < numOfMeshes; index++) {
  18707. var mesh = meshes[index];
  18708. mesh._resetPointsArrayCache();
  18709. if (updateExtends) {
  18710. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18711. }
  18712. }
  18713. }
  18714. };
  18715. Geometry.prototype.getTotalVertices = function () {
  18716. if (!this.isReady()) {
  18717. return 0;
  18718. }
  18719. return this._totalVertices;
  18720. };
  18721. Geometry.prototype.getVerticesData = function (kind) {
  18722. var vertexBuffer = this.getVertexBuffer(kind);
  18723. if (!vertexBuffer) {
  18724. return null;
  18725. }
  18726. return vertexBuffer.getData();
  18727. };
  18728. Geometry.prototype.getVertexBuffer = function (kind) {
  18729. if (!this.isReady()) {
  18730. return null;
  18731. }
  18732. return this._vertexBuffers[kind];
  18733. };
  18734. Geometry.prototype.getVertexBuffers = function () {
  18735. if (!this.isReady()) {
  18736. return null;
  18737. }
  18738. return this._vertexBuffers;
  18739. };
  18740. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18741. if (!this._vertexBuffers) {
  18742. if (this._delayInfo) {
  18743. return this._delayInfo.indexOf(kind) !== -1;
  18744. }
  18745. return false;
  18746. }
  18747. return this._vertexBuffers[kind] !== undefined;
  18748. };
  18749. Geometry.prototype.getVerticesDataKinds = function () {
  18750. var result = [];
  18751. if (!this._vertexBuffers && this._delayInfo) {
  18752. for (var kind in this._delayInfo) {
  18753. result.push(kind);
  18754. }
  18755. } else {
  18756. for (kind in this._vertexBuffers) {
  18757. result.push(kind);
  18758. }
  18759. }
  18760. return result;
  18761. };
  18762. Geometry.prototype.setIndices = function (indices) {
  18763. if (this._indexBuffer) {
  18764. this._engine._releaseBuffer(this._indexBuffer);
  18765. }
  18766. this._indices = indices;
  18767. if (this._meshes.length !== 0 && this._indices) {
  18768. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18769. }
  18770. var meshes = this._meshes;
  18771. var numOfMeshes = meshes.length;
  18772. for (var index = 0; index < numOfMeshes; index++) {
  18773. meshes[index]._createGlobalSubMesh();
  18774. }
  18775. };
  18776. Geometry.prototype.getTotalIndices = function () {
  18777. if (!this.isReady()) {
  18778. return 0;
  18779. }
  18780. return this._indices.length;
  18781. };
  18782. Geometry.prototype.getIndices = function () {
  18783. if (!this.isReady()) {
  18784. return null;
  18785. }
  18786. return this._indices;
  18787. };
  18788. Geometry.prototype.getIndexBuffer = function () {
  18789. if (!this.isReady()) {
  18790. return null;
  18791. }
  18792. return this._indexBuffer;
  18793. };
  18794. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18795. var meshes = this._meshes;
  18796. var index = meshes.indexOf(mesh);
  18797. if (index === -1) {
  18798. return;
  18799. }
  18800. for (var kind in this._vertexBuffers) {
  18801. this._vertexBuffers[kind].dispose();
  18802. }
  18803. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18804. this._indexBuffer = null;
  18805. }
  18806. meshes.splice(index, 1);
  18807. mesh._geometry = null;
  18808. if (meshes.length == 0 && shouldDispose) {
  18809. this.dispose();
  18810. }
  18811. };
  18812. Geometry.prototype.applyToMesh = function (mesh) {
  18813. if (mesh._geometry === this) {
  18814. return;
  18815. }
  18816. var previousGeometry = mesh._geometry;
  18817. if (previousGeometry) {
  18818. previousGeometry.releaseForMesh(mesh);
  18819. }
  18820. var meshes = this._meshes;
  18821. mesh._geometry = this;
  18822. this._scene.pushGeometry(this);
  18823. meshes.push(mesh);
  18824. if (this.isReady()) {
  18825. this._applyToMesh(mesh);
  18826. } else {
  18827. mesh._boundingInfo = this._boundingInfo;
  18828. }
  18829. };
  18830. Geometry.prototype._applyToMesh = function (mesh) {
  18831. var numOfMeshes = this._meshes.length;
  18832. for (var kind in this._vertexBuffers) {
  18833. if (numOfMeshes === 1) {
  18834. this._vertexBuffers[kind].create();
  18835. }
  18836. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18837. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18838. mesh._resetPointsArrayCache();
  18839. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18840. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18841. mesh._createGlobalSubMesh();
  18842. }
  18843. }
  18844. if (numOfMeshes === 1 && this._indices) {
  18845. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18846. }
  18847. if (this._indexBuffer) {
  18848. this._indexBuffer.references = numOfMeshes;
  18849. }
  18850. };
  18851. Geometry.prototype.load = function (scene, onLoaded) {
  18852. var _this = this;
  18853. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18854. return;
  18855. }
  18856. if (this.isReady()) {
  18857. if (onLoaded) {
  18858. onLoaded();
  18859. }
  18860. return;
  18861. }
  18862. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18863. scene._addPendingData(this);
  18864. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18865. _this._delayLoadingFunction(JSON.parse(data), _this);
  18866. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18867. _this._delayInfo = [];
  18868. scene._removePendingData(_this);
  18869. var meshes = _this._meshes;
  18870. var numOfMeshes = meshes.length;
  18871. for (var index = 0; index < numOfMeshes; index++) {
  18872. _this._applyToMesh(meshes[index]);
  18873. }
  18874. if (onLoaded) {
  18875. onLoaded();
  18876. }
  18877. }, function () {
  18878. }, scene.database);
  18879. };
  18880. Geometry.prototype.dispose = function () {
  18881. var meshes = this._meshes;
  18882. var numOfMeshes = meshes.length;
  18883. for (var index = 0; index < numOfMeshes; index++) {
  18884. this.releaseForMesh(meshes[index]);
  18885. }
  18886. this._meshes = [];
  18887. for (var kind in this._vertexBuffers) {
  18888. this._vertexBuffers[kind].dispose();
  18889. }
  18890. this._vertexBuffers = [];
  18891. this._totalVertices = 0;
  18892. if (this._indexBuffer) {
  18893. this._engine._releaseBuffer(this._indexBuffer);
  18894. }
  18895. this._indexBuffer = null;
  18896. this._indices = [];
  18897. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18898. this.delayLoadingFile = null;
  18899. this._delayLoadingFunction = null;
  18900. this._delayInfo = [];
  18901. this._boundingInfo = null;
  18902. var geometries = this._scene.getGeometries();
  18903. index = geometries.indexOf(this);
  18904. if (index > -1) {
  18905. geometries.splice(index, 1);
  18906. }
  18907. };
  18908. Geometry.prototype.copy = function (id) {
  18909. var vertexData = new BABYLON.VertexData();
  18910. vertexData.indices = [];
  18911. var indices = this.getIndices();
  18912. for (var index = 0; index < indices.length; index++) {
  18913. vertexData.indices.push(indices[index]);
  18914. }
  18915. var updatable = false;
  18916. var stopChecking = false;
  18917. for (var kind in this._vertexBuffers) {
  18918. vertexData.set(this.getVerticesData(kind), kind);
  18919. if (!stopChecking) {
  18920. updatable = this.getVertexBuffer(kind).isUpdatable();
  18921. stopChecking = !updatable;
  18922. }
  18923. }
  18924. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  18925. geometry.delayLoadState = this.delayLoadState;
  18926. geometry.delayLoadingFile = this.delayLoadingFile;
  18927. geometry._delayLoadingFunction = this._delayLoadingFunction;
  18928. for (kind in this._delayInfo) {
  18929. geometry._delayInfo = geometry._delayInfo || [];
  18930. geometry._delayInfo.push(kind);
  18931. }
  18932. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  18933. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18934. return geometry;
  18935. };
  18936. Geometry.ExtractFromMesh = function (mesh, id) {
  18937. var geometry = mesh._geometry;
  18938. if (!geometry) {
  18939. return null;
  18940. }
  18941. return geometry.copy(id);
  18942. };
  18943. Geometry.RandomId = function () {
  18944. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  18945. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  18946. return v.toString(16);
  18947. });
  18948. };
  18949. return Geometry;
  18950. })();
  18951. BABYLON.Geometry = Geometry;
  18952. (function (Geometry) {
  18953. (function (Primitives) {
  18954. var _Primitive = (function (_super) {
  18955. __extends(_Primitive, _super);
  18956. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  18957. this._beingRegenerated = true;
  18958. this._canBeRegenerated = canBeRegenerated;
  18959. _super.call(this, id, scene, vertexData, false, mesh);
  18960. this._beingRegenerated = false;
  18961. }
  18962. _Primitive.prototype.canBeRegenerated = function () {
  18963. return this._canBeRegenerated;
  18964. };
  18965. _Primitive.prototype.regenerate = function () {
  18966. if (!this._canBeRegenerated) {
  18967. return;
  18968. }
  18969. this._beingRegenerated = true;
  18970. this.setAllVerticesData(this._regenerateVertexData(), false);
  18971. this._beingRegenerated = false;
  18972. };
  18973. _Primitive.prototype.asNewGeometry = function (id) {
  18974. return _super.prototype.copy.call(this, id);
  18975. };
  18976. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  18977. if (!this._beingRegenerated) {
  18978. return;
  18979. }
  18980. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  18981. };
  18982. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  18983. if (!this._beingRegenerated) {
  18984. return;
  18985. }
  18986. _super.prototype.setVerticesData.call(this, kind, data, false);
  18987. };
  18988. _Primitive.prototype._regenerateVertexData = function () {
  18989. throw new Error("Abstract method");
  18990. };
  18991. _Primitive.prototype.copy = function (id) {
  18992. throw new Error("Must be overriden in sub-classes.");
  18993. };
  18994. return _Primitive;
  18995. })(Geometry);
  18996. Primitives._Primitive = _Primitive;
  18997. var Box = (function (_super) {
  18998. __extends(Box, _super);
  18999. function Box(id, scene, size, canBeRegenerated, mesh) {
  19000. this.size = size;
  19001. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19002. }
  19003. Box.prototype._regenerateVertexData = function () {
  19004. return BABYLON.VertexData.CreateBox(this.size);
  19005. };
  19006. Box.prototype.copy = function (id) {
  19007. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19008. };
  19009. return Box;
  19010. })(_Primitive);
  19011. Primitives.Box = Box;
  19012. var Sphere = (function (_super) {
  19013. __extends(Sphere, _super);
  19014. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19015. this.segments = segments;
  19016. this.diameter = diameter;
  19017. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19018. }
  19019. Sphere.prototype._regenerateVertexData = function () {
  19020. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19021. };
  19022. Sphere.prototype.copy = function (id) {
  19023. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19024. };
  19025. return Sphere;
  19026. })(_Primitive);
  19027. Primitives.Sphere = Sphere;
  19028. var Cylinder = (function (_super) {
  19029. __extends(Cylinder, _super);
  19030. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19031. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19032. this.height = height;
  19033. this.diameterTop = diameterTop;
  19034. this.diameterBottom = diameterBottom;
  19035. this.tessellation = tessellation;
  19036. this.subdivisions = subdivisions;
  19037. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19038. }
  19039. Cylinder.prototype._regenerateVertexData = function () {
  19040. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19041. };
  19042. Cylinder.prototype.copy = function (id) {
  19043. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19044. };
  19045. return Cylinder;
  19046. })(_Primitive);
  19047. Primitives.Cylinder = Cylinder;
  19048. var Torus = (function (_super) {
  19049. __extends(Torus, _super);
  19050. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19051. this.diameter = diameter;
  19052. this.thickness = thickness;
  19053. this.tessellation = tessellation;
  19054. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19055. }
  19056. Torus.prototype._regenerateVertexData = function () {
  19057. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19058. };
  19059. Torus.prototype.copy = function (id) {
  19060. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19061. };
  19062. return Torus;
  19063. })(_Primitive);
  19064. Primitives.Torus = Torus;
  19065. var Ground = (function (_super) {
  19066. __extends(Ground, _super);
  19067. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19068. this.width = width;
  19069. this.height = height;
  19070. this.subdivisions = subdivisions;
  19071. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19072. }
  19073. Ground.prototype._regenerateVertexData = function () {
  19074. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19075. };
  19076. Ground.prototype.copy = function (id) {
  19077. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19078. };
  19079. return Ground;
  19080. })(_Primitive);
  19081. Primitives.Ground = Ground;
  19082. var TiledGround = (function (_super) {
  19083. __extends(TiledGround, _super);
  19084. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19085. this.xmin = xmin;
  19086. this.zmin = zmin;
  19087. this.xmax = xmax;
  19088. this.zmax = zmax;
  19089. this.subdivisions = subdivisions;
  19090. this.precision = precision;
  19091. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19092. }
  19093. TiledGround.prototype._regenerateVertexData = function () {
  19094. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19095. };
  19096. TiledGround.prototype.copy = function (id) {
  19097. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19098. };
  19099. return TiledGround;
  19100. })(_Primitive);
  19101. Primitives.TiledGround = TiledGround;
  19102. var Plane = (function (_super) {
  19103. __extends(Plane, _super);
  19104. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19105. this.size = size;
  19106. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19107. }
  19108. Plane.prototype._regenerateVertexData = function () {
  19109. return BABYLON.VertexData.CreatePlane(this.size);
  19110. };
  19111. Plane.prototype.copy = function (id) {
  19112. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19113. };
  19114. return Plane;
  19115. })(_Primitive);
  19116. Primitives.Plane = Plane;
  19117. var TorusKnot = (function (_super) {
  19118. __extends(TorusKnot, _super);
  19119. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19120. this.radius = radius;
  19121. this.tube = tube;
  19122. this.radialSegments = radialSegments;
  19123. this.tubularSegments = tubularSegments;
  19124. this.p = p;
  19125. this.q = q;
  19126. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19127. }
  19128. TorusKnot.prototype._regenerateVertexData = function () {
  19129. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19130. };
  19131. TorusKnot.prototype.copy = function (id) {
  19132. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19133. };
  19134. return TorusKnot;
  19135. })(_Primitive);
  19136. Primitives.TorusKnot = TorusKnot;
  19137. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19138. var Primitives = Geometry.Primitives;
  19139. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19140. var Geometry = BABYLON.Geometry;
  19141. })(BABYLON || (BABYLON = {}));
  19142. var __extends = this.__extends || function (d, b) {
  19143. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19144. function __() { this.constructor = d; }
  19145. __.prototype = b.prototype;
  19146. d.prototype = new __();
  19147. };
  19148. var BABYLON;
  19149. (function (BABYLON) {
  19150. var Gamepads = (function () {
  19151. function Gamepads(ongamedpadconnected) {
  19152. var _this = this;
  19153. this.babylonGamepads = [];
  19154. this.oneGamepadConnected = false;
  19155. this.isMonitoring = false;
  19156. this.gamepadEventSupported = 'GamepadEvent' in window;
  19157. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19158. 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=";
  19159. this._callbackGamepadConnected = ongamedpadconnected;
  19160. if (this.gamepadSupportAvailable) {
  19161. if (this.gamepadEventSupported) {
  19162. window.addEventListener('gamepadconnected', function (evt) {
  19163. _this._onGamepadConnected(evt);
  19164. }, false);
  19165. window.addEventListener('gamepaddisconnected', function (evt) {
  19166. _this._onGamepadDisconnected(evt);
  19167. }, false);
  19168. } else {
  19169. this._startMonitoringGamepads();
  19170. }
  19171. if (!this.oneGamepadConnected) {
  19172. this._insertGamepadDOMInstructions();
  19173. }
  19174. } else {
  19175. this._insertGamepadDOMNotSupported();
  19176. }
  19177. }
  19178. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19179. Gamepads.gamepadDOMInfo = document.createElement("div");
  19180. var buttonAImage = document.createElement("img");
  19181. buttonAImage.src = this.buttonADataURL;
  19182. var spanMessage = document.createElement("span");
  19183. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19184. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19185. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19186. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19187. Gamepads.gamepadDOMInfo.style.width = "100%";
  19188. Gamepads.gamepadDOMInfo.style.height = "48px";
  19189. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19190. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19191. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19192. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19193. buttonAImage.style.position = "relative";
  19194. buttonAImage.style.bottom = "8px";
  19195. spanMessage.style.position = "relative";
  19196. spanMessage.style.fontSize = "32px";
  19197. spanMessage.style.bottom = "32px";
  19198. spanMessage.style.color = "green";
  19199. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19200. };
  19201. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19202. Gamepads.gamepadDOMInfo = document.createElement("div");
  19203. var spanMessage = document.createElement("span");
  19204. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19205. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19206. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19207. Gamepads.gamepadDOMInfo.style.width = "100%";
  19208. Gamepads.gamepadDOMInfo.style.height = "40px";
  19209. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19210. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19211. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19212. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19213. spanMessage.style.position = "relative";
  19214. spanMessage.style.fontSize = "32px";
  19215. spanMessage.style.color = "red";
  19216. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19217. };
  19218. Gamepads.prototype.dispose = function () {
  19219. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19220. };
  19221. Gamepads.prototype._onGamepadConnected = function (evt) {
  19222. var newGamepad = this._addNewGamepad(evt.gamepad);
  19223. if (this._callbackGamepadConnected)
  19224. this._callbackGamepadConnected(newGamepad);
  19225. this._startMonitoringGamepads();
  19226. };
  19227. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19228. if (!this.oneGamepadConnected) {
  19229. this.oneGamepadConnected = true;
  19230. if (Gamepads.gamepadDOMInfo) {
  19231. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19232. Gamepads.gamepadDOMInfo = null;
  19233. }
  19234. }
  19235. var newGamepad;
  19236. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19237. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19238. } else {
  19239. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19240. }
  19241. this.babylonGamepads.push(newGamepad);
  19242. return newGamepad;
  19243. };
  19244. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19245. for (var i in this.babylonGamepads) {
  19246. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19247. this.babylonGamepads.splice(i, 1);
  19248. break;
  19249. }
  19250. }
  19251. if (this.babylonGamepads.length == 0) {
  19252. this._stopMonitoringGamepads();
  19253. }
  19254. };
  19255. Gamepads.prototype._startMonitoringGamepads = function () {
  19256. if (!this.isMonitoring) {
  19257. this.isMonitoring = true;
  19258. this._checkGamepadsStatus();
  19259. }
  19260. };
  19261. Gamepads.prototype._stopMonitoringGamepads = function () {
  19262. this.isMonitoring = false;
  19263. };
  19264. Gamepads.prototype._checkGamepadsStatus = function () {
  19265. var _this = this;
  19266. this._updateGamepadObjects();
  19267. for (var i in this.babylonGamepads) {
  19268. this.babylonGamepads[i].update();
  19269. }
  19270. if (this.isMonitoring) {
  19271. if (window.requestAnimationFrame) {
  19272. window.requestAnimationFrame(function () {
  19273. _this._checkGamepadsStatus();
  19274. });
  19275. } else if (window.mozRequestAnimationFrame) {
  19276. window.mozRequestAnimationFrame(function () {
  19277. _this._checkGamepadsStatus();
  19278. });
  19279. } else if (window.webkitRequestAnimationFrame) {
  19280. window.webkitRequestAnimationFrame(function () {
  19281. _this._checkGamepadsStatus();
  19282. });
  19283. }
  19284. }
  19285. };
  19286. Gamepads.prototype._updateGamepadObjects = function () {
  19287. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19288. for (var i = 0; i < gamepads.length; i++) {
  19289. if (gamepads[i]) {
  19290. if (!(gamepads[i].index in this.babylonGamepads)) {
  19291. var newGamepad = this._addNewGamepad(gamepads[i]);
  19292. if (this._callbackGamepadConnected) {
  19293. this._callbackGamepadConnected(newGamepad);
  19294. }
  19295. } else {
  19296. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19297. }
  19298. }
  19299. }
  19300. };
  19301. return Gamepads;
  19302. })();
  19303. BABYLON.Gamepads = Gamepads;
  19304. var StickValues = (function () {
  19305. function StickValues(x, y) {
  19306. this.x = x;
  19307. this.y = y;
  19308. }
  19309. return StickValues;
  19310. })();
  19311. BABYLON.StickValues = StickValues;
  19312. var Gamepad = (function () {
  19313. function Gamepad(id, index, browserGamepad) {
  19314. this.id = id;
  19315. this.index = index;
  19316. this.browserGamepad = browserGamepad;
  19317. if (this.browserGamepad.axes.length >= 2) {
  19318. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19319. }
  19320. if (this.browserGamepad.axes.length >= 4) {
  19321. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19322. }
  19323. }
  19324. Gamepad.prototype.onleftstickchanged = function (callback) {
  19325. this._onleftstickchanged = callback;
  19326. };
  19327. Gamepad.prototype.onrightstickchanged = function (callback) {
  19328. this._onrightstickchanged = callback;
  19329. };
  19330. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19331. get: function () {
  19332. return this._leftStick;
  19333. },
  19334. set: function (newValues) {
  19335. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19336. this._onleftstickchanged(newValues);
  19337. }
  19338. this._leftStick = newValues;
  19339. },
  19340. enumerable: true,
  19341. configurable: true
  19342. });
  19343. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19344. get: function () {
  19345. return this._rightStick;
  19346. },
  19347. set: function (newValues) {
  19348. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19349. this._onrightstickchanged(newValues);
  19350. }
  19351. this._rightStick = newValues;
  19352. },
  19353. enumerable: true,
  19354. configurable: true
  19355. });
  19356. Gamepad.prototype.update = function () {
  19357. if (this._leftStick) {
  19358. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19359. }
  19360. if (this._rightStick) {
  19361. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19362. }
  19363. };
  19364. return Gamepad;
  19365. })();
  19366. BABYLON.Gamepad = Gamepad;
  19367. var GenericPad = (function (_super) {
  19368. __extends(GenericPad, _super);
  19369. function GenericPad(id, index, gamepad) {
  19370. _super.call(this, id, index, gamepad);
  19371. this.id = id;
  19372. this.index = index;
  19373. this.gamepad = gamepad;
  19374. this._buttons = new Array(gamepad.buttons.length);
  19375. }
  19376. GenericPad.prototype.onbuttondown = function (callback) {
  19377. this._onbuttondown = callback;
  19378. };
  19379. GenericPad.prototype.onbuttonup = function (callback) {
  19380. this._onbuttonup = callback;
  19381. };
  19382. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19383. if (newValue !== currentValue) {
  19384. if (this._onbuttondown && newValue === 1) {
  19385. this._onbuttondown(buttonIndex);
  19386. }
  19387. if (this._onbuttonup && newValue === 0) {
  19388. this._onbuttonup(buttonIndex);
  19389. }
  19390. }
  19391. return newValue;
  19392. };
  19393. GenericPad.prototype.update = function () {
  19394. _super.prototype.update.call(this);
  19395. for (var index = 0; index < this._buttons.length; index++) {
  19396. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19397. }
  19398. };
  19399. return GenericPad;
  19400. })(Gamepad);
  19401. BABYLON.GenericPad = GenericPad;
  19402. (function (Xbox360Button) {
  19403. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19404. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19405. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19406. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19407. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19408. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19409. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19410. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19411. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19412. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19413. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19414. var Xbox360Button = BABYLON.Xbox360Button;
  19415. (function (Xbox360Dpad) {
  19416. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19417. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19418. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19419. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19420. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19421. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19422. var Xbox360Pad = (function (_super) {
  19423. __extends(Xbox360Pad, _super);
  19424. function Xbox360Pad() {
  19425. _super.apply(this, arguments);
  19426. this._leftTrigger = 0;
  19427. this._rightTrigger = 0;
  19428. this._buttonA = 0;
  19429. this._buttonB = 0;
  19430. this._buttonX = 0;
  19431. this._buttonY = 0;
  19432. this._buttonBack = 0;
  19433. this._buttonStart = 0;
  19434. this._buttonLB = 0;
  19435. this._buttonRB = 0;
  19436. this._buttonLeftStick = 0;
  19437. this._buttonRightStick = 0;
  19438. this._dPadUp = 0;
  19439. this._dPadDown = 0;
  19440. this._dPadLeft = 0;
  19441. this._dPadRight = 0;
  19442. }
  19443. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19444. this._onlefttriggerchanged = callback;
  19445. };
  19446. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19447. this._onrighttriggerchanged = callback;
  19448. };
  19449. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19450. get: function () {
  19451. return this._leftTrigger;
  19452. },
  19453. set: function (newValue) {
  19454. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19455. this._onlefttriggerchanged(newValue);
  19456. }
  19457. this._leftTrigger = newValue;
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19463. get: function () {
  19464. return this._rightTrigger;
  19465. },
  19466. set: function (newValue) {
  19467. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19468. this._onrighttriggerchanged(newValue);
  19469. }
  19470. this._rightTrigger = newValue;
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19476. this._onbuttondown = callback;
  19477. };
  19478. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19479. this._onbuttonup = callback;
  19480. };
  19481. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19482. this._ondpaddown = callback;
  19483. };
  19484. Xbox360Pad.prototype.ondpadup = function (callback) {
  19485. this._ondpadup = callback;
  19486. };
  19487. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19488. if (newValue !== currentValue) {
  19489. if (this._onbuttondown && newValue === 1) {
  19490. this._onbuttondown(buttonType);
  19491. }
  19492. if (this._onbuttonup && newValue === 0) {
  19493. this._onbuttonup(buttonType);
  19494. }
  19495. }
  19496. return newValue;
  19497. };
  19498. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19499. if (newValue !== currentValue) {
  19500. if (this._ondpaddown && newValue === 1) {
  19501. this._ondpaddown(buttonType);
  19502. }
  19503. if (this._ondpadup && newValue === 0) {
  19504. this._ondpadup(buttonType);
  19505. }
  19506. }
  19507. return newValue;
  19508. };
  19509. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19510. get: function () {
  19511. return this._buttonA;
  19512. },
  19513. set: function (value) {
  19514. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19520. get: function () {
  19521. return this._buttonB;
  19522. },
  19523. set: function (value) {
  19524. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19530. get: function () {
  19531. return this._buttonX;
  19532. },
  19533. set: function (value) {
  19534. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19540. get: function () {
  19541. return this._buttonY;
  19542. },
  19543. set: function (value) {
  19544. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19545. },
  19546. enumerable: true,
  19547. configurable: true
  19548. });
  19549. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19550. get: function () {
  19551. return this._buttonStart;
  19552. },
  19553. set: function (value) {
  19554. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19560. get: function () {
  19561. return this._buttonBack;
  19562. },
  19563. set: function (value) {
  19564. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19570. get: function () {
  19571. return this._buttonLB;
  19572. },
  19573. set: function (value) {
  19574. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19580. get: function () {
  19581. return this._buttonRB;
  19582. },
  19583. set: function (value) {
  19584. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19585. },
  19586. enumerable: true,
  19587. configurable: true
  19588. });
  19589. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19590. get: function () {
  19591. return this._buttonLeftStick;
  19592. },
  19593. set: function (value) {
  19594. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19595. },
  19596. enumerable: true,
  19597. configurable: true
  19598. });
  19599. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19600. get: function () {
  19601. return this._buttonRightStick;
  19602. },
  19603. set: function (value) {
  19604. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19605. },
  19606. enumerable: true,
  19607. configurable: true
  19608. });
  19609. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19610. get: function () {
  19611. return this._dPadUp;
  19612. },
  19613. set: function (value) {
  19614. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19615. },
  19616. enumerable: true,
  19617. configurable: true
  19618. });
  19619. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19620. get: function () {
  19621. return this._dPadDown;
  19622. },
  19623. set: function (value) {
  19624. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19625. },
  19626. enumerable: true,
  19627. configurable: true
  19628. });
  19629. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19630. get: function () {
  19631. return this._dPadLeft;
  19632. },
  19633. set: function (value) {
  19634. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19640. get: function () {
  19641. return this._dPadRight;
  19642. },
  19643. set: function (value) {
  19644. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. Xbox360Pad.prototype.update = function () {
  19650. _super.prototype.update.call(this);
  19651. this.buttonA = this.browserGamepad.buttons[0].value;
  19652. this.buttonB = this.browserGamepad.buttons[1].value;
  19653. this.buttonX = this.browserGamepad.buttons[2].value;
  19654. this.buttonY = this.browserGamepad.buttons[3].value;
  19655. this.buttonLB = this.browserGamepad.buttons[4].value;
  19656. this.buttonRB = this.browserGamepad.buttons[5].value;
  19657. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19658. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19659. this.buttonBack = this.browserGamepad.buttons[8].value;
  19660. this.buttonStart = this.browserGamepad.buttons[9].value;
  19661. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19662. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19663. this.dPadUp = this.browserGamepad.buttons[12].value;
  19664. this.dPadDown = this.browserGamepad.buttons[13].value;
  19665. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19666. this.dPadRight = this.browserGamepad.buttons[15].value;
  19667. };
  19668. return Xbox360Pad;
  19669. })(Gamepad);
  19670. BABYLON.Xbox360Pad = Xbox360Pad;
  19671. })(BABYLON || (BABYLON = {}));
  19672. var __extends = this.__extends || function (d, b) {
  19673. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19674. function __() { this.constructor = d; }
  19675. __.prototype = b.prototype;
  19676. d.prototype = new __();
  19677. };
  19678. var BABYLON;
  19679. (function (BABYLON) {
  19680. var GamepadCamera = (function (_super) {
  19681. __extends(GamepadCamera, _super);
  19682. function GamepadCamera(name, position, scene) {
  19683. var _this = this;
  19684. _super.call(this, name, position, scene);
  19685. this.angularSensibility = 200;
  19686. this.moveSensibility = 75;
  19687. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19688. _this._onNewGameConnected(gamepad);
  19689. });
  19690. }
  19691. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19692. if (gamepad.index === 0) {
  19693. this._gamepad = gamepad;
  19694. }
  19695. };
  19696. GamepadCamera.prototype._checkInputs = function () {
  19697. if (!this._gamepad) {
  19698. return;
  19699. }
  19700. var LSValues = this._gamepad.leftStick;
  19701. var normalizedLX = LSValues.x / this.moveSensibility;
  19702. var normalizedLY = LSValues.y / this.moveSensibility;
  19703. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19704. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19705. var RSValues = this._gamepad.rightStick;
  19706. var normalizedRX = RSValues.x / this.angularSensibility;
  19707. var normalizedRY = RSValues.y / this.angularSensibility;
  19708. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19709. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19710. ;
  19711. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19712. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19713. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19714. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19715. };
  19716. GamepadCamera.prototype.dispose = function () {
  19717. this._gamepads.dispose();
  19718. _super.prototype.dispose.call(this);
  19719. };
  19720. return GamepadCamera;
  19721. })(BABYLON.FreeCamera);
  19722. BABYLON.GamepadCamera = GamepadCamera;
  19723. })(BABYLON || (BABYLON = {}));
  19724. var __extends = this.__extends || function (d, b) {
  19725. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19726. function __() { this.constructor = d; }
  19727. __.prototype = b.prototype;
  19728. d.prototype = new __();
  19729. };
  19730. var BABYLON;
  19731. (function (BABYLON) {
  19732. var LinesMesh = (function (_super) {
  19733. __extends(LinesMesh, _super);
  19734. function LinesMesh(name, scene, updatable) {
  19735. if (typeof updatable === "undefined") { updatable = false; }
  19736. _super.call(this, name, scene);
  19737. this.color = new BABYLON.Color3(1, 1, 1);
  19738. this.alpha = 1;
  19739. this._indices = new Array();
  19740. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19741. attributes: ["position"],
  19742. uniforms: ["worldViewProjection", "color"],
  19743. needAlphaBlending: true
  19744. });
  19745. }
  19746. Object.defineProperty(LinesMesh.prototype, "material", {
  19747. get: function () {
  19748. return this._colorShader;
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19754. get: function () {
  19755. return false;
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19761. get: function () {
  19762. return false;
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19768. var engine = this.getScene().getEngine();
  19769. var indexToBind = this._geometry.getIndexBuffer();
  19770. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19771. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19772. };
  19773. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19774. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19775. return;
  19776. }
  19777. var engine = this.getScene().getEngine();
  19778. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19779. };
  19780. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19781. return null;
  19782. };
  19783. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19784. this._colorShader.dispose();
  19785. _super.prototype.dispose.call(this, doNotRecurse);
  19786. };
  19787. return LinesMesh;
  19788. })(BABYLON.Mesh);
  19789. BABYLON.LinesMesh = LinesMesh;
  19790. })(BABYLON || (BABYLON = {}));
  19791. var BABYLON;
  19792. (function (BABYLON) {
  19793. var OutlineRenderer = (function () {
  19794. function OutlineRenderer(scene) {
  19795. this._scene = scene;
  19796. }
  19797. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19798. var scene = this._scene;
  19799. var engine = this._scene.getEngine();
  19800. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19801. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19802. return;
  19803. }
  19804. var mesh = subMesh.getRenderingMesh();
  19805. var material = subMesh.getMaterial();
  19806. engine.enableEffect(this._effect);
  19807. this._effect.setFloat("offset", mesh.outlineWidth);
  19808. this._effect.setColor3("color", mesh.outlineColor);
  19809. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19810. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19811. if (useBones) {
  19812. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19813. }
  19814. mesh._bind(subMesh, this._effect, false);
  19815. if (material && material.needAlphaTesting()) {
  19816. var alphaTexture = material.getAlphaTestTexture();
  19817. this._effect.setTexture("diffuseSampler", alphaTexture);
  19818. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19819. }
  19820. if (hardwareInstancedRendering) {
  19821. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19822. } else {
  19823. if (batch.renderSelf[subMesh._id]) {
  19824. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19825. mesh._draw(subMesh, true);
  19826. }
  19827. if (batch.visibleInstances[subMesh._id]) {
  19828. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19829. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19830. this._effect.setMatrix("world", instance.getWorldMatrix());
  19831. mesh._draw(subMesh, true);
  19832. }
  19833. }
  19834. }
  19835. };
  19836. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19837. var defines = [];
  19838. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19839. var mesh = subMesh.getMesh();
  19840. var material = subMesh.getMaterial();
  19841. if (material && material.needAlphaTesting()) {
  19842. defines.push("#define ALPHATEST");
  19843. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19844. attribs.push(BABYLON.VertexBuffer.UVKind);
  19845. defines.push("#define UV1");
  19846. }
  19847. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19848. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19849. defines.push("#define UV2");
  19850. }
  19851. }
  19852. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19853. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19854. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19855. defines.push("#define BONES");
  19856. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19857. }
  19858. if (useInstances) {
  19859. defines.push("#define INSTANCES");
  19860. attribs.push("world0");
  19861. attribs.push("world1");
  19862. attribs.push("world2");
  19863. attribs.push("world3");
  19864. }
  19865. var join = defines.join("\n");
  19866. if (this._cachedDefines != join) {
  19867. this._cachedDefines = join;
  19868. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  19869. }
  19870. return this._effect.isReady();
  19871. };
  19872. return OutlineRenderer;
  19873. })();
  19874. BABYLON.OutlineRenderer = OutlineRenderer;
  19875. })(BABYLON || (BABYLON = {}));
  19876. var BABYLON;
  19877. (function (BABYLON) {
  19878. var MeshAssetTask = (function () {
  19879. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  19880. this.name = name;
  19881. this.meshesNames = meshesNames;
  19882. this.rootUrl = rootUrl;
  19883. this.sceneFilename = sceneFilename;
  19884. this.isCompleted = false;
  19885. }
  19886. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19887. var _this = this;
  19888. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  19889. _this.loadedMeshes = meshes;
  19890. _this.loadedParticleSystems = particleSystems;
  19891. _this.loadedSkeletons = skeletons;
  19892. _this.isCompleted = true;
  19893. if (_this.onSuccess) {
  19894. _this.onSuccess(_this);
  19895. }
  19896. onSuccess();
  19897. }, null, function () {
  19898. if (_this.onError) {
  19899. _this.onError(_this);
  19900. }
  19901. onError();
  19902. });
  19903. };
  19904. return MeshAssetTask;
  19905. })();
  19906. BABYLON.MeshAssetTask = MeshAssetTask;
  19907. var TextFileAssetTask = (function () {
  19908. function TextFileAssetTask(name, url) {
  19909. this.name = name;
  19910. this.url = url;
  19911. this.isCompleted = false;
  19912. }
  19913. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19914. var _this = this;
  19915. BABYLON.Tools.LoadFile(this.url, function (data) {
  19916. _this.text = data;
  19917. _this.isCompleted = true;
  19918. if (_this.onSuccess) {
  19919. _this.onSuccess(_this);
  19920. }
  19921. onSuccess();
  19922. }, null, scene.database, false, function () {
  19923. if (_this.onError) {
  19924. _this.onError(_this);
  19925. }
  19926. onError();
  19927. });
  19928. };
  19929. return TextFileAssetTask;
  19930. })();
  19931. BABYLON.TextFileAssetTask = TextFileAssetTask;
  19932. var BinaryFileAssetTask = (function () {
  19933. function BinaryFileAssetTask(name, url) {
  19934. this.name = name;
  19935. this.url = url;
  19936. this.isCompleted = false;
  19937. }
  19938. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19939. var _this = this;
  19940. BABYLON.Tools.LoadFile(this.url, function (data) {
  19941. _this.data = data;
  19942. _this.isCompleted = true;
  19943. if (_this.onSuccess) {
  19944. _this.onSuccess(_this);
  19945. }
  19946. onSuccess();
  19947. }, null, scene.database, true, function () {
  19948. if (_this.onError) {
  19949. _this.onError(_this);
  19950. }
  19951. onError();
  19952. });
  19953. };
  19954. return BinaryFileAssetTask;
  19955. })();
  19956. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  19957. var ImageAssetTask = (function () {
  19958. function ImageAssetTask(name, url) {
  19959. this.name = name;
  19960. this.url = url;
  19961. this.isCompleted = false;
  19962. }
  19963. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19964. var _this = this;
  19965. var img = new Image();
  19966. img.onload = function () {
  19967. _this.image = img;
  19968. _this.isCompleted = true;
  19969. if (_this.onSuccess) {
  19970. _this.onSuccess(_this);
  19971. }
  19972. onSuccess();
  19973. };
  19974. img.onerror = function () {
  19975. if (_this.onError) {
  19976. _this.onError(_this);
  19977. }
  19978. onError();
  19979. };
  19980. img.src = this.url;
  19981. };
  19982. return ImageAssetTask;
  19983. })();
  19984. BABYLON.ImageAssetTask = ImageAssetTask;
  19985. var AssetsManager = (function () {
  19986. function AssetsManager(scene) {
  19987. this._tasks = new Array();
  19988. this._waitingTasksCount = 0;
  19989. this.useDefaultLoadingScreen = true;
  19990. this._scene = scene;
  19991. }
  19992. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  19993. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  19994. this._tasks.push(task);
  19995. return task;
  19996. };
  19997. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  19998. var task = new TextFileAssetTask(taskName, url);
  19999. this._tasks.push(task);
  20000. return task;
  20001. };
  20002. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20003. var task = new BinaryFileAssetTask(taskName, url);
  20004. this._tasks.push(task);
  20005. return task;
  20006. };
  20007. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20008. var task = new ImageAssetTask(taskName, url);
  20009. this._tasks.push(task);
  20010. return task;
  20011. };
  20012. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20013. this._waitingTasksCount--;
  20014. if (this._waitingTasksCount === 0) {
  20015. if (this.onFinish) {
  20016. this.onFinish(this._tasks);
  20017. }
  20018. this._scene.getEngine().hideLoadingUI();
  20019. }
  20020. };
  20021. AssetsManager.prototype._runTask = function (task) {
  20022. var _this = this;
  20023. task.run(this._scene, function () {
  20024. if (_this.onTaskSuccess) {
  20025. _this.onTaskSuccess(task);
  20026. }
  20027. _this._decreaseWaitingTasksCount();
  20028. }, function () {
  20029. if (_this.onTaskError) {
  20030. _this.onTaskError(task);
  20031. }
  20032. _this._decreaseWaitingTasksCount();
  20033. });
  20034. };
  20035. AssetsManager.prototype.reset = function () {
  20036. this._tasks = new Array();
  20037. return this;
  20038. };
  20039. AssetsManager.prototype.load = function () {
  20040. this._waitingTasksCount = this._tasks.length;
  20041. if (this._waitingTasksCount === 0) {
  20042. if (this.onFinish) {
  20043. this.onFinish(this._tasks);
  20044. }
  20045. return this;
  20046. }
  20047. if (this.useDefaultLoadingScreen) {
  20048. this._scene.getEngine().displayLoadingUI();
  20049. }
  20050. for (var index = 0; index < this._tasks.length; index++) {
  20051. var task = this._tasks[index];
  20052. this._runTask(task);
  20053. }
  20054. return this;
  20055. };
  20056. return AssetsManager;
  20057. })();
  20058. BABYLON.AssetsManager = AssetsManager;
  20059. })(BABYLON || (BABYLON = {}));