babylon.2.2.max.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = 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);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. source.x = source.x / viewportWidth * 2 - 1;
  807. source.y = -(source.y / viewportHeight * 2 - 1);
  808. var vector = Vector3.TransformCoordinates(source, matrix);
  809. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  810. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  811. vector = vector.scale(1.0 / num);
  812. }
  813. return vector;
  814. };
  815. Vector3.Minimize = function (left, right) {
  816. var min = left.clone();
  817. min.MinimizeInPlace(right);
  818. return min;
  819. };
  820. Vector3.Maximize = function (left, right) {
  821. var max = left.clone();
  822. max.MaximizeInPlace(right);
  823. return max;
  824. };
  825. Vector3.Distance = function (value1, value2) {
  826. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  827. };
  828. Vector3.DistanceSquared = function (value1, value2) {
  829. var x = value1.x - value2.x;
  830. var y = value1.y - value2.y;
  831. var z = value1.z - value2.z;
  832. return (x * x) + (y * y) + (z * z);
  833. };
  834. Vector3.Center = function (value1, value2) {
  835. var center = value1.add(value2);
  836. center.scaleInPlace(0.5);
  837. return center;
  838. };
  839. /**
  840. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  841. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  842. * to something in order to rotate it from its local system to the given target system.
  843. */
  844. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  845. var u = Vector3.Normalize(axis1);
  846. var w = Vector3.Normalize(axis3);
  847. // world axis
  848. var X = Axis.X;
  849. var Y = Axis.Y;
  850. // equation unknowns and vars
  851. var yaw = 0.0;
  852. var pitch = 0.0;
  853. var roll = 0.0;
  854. var x = 0.0;
  855. var y = 0.0;
  856. var z = 0.0;
  857. var t = 0.0;
  858. var sign = -1.0;
  859. var nbRevert = 0;
  860. var cross;
  861. var dot = 0.0;
  862. // step 1 : rotation around w
  863. // Rv3(u) = u1, and u1 belongs to plane xOz
  864. // Rv3(w) = w1 = w invariant
  865. var u1;
  866. var v1;
  867. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  868. z = 1.0;
  869. }
  870. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  871. x = 1.0;
  872. }
  873. else {
  874. t = w.z / w.x;
  875. x = -t * Math.sqrt(1 / (1 + t * t));
  876. z = Math.sqrt(1 / (1 + t * t));
  877. }
  878. u1 = new Vector3(x, y, z);
  879. u1.normalize();
  880. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  881. v1.normalize();
  882. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  883. cross.normalize();
  884. if (Vector3.Dot(w, cross) < 0) {
  885. sign = 1.0;
  886. }
  887. dot = Vector3.Dot(u, u1);
  888. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  889. roll = Math.acos(dot) * sign;
  890. if (Vector3.Dot(u1, X) < 0) {
  891. roll = Math.PI + roll;
  892. u1 = u1.scaleInPlace(-1);
  893. v1 = v1.scaleInPlace(-1);
  894. nbRevert++;
  895. }
  896. // step 2 : rotate around u1
  897. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  898. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  899. var w2;
  900. var v2;
  901. x = 0.0;
  902. y = 0.0;
  903. z = 0.0;
  904. sign = -1;
  905. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  906. x = 1.0;
  907. }
  908. else {
  909. t = u1.z / u1.x;
  910. x = -t * Math.sqrt(1 / (1 + t * t));
  911. z = Math.sqrt(1 / (1 + t * t));
  912. }
  913. w2 = new Vector3(x, y, z);
  914. w2.normalize();
  915. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  916. v2.normalize();
  917. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  918. cross.normalize();
  919. if (Vector3.Dot(u1, cross) < 0) {
  920. sign = 1.0;
  921. }
  922. dot = Vector3.Dot(w, w2);
  923. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  924. pitch = Math.acos(dot) * sign;
  925. if (Vector3.Dot(v2, Y) < 0) {
  926. pitch = Math.PI + pitch;
  927. v2 = v2.scaleInPlace(-1);
  928. w2 = w2.scaleInPlace(-1);
  929. nbRevert++;
  930. }
  931. // step 3 : rotate around v2
  932. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  933. sign = -1;
  934. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  935. cross.normalize();
  936. if (Vector3.Dot(cross, Y) < 0) {
  937. sign = 1.0;
  938. }
  939. dot = Vector3.Dot(u1, X);
  940. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  941. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  942. if (dot < 0 && nbRevert < 2) {
  943. yaw = Math.PI + yaw;
  944. }
  945. return new Vector3(pitch, yaw, roll);
  946. };
  947. return Vector3;
  948. })();
  949. BABYLON.Vector3 = Vector3;
  950. //Vector4 class created for EulerAngle class conversion to Quaternion
  951. var Vector4 = (function () {
  952. function Vector4(x, y, z, w) {
  953. this.x = x;
  954. this.y = y;
  955. this.z = z;
  956. this.w = w;
  957. }
  958. Vector4.prototype.toString = function () {
  959. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  960. };
  961. // Operators
  962. Vector4.prototype.asArray = function () {
  963. var result = [];
  964. this.toArray(result, 0);
  965. return result;
  966. };
  967. Vector4.prototype.toArray = function (array, index) {
  968. if (index === undefined) {
  969. index = 0;
  970. }
  971. array[index] = this.x;
  972. array[index + 1] = this.y;
  973. array[index + 2] = this.z;
  974. array[index + 3] = this.w;
  975. return this;
  976. };
  977. Vector4.prototype.addInPlace = function (otherVector) {
  978. this.x += otherVector.x;
  979. this.y += otherVector.y;
  980. this.z += otherVector.z;
  981. this.w += otherVector.w;
  982. return this;
  983. };
  984. Vector4.prototype.add = function (otherVector) {
  985. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  986. };
  987. Vector4.prototype.addToRef = function (otherVector, result) {
  988. result.x = this.x + otherVector.x;
  989. result.y = this.y + otherVector.y;
  990. result.z = this.z + otherVector.z;
  991. result.w = this.w + otherVector.w;
  992. return this;
  993. };
  994. Vector4.prototype.subtractInPlace = function (otherVector) {
  995. this.x -= otherVector.x;
  996. this.y -= otherVector.y;
  997. this.z -= otherVector.z;
  998. this.w -= otherVector.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.subtract = function (otherVector) {
  1002. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1003. };
  1004. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1005. result.x = this.x - otherVector.x;
  1006. result.y = this.y - otherVector.y;
  1007. result.z = this.z - otherVector.z;
  1008. result.w = this.w - otherVector.w;
  1009. return this;
  1010. };
  1011. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1012. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1013. };
  1014. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1015. result.x = this.x - x;
  1016. result.y = this.y - y;
  1017. result.z = this.z - z;
  1018. result.w = this.w - w;
  1019. return this;
  1020. };
  1021. Vector4.prototype.negate = function () {
  1022. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1023. };
  1024. Vector4.prototype.scaleInPlace = function (scale) {
  1025. this.x *= scale;
  1026. this.y *= scale;
  1027. this.z *= scale;
  1028. this.w *= scale;
  1029. return this;
  1030. };
  1031. Vector4.prototype.scale = function (scale) {
  1032. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1033. };
  1034. Vector4.prototype.scaleToRef = function (scale, result) {
  1035. result.x = this.x * scale;
  1036. result.y = this.y * scale;
  1037. result.z = this.z * scale;
  1038. result.w = this.w * scale;
  1039. };
  1040. Vector4.prototype.equals = function (otherVector) {
  1041. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1042. };
  1043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1044. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1045. return otherVector
  1046. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1047. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1048. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1049. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1050. };
  1051. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1052. return this.x === x && this.y === y && this.z === z && this.w === w;
  1053. };
  1054. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1055. this.x *= otherVector.x;
  1056. this.y *= otherVector.y;
  1057. this.z *= otherVector.z;
  1058. this.w *= otherVector.w;
  1059. return this;
  1060. };
  1061. Vector4.prototype.multiply = function (otherVector) {
  1062. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1063. };
  1064. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1065. result.x = this.x * otherVector.x;
  1066. result.y = this.y * otherVector.y;
  1067. result.z = this.z * otherVector.z;
  1068. result.w = this.w * otherVector.w;
  1069. return this;
  1070. };
  1071. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1072. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1073. };
  1074. Vector4.prototype.divide = function (otherVector) {
  1075. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1076. };
  1077. Vector4.prototype.divideToRef = function (otherVector, result) {
  1078. result.x = this.x / otherVector.x;
  1079. result.y = this.y / otherVector.y;
  1080. result.z = this.z / otherVector.z;
  1081. result.w = this.w / otherVector.w;
  1082. return this;
  1083. };
  1084. Vector4.prototype.MinimizeInPlace = function (other) {
  1085. if (other.x < this.x)
  1086. this.x = other.x;
  1087. if (other.y < this.y)
  1088. this.y = other.y;
  1089. if (other.z < this.z)
  1090. this.z = other.z;
  1091. if (other.w < this.w)
  1092. this.w = other.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.MaximizeInPlace = function (other) {
  1096. if (other.x > this.x)
  1097. this.x = other.x;
  1098. if (other.y > this.y)
  1099. this.y = other.y;
  1100. if (other.z > this.z)
  1101. this.z = other.z;
  1102. if (other.w > this.w)
  1103. this.w = other.w;
  1104. return this;
  1105. };
  1106. // Properties
  1107. Vector4.prototype.length = function () {
  1108. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1109. };
  1110. Vector4.prototype.lengthSquared = function () {
  1111. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1112. };
  1113. // Methods
  1114. Vector4.prototype.normalize = function () {
  1115. var len = this.length();
  1116. if (len === 0)
  1117. return this;
  1118. var num = 1.0 / len;
  1119. this.x *= num;
  1120. this.y *= num;
  1121. this.z *= num;
  1122. this.w *= num;
  1123. return this;
  1124. };
  1125. Vector4.prototype.clone = function () {
  1126. return new Vector4(this.x, this.y, this.z, this.w);
  1127. };
  1128. Vector4.prototype.copyFrom = function (source) {
  1129. this.x = source.x;
  1130. this.y = source.y;
  1131. this.z = source.z;
  1132. this.w = source.w;
  1133. return this;
  1134. };
  1135. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1136. this.x = x;
  1137. this.y = y;
  1138. this.z = z;
  1139. this.w = w;
  1140. return this;
  1141. };
  1142. // Statics
  1143. Vector4.FromArray = function (array, offset) {
  1144. if (!offset) {
  1145. offset = 0;
  1146. }
  1147. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1148. };
  1149. Vector4.FromArrayToRef = function (array, offset, result) {
  1150. result.x = array[offset];
  1151. result.y = array[offset + 1];
  1152. result.z = array[offset + 2];
  1153. result.w = array[offset + 3];
  1154. };
  1155. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1156. result.x = array[offset];
  1157. result.y = array[offset + 1];
  1158. result.z = array[offset + 2];
  1159. result.w = array[offset + 3];
  1160. };
  1161. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1162. result.x = x;
  1163. result.y = y;
  1164. result.z = z;
  1165. result.w = w;
  1166. };
  1167. Vector4.Zero = function () {
  1168. return new Vector4(0, 0, 0, 0);
  1169. };
  1170. Vector4.Normalize = function (vector) {
  1171. var result = Vector4.Zero();
  1172. Vector4.NormalizeToRef(vector, result);
  1173. return result;
  1174. };
  1175. Vector4.NormalizeToRef = function (vector, result) {
  1176. result.copyFrom(vector);
  1177. result.normalize();
  1178. };
  1179. Vector4.Minimize = function (left, right) {
  1180. var min = left.clone();
  1181. min.MinimizeInPlace(right);
  1182. return min;
  1183. };
  1184. Vector4.Maximize = function (left, right) {
  1185. var max = left.clone();
  1186. max.MaximizeInPlace(right);
  1187. return max;
  1188. };
  1189. Vector4.Distance = function (value1, value2) {
  1190. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1191. };
  1192. Vector4.DistanceSquared = function (value1, value2) {
  1193. var x = value1.x - value2.x;
  1194. var y = value1.y - value2.y;
  1195. var z = value1.z - value2.z;
  1196. var w = value1.w - value2.w;
  1197. return (x * x) + (y * y) + (z * z) + (w * w);
  1198. };
  1199. Vector4.Center = function (value1, value2) {
  1200. var center = value1.add(value2);
  1201. center.scaleInPlace(0.5);
  1202. return center;
  1203. };
  1204. return Vector4;
  1205. })();
  1206. BABYLON.Vector4 = Vector4;
  1207. var Quaternion = (function () {
  1208. function Quaternion(x, y, z, w) {
  1209. if (x === void 0) { x = 0; }
  1210. if (y === void 0) { y = 0; }
  1211. if (z === void 0) { z = 0; }
  1212. if (w === void 0) { w = 1; }
  1213. this.x = x;
  1214. this.y = y;
  1215. this.z = z;
  1216. this.w = w;
  1217. }
  1218. Quaternion.prototype.toString = function () {
  1219. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1220. };
  1221. Quaternion.prototype.asArray = function () {
  1222. return [this.x, this.y, this.z, this.w];
  1223. };
  1224. Quaternion.prototype.equals = function (otherQuaternion) {
  1225. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1226. };
  1227. Quaternion.prototype.clone = function () {
  1228. return new Quaternion(this.x, this.y, this.z, this.w);
  1229. };
  1230. Quaternion.prototype.copyFrom = function (other) {
  1231. this.x = other.x;
  1232. this.y = other.y;
  1233. this.z = other.z;
  1234. this.w = other.w;
  1235. return this;
  1236. };
  1237. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1238. this.x = x;
  1239. this.y = y;
  1240. this.z = z;
  1241. this.w = w;
  1242. return this;
  1243. };
  1244. Quaternion.prototype.add = function (other) {
  1245. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1246. };
  1247. Quaternion.prototype.subtract = function (other) {
  1248. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1249. };
  1250. Quaternion.prototype.scale = function (value) {
  1251. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1252. };
  1253. Quaternion.prototype.multiply = function (q1) {
  1254. var result = new Quaternion(0, 0, 0, 1.0);
  1255. this.multiplyToRef(q1, result);
  1256. return result;
  1257. };
  1258. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1259. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1260. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1261. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1262. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1263. result.copyFromFloats(x, y, z, w);
  1264. return this;
  1265. };
  1266. Quaternion.prototype.length = function () {
  1267. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1268. };
  1269. Quaternion.prototype.normalize = function () {
  1270. var length = 1.0 / this.length();
  1271. this.x *= length;
  1272. this.y *= length;
  1273. this.z *= length;
  1274. this.w *= length;
  1275. return this;
  1276. };
  1277. Quaternion.prototype.toEulerAngles = function () {
  1278. var result = Vector3.Zero();
  1279. this.toEulerAnglesToRef(result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1283. //result is an EulerAngles in the in the z-x-z convention
  1284. var qx = this.x;
  1285. var qy = this.y;
  1286. var qz = this.z;
  1287. var qw = this.w;
  1288. var qxy = qx * qy;
  1289. var qxz = qx * qz;
  1290. var qwy = qw * qy;
  1291. var qwz = qw * qz;
  1292. var qwx = qw * qx;
  1293. var qyz = qy * qz;
  1294. var sqx = qx * qx;
  1295. var sqy = qy * qy;
  1296. var determinant = sqx + sqy;
  1297. if (determinant !== 0.000 && determinant !== 1.000) {
  1298. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1299. result.y = Math.acos(1 - 2 * determinant);
  1300. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1301. }
  1302. else {
  1303. if (determinant === 0.0) {
  1304. result.x = 0.0;
  1305. result.y = 0.0;
  1306. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1307. }
  1308. else {
  1309. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1310. result.y = Math.PI;
  1311. result.z = 0.0;
  1312. }
  1313. }
  1314. return this;
  1315. };
  1316. Quaternion.prototype.toRotationMatrix = function (result) {
  1317. var xx = this.x * this.x;
  1318. var yy = this.y * this.y;
  1319. var zz = this.z * this.z;
  1320. var xy = this.x * this.y;
  1321. var zw = this.z * this.w;
  1322. var zx = this.z * this.x;
  1323. var yw = this.y * this.w;
  1324. var yz = this.y * this.z;
  1325. var xw = this.x * this.w;
  1326. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1327. result.m[1] = 2.0 * (xy + zw);
  1328. result.m[2] = 2.0 * (zx - yw);
  1329. result.m[3] = 0;
  1330. result.m[4] = 2.0 * (xy - zw);
  1331. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1332. result.m[6] = 2.0 * (yz + xw);
  1333. result.m[7] = 0;
  1334. result.m[8] = 2.0 * (zx + yw);
  1335. result.m[9] = 2.0 * (yz - xw);
  1336. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1337. result.m[11] = 0;
  1338. result.m[12] = 0;
  1339. result.m[13] = 0;
  1340. result.m[14] = 0;
  1341. result.m[15] = 1.0;
  1342. return this;
  1343. };
  1344. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1345. Quaternion.FromRotationMatrixToRef(matrix, this);
  1346. return this;
  1347. };
  1348. // Statics
  1349. Quaternion.FromRotationMatrix = function (matrix) {
  1350. var result = new Quaternion();
  1351. Quaternion.FromRotationMatrixToRef(matrix, result);
  1352. return result;
  1353. };
  1354. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1355. var data = matrix.m;
  1356. var m11 = data[0], m12 = data[4], m13 = data[8];
  1357. var m21 = data[1], m22 = data[5], m23 = data[9];
  1358. var m31 = data[2], m32 = data[6], m33 = data[10];
  1359. var trace = m11 + m22 + m33;
  1360. var s;
  1361. if (trace > 0) {
  1362. s = 0.5 / Math.sqrt(trace + 1.0);
  1363. result.w = 0.25 / s;
  1364. result.x = (m32 - m23) * s;
  1365. result.y = (m13 - m31) * s;
  1366. result.z = (m21 - m12) * s;
  1367. }
  1368. else if (m11 > m22 && m11 > m33) {
  1369. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1370. result.w = (m32 - m23) / s;
  1371. result.x = 0.25 * s;
  1372. result.y = (m12 + m21) / s;
  1373. result.z = (m13 + m31) / s;
  1374. }
  1375. else if (m22 > m33) {
  1376. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1377. result.w = (m13 - m31) / s;
  1378. result.x = (m12 + m21) / s;
  1379. result.y = 0.25 * s;
  1380. result.z = (m23 + m32) / s;
  1381. }
  1382. else {
  1383. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1384. result.w = (m21 - m12) / s;
  1385. result.x = (m13 + m31) / s;
  1386. result.y = (m23 + m32) / s;
  1387. result.z = 0.25 * s;
  1388. }
  1389. };
  1390. Quaternion.Inverse = function (q) {
  1391. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1392. };
  1393. Quaternion.Identity = function () {
  1394. return new Quaternion(0, 0, 0, 1);
  1395. };
  1396. Quaternion.RotationAxis = function (axis, angle) {
  1397. var result = new Quaternion();
  1398. var sin = Math.sin(angle / 2);
  1399. result.w = Math.cos(angle / 2);
  1400. result.x = axis.x * sin;
  1401. result.y = axis.y * sin;
  1402. result.z = axis.z * sin;
  1403. return result;
  1404. };
  1405. Quaternion.FromArray = function (array, offset) {
  1406. if (!offset) {
  1407. offset = 0;
  1408. }
  1409. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1410. };
  1411. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1412. var result = new Quaternion();
  1413. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1414. return result;
  1415. };
  1416. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1417. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1418. var halfRoll = roll * 0.5;
  1419. var halfPitch = pitch * 0.5;
  1420. var halfYaw = yaw * 0.5;
  1421. var sinRoll = Math.sin(halfRoll);
  1422. var cosRoll = Math.cos(halfRoll);
  1423. var sinPitch = Math.sin(halfPitch);
  1424. var cosPitch = Math.cos(halfPitch);
  1425. var sinYaw = Math.sin(halfYaw);
  1426. var cosYaw = Math.cos(halfYaw);
  1427. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1428. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1429. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1430. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1431. };
  1432. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1433. var result = new Quaternion();
  1434. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1435. return result;
  1436. };
  1437. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1438. // Produces a quaternion from Euler angles in the z-x-z orientation
  1439. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1440. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1441. var halfBeta = beta * 0.5;
  1442. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1443. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1444. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1445. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1446. };
  1447. Quaternion.Slerp = function (left, right, amount) {
  1448. var num2;
  1449. var num3;
  1450. var num = amount;
  1451. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1452. var flag = false;
  1453. if (num4 < 0) {
  1454. flag = true;
  1455. num4 = -num4;
  1456. }
  1457. if (num4 > 0.999999) {
  1458. num3 = 1 - num;
  1459. num2 = flag ? -num : num;
  1460. }
  1461. else {
  1462. var num5 = Math.acos(num4);
  1463. var num6 = (1.0 / Math.sin(num5));
  1464. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1465. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1466. }
  1467. 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));
  1468. };
  1469. return Quaternion;
  1470. })();
  1471. BABYLON.Quaternion = Quaternion;
  1472. var Matrix = (function () {
  1473. function Matrix() {
  1474. this.m = new Float32Array(16);
  1475. }
  1476. // Properties
  1477. Matrix.prototype.isIdentity = function () {
  1478. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1479. return false;
  1480. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1481. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1482. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1483. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1484. return false;
  1485. return true;
  1486. };
  1487. Matrix.prototype.determinant = function () {
  1488. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1489. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1490. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1491. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1492. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1493. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1494. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1495. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1496. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1497. };
  1498. // Methods
  1499. Matrix.prototype.toArray = function () {
  1500. return this.m;
  1501. };
  1502. Matrix.prototype.asArray = function () {
  1503. return this.toArray();
  1504. };
  1505. Matrix.prototype.invert = function () {
  1506. this.invertToRef(this);
  1507. return this;
  1508. };
  1509. Matrix.prototype.reset = function () {
  1510. for (var index = 0; index < 16; index++) {
  1511. this.m[index] = 0;
  1512. }
  1513. return this;
  1514. };
  1515. Matrix.prototype.add = function (other) {
  1516. var result = new Matrix();
  1517. this.addToRef(other, result);
  1518. return result;
  1519. };
  1520. Matrix.prototype.addToRef = function (other, result) {
  1521. for (var index = 0; index < 16; index++) {
  1522. result.m[index] = this.m[index] + other.m[index];
  1523. }
  1524. return this;
  1525. };
  1526. Matrix.prototype.addToSelf = function (other) {
  1527. for (var index = 0; index < 16; index++) {
  1528. this.m[index] += other.m[index];
  1529. }
  1530. return this;
  1531. };
  1532. Matrix.prototype.invertToRef = function (other) {
  1533. var l1 = this.m[0];
  1534. var l2 = this.m[1];
  1535. var l3 = this.m[2];
  1536. var l4 = this.m[3];
  1537. var l5 = this.m[4];
  1538. var l6 = this.m[5];
  1539. var l7 = this.m[6];
  1540. var l8 = this.m[7];
  1541. var l9 = this.m[8];
  1542. var l10 = this.m[9];
  1543. var l11 = this.m[10];
  1544. var l12 = this.m[11];
  1545. var l13 = this.m[12];
  1546. var l14 = this.m[13];
  1547. var l15 = this.m[14];
  1548. var l16 = this.m[15];
  1549. var l17 = (l11 * l16) - (l12 * l15);
  1550. var l18 = (l10 * l16) - (l12 * l14);
  1551. var l19 = (l10 * l15) - (l11 * l14);
  1552. var l20 = (l9 * l16) - (l12 * l13);
  1553. var l21 = (l9 * l15) - (l11 * l13);
  1554. var l22 = (l9 * l14) - (l10 * l13);
  1555. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1556. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1557. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1558. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1559. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1560. var l28 = (l7 * l16) - (l8 * l15);
  1561. var l29 = (l6 * l16) - (l8 * l14);
  1562. var l30 = (l6 * l15) - (l7 * l14);
  1563. var l31 = (l5 * l16) - (l8 * l13);
  1564. var l32 = (l5 * l15) - (l7 * l13);
  1565. var l33 = (l5 * l14) - (l6 * l13);
  1566. var l34 = (l7 * l12) - (l8 * l11);
  1567. var l35 = (l6 * l12) - (l8 * l10);
  1568. var l36 = (l6 * l11) - (l7 * l10);
  1569. var l37 = (l5 * l12) - (l8 * l9);
  1570. var l38 = (l5 * l11) - (l7 * l9);
  1571. var l39 = (l5 * l10) - (l6 * l9);
  1572. other.m[0] = l23 * l27;
  1573. other.m[4] = l24 * l27;
  1574. other.m[8] = l25 * l27;
  1575. other.m[12] = l26 * l27;
  1576. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1577. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1578. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1579. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1580. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1581. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1582. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1583. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1584. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1585. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1586. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1587. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1588. return this;
  1589. };
  1590. Matrix.prototype.invertToRefSIMD = function (other) {
  1591. var src = this.m;
  1592. var dest = other.m;
  1593. var row0, row1, row2, row3;
  1594. var tmp1;
  1595. var minor0, minor1, minor2, minor3;
  1596. var det;
  1597. // Load the 4 rows
  1598. var src0 = SIMD.float32x4.load(src, 0);
  1599. var src1 = SIMD.float32x4.load(src, 4);
  1600. var src2 = SIMD.float32x4.load(src, 8);
  1601. var src3 = SIMD.float32x4.load(src, 12);
  1602. // Transpose the source matrix. Sort of. Not a true transpose operation
  1603. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1604. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1605. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1606. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1607. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1608. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1609. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1610. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1611. // This is a true transposition, but it will lead to an incorrect result
  1612. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1613. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1614. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1615. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1616. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1617. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1618. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1619. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1620. // ----
  1621. tmp1 = SIMD.float32x4.mul(row2, row3);
  1622. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1623. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1624. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1625. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1626. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1627. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1628. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1629. // ----
  1630. tmp1 = SIMD.float32x4.mul(row1, row2);
  1631. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1632. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1633. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1634. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1635. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1636. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1637. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1638. // ----
  1639. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1640. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1641. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1643. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1646. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1647. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(row0, row1);
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1652. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1653. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1654. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1655. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1656. // ----
  1657. tmp1 = SIMD.float32x4.mul(row0, row3);
  1658. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1659. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1660. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1661. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1662. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1663. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1664. // ----
  1665. tmp1 = SIMD.float32x4.mul(row0, row2);
  1666. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1667. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1668. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1669. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1670. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1671. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1672. // Compute determinant
  1673. det = SIMD.float32x4.mul(row0, minor0);
  1674. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1675. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1676. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1677. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1678. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1679. // These shuffles aren't necessary if the faulty transposition is done
  1680. // up at the top of this function.
  1681. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1682. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1683. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1684. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1685. // Compute final values by multiplying with 1/det
  1686. minor0 = SIMD.float32x4.mul(det, minor0);
  1687. minor1 = SIMD.float32x4.mul(det, minor1);
  1688. minor2 = SIMD.float32x4.mul(det, minor2);
  1689. minor3 = SIMD.float32x4.mul(det, minor3);
  1690. SIMD.float32x4.store(dest, 0, minor0);
  1691. SIMD.float32x4.store(dest, 4, minor1);
  1692. SIMD.float32x4.store(dest, 8, minor2);
  1693. SIMD.float32x4.store(dest, 12, minor3);
  1694. return this;
  1695. };
  1696. Matrix.prototype.setTranslation = function (vector3) {
  1697. this.m[12] = vector3.x;
  1698. this.m[13] = vector3.y;
  1699. this.m[14] = vector3.z;
  1700. return this;
  1701. };
  1702. Matrix.prototype.multiply = function (other) {
  1703. var result = new Matrix();
  1704. this.multiplyToRef(other, result);
  1705. return result;
  1706. };
  1707. Matrix.prototype.copyFrom = function (other) {
  1708. for (var index = 0; index < 16; index++) {
  1709. this.m[index] = other.m[index];
  1710. }
  1711. return this;
  1712. };
  1713. Matrix.prototype.copyToArray = function (array, offset) {
  1714. if (offset === void 0) { offset = 0; }
  1715. for (var index = 0; index < 16; index++) {
  1716. array[offset + index] = this.m[index];
  1717. }
  1718. return this;
  1719. };
  1720. Matrix.prototype.multiplyToRef = function (other, result) {
  1721. this.multiplyToArray(other, result.m, 0);
  1722. return this;
  1723. };
  1724. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1725. var tm0 = this.m[0];
  1726. var tm1 = this.m[1];
  1727. var tm2 = this.m[2];
  1728. var tm3 = this.m[3];
  1729. var tm4 = this.m[4];
  1730. var tm5 = this.m[5];
  1731. var tm6 = this.m[6];
  1732. var tm7 = this.m[7];
  1733. var tm8 = this.m[8];
  1734. var tm9 = this.m[9];
  1735. var tm10 = this.m[10];
  1736. var tm11 = this.m[11];
  1737. var tm12 = this.m[12];
  1738. var tm13 = this.m[13];
  1739. var tm14 = this.m[14];
  1740. var tm15 = this.m[15];
  1741. var om0 = other.m[0];
  1742. var om1 = other.m[1];
  1743. var om2 = other.m[2];
  1744. var om3 = other.m[3];
  1745. var om4 = other.m[4];
  1746. var om5 = other.m[5];
  1747. var om6 = other.m[6];
  1748. var om7 = other.m[7];
  1749. var om8 = other.m[8];
  1750. var om9 = other.m[9];
  1751. var om10 = other.m[10];
  1752. var om11 = other.m[11];
  1753. var om12 = other.m[12];
  1754. var om13 = other.m[13];
  1755. var om14 = other.m[14];
  1756. var om15 = other.m[15];
  1757. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1758. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1759. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1760. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1761. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1762. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1763. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1764. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1765. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1766. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1767. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1768. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1769. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1770. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1771. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1772. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1773. return this;
  1774. };
  1775. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1776. if (offset === void 0) { offset = 0; }
  1777. var tm = this.m;
  1778. var om = other.m;
  1779. var om0 = SIMD.float32x4.load(om, 0);
  1780. var om1 = SIMD.float32x4.load(om, 4);
  1781. var om2 = SIMD.float32x4.load(om, 8);
  1782. var om3 = SIMD.float32x4.load(om, 12);
  1783. var tm0 = SIMD.float32x4.load(tm, 0);
  1784. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1785. var tm1 = SIMD.float32x4.load(tm, 4);
  1786. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1787. var tm2 = SIMD.float32x4.load(tm, 8);
  1788. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1789. var tm3 = SIMD.float32x4.load(tm, 12);
  1790. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1791. };
  1792. Matrix.prototype.equals = function (value) {
  1793. return value &&
  1794. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1795. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1796. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1797. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1798. };
  1799. Matrix.prototype.clone = function () {
  1800. 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]);
  1801. };
  1802. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1803. translation.x = this.m[12];
  1804. translation.y = this.m[13];
  1805. translation.z = this.m[14];
  1806. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1807. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1808. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1809. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1810. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1811. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1812. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1813. rotation.x = 0;
  1814. rotation.y = 0;
  1815. rotation.z = 0;
  1816. rotation.w = 1;
  1817. return false;
  1818. }
  1819. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1820. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1821. return true;
  1822. };
  1823. // Statics
  1824. Matrix.FromArray = function (array, offset) {
  1825. var result = new Matrix();
  1826. if (!offset) {
  1827. offset = 0;
  1828. }
  1829. Matrix.FromArrayToRef(array, offset, result);
  1830. return result;
  1831. };
  1832. Matrix.FromArrayToRef = function (array, offset, result) {
  1833. for (var index = 0; index < 16; index++) {
  1834. result.m[index] = array[index + offset];
  1835. }
  1836. };
  1837. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1838. for (var index = 0; index < 16; index++) {
  1839. result.m[index] = array[index + offset] * scale;
  1840. }
  1841. };
  1842. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1843. result.m[0] = initialM11;
  1844. result.m[1] = initialM12;
  1845. result.m[2] = initialM13;
  1846. result.m[3] = initialM14;
  1847. result.m[4] = initialM21;
  1848. result.m[5] = initialM22;
  1849. result.m[6] = initialM23;
  1850. result.m[7] = initialM24;
  1851. result.m[8] = initialM31;
  1852. result.m[9] = initialM32;
  1853. result.m[10] = initialM33;
  1854. result.m[11] = initialM34;
  1855. result.m[12] = initialM41;
  1856. result.m[13] = initialM42;
  1857. result.m[14] = initialM43;
  1858. result.m[15] = initialM44;
  1859. };
  1860. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1861. var result = new Matrix();
  1862. result.m[0] = initialM11;
  1863. result.m[1] = initialM12;
  1864. result.m[2] = initialM13;
  1865. result.m[3] = initialM14;
  1866. result.m[4] = initialM21;
  1867. result.m[5] = initialM22;
  1868. result.m[6] = initialM23;
  1869. result.m[7] = initialM24;
  1870. result.m[8] = initialM31;
  1871. result.m[9] = initialM32;
  1872. result.m[10] = initialM33;
  1873. result.m[11] = initialM34;
  1874. result.m[12] = initialM41;
  1875. result.m[13] = initialM42;
  1876. result.m[14] = initialM43;
  1877. result.m[15] = initialM44;
  1878. return result;
  1879. };
  1880. Matrix.Compose = function (scale, rotation, translation) {
  1881. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1882. var rotationMatrix = Matrix.Identity();
  1883. rotation.toRotationMatrix(rotationMatrix);
  1884. result = result.multiply(rotationMatrix);
  1885. result.setTranslation(translation);
  1886. return result;
  1887. };
  1888. Matrix.Identity = function () {
  1889. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1890. };
  1891. Matrix.IdentityToRef = function (result) {
  1892. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1893. };
  1894. Matrix.Zero = function () {
  1895. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1896. };
  1897. Matrix.RotationX = function (angle) {
  1898. var result = new Matrix();
  1899. Matrix.RotationXToRef(angle, result);
  1900. return result;
  1901. };
  1902. Matrix.Invert = function (source) {
  1903. var result = new Matrix();
  1904. source.invertToRef(result);
  1905. return result;
  1906. };
  1907. Matrix.RotationXToRef = function (angle, result) {
  1908. var s = Math.sin(angle);
  1909. var c = Math.cos(angle);
  1910. result.m[0] = 1.0;
  1911. result.m[15] = 1.0;
  1912. result.m[5] = c;
  1913. result.m[10] = c;
  1914. result.m[9] = -s;
  1915. result.m[6] = s;
  1916. result.m[1] = 0;
  1917. result.m[2] = 0;
  1918. result.m[3] = 0;
  1919. result.m[4] = 0;
  1920. result.m[7] = 0;
  1921. result.m[8] = 0;
  1922. result.m[11] = 0;
  1923. result.m[12] = 0;
  1924. result.m[13] = 0;
  1925. result.m[14] = 0;
  1926. };
  1927. Matrix.RotationY = function (angle) {
  1928. var result = new Matrix();
  1929. Matrix.RotationYToRef(angle, result);
  1930. return result;
  1931. };
  1932. Matrix.RotationYToRef = function (angle, result) {
  1933. var s = Math.sin(angle);
  1934. var c = Math.cos(angle);
  1935. result.m[5] = 1.0;
  1936. result.m[15] = 1.0;
  1937. result.m[0] = c;
  1938. result.m[2] = -s;
  1939. result.m[8] = s;
  1940. result.m[10] = c;
  1941. result.m[1] = 0;
  1942. result.m[3] = 0;
  1943. result.m[4] = 0;
  1944. result.m[6] = 0;
  1945. result.m[7] = 0;
  1946. result.m[9] = 0;
  1947. result.m[11] = 0;
  1948. result.m[12] = 0;
  1949. result.m[13] = 0;
  1950. result.m[14] = 0;
  1951. };
  1952. Matrix.RotationZ = function (angle) {
  1953. var result = new Matrix();
  1954. Matrix.RotationZToRef(angle, result);
  1955. return result;
  1956. };
  1957. Matrix.RotationZToRef = function (angle, result) {
  1958. var s = Math.sin(angle);
  1959. var c = Math.cos(angle);
  1960. result.m[10] = 1.0;
  1961. result.m[15] = 1.0;
  1962. result.m[0] = c;
  1963. result.m[1] = s;
  1964. result.m[4] = -s;
  1965. result.m[5] = c;
  1966. result.m[2] = 0;
  1967. result.m[3] = 0;
  1968. result.m[6] = 0;
  1969. result.m[7] = 0;
  1970. result.m[8] = 0;
  1971. result.m[9] = 0;
  1972. result.m[11] = 0;
  1973. result.m[12] = 0;
  1974. result.m[13] = 0;
  1975. result.m[14] = 0;
  1976. };
  1977. Matrix.RotationAxis = function (axis, angle) {
  1978. var s = Math.sin(-angle);
  1979. var c = Math.cos(-angle);
  1980. var c1 = 1 - c;
  1981. axis.normalize();
  1982. var result = Matrix.Zero();
  1983. result.m[0] = (axis.x * axis.x) * c1 + c;
  1984. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1985. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1986. result.m[3] = 0.0;
  1987. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1988. result.m[5] = (axis.y * axis.y) * c1 + c;
  1989. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1990. result.m[7] = 0.0;
  1991. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1992. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1993. result.m[10] = (axis.z * axis.z) * c1 + c;
  1994. result.m[11] = 0.0;
  1995. result.m[15] = 1.0;
  1996. return result;
  1997. };
  1998. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1999. var result = new Matrix();
  2000. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2001. return result;
  2002. };
  2003. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2004. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2005. this._tempQuaternion.toRotationMatrix(result);
  2006. };
  2007. Matrix.Scaling = function (x, y, z) {
  2008. var result = Matrix.Zero();
  2009. Matrix.ScalingToRef(x, y, z, result);
  2010. return result;
  2011. };
  2012. Matrix.ScalingToRef = function (x, y, z, result) {
  2013. result.m[0] = x;
  2014. result.m[1] = 0;
  2015. result.m[2] = 0;
  2016. result.m[3] = 0;
  2017. result.m[4] = 0;
  2018. result.m[5] = y;
  2019. result.m[6] = 0;
  2020. result.m[7] = 0;
  2021. result.m[8] = 0;
  2022. result.m[9] = 0;
  2023. result.m[10] = z;
  2024. result.m[11] = 0;
  2025. result.m[12] = 0;
  2026. result.m[13] = 0;
  2027. result.m[14] = 0;
  2028. result.m[15] = 1.0;
  2029. };
  2030. Matrix.Translation = function (x, y, z) {
  2031. var result = Matrix.Identity();
  2032. Matrix.TranslationToRef(x, y, z, result);
  2033. return result;
  2034. };
  2035. Matrix.TranslationToRef = function (x, y, z, result) {
  2036. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2037. };
  2038. Matrix.LookAtLH = function (eye, target, up) {
  2039. var result = Matrix.Zero();
  2040. Matrix.LookAtLHToRef(eye, target, up, result);
  2041. return result;
  2042. };
  2043. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2044. // Z axis
  2045. target.subtractToRef(eye, this._zAxis);
  2046. this._zAxis.normalize();
  2047. // X axis
  2048. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2049. this._xAxis.normalize();
  2050. // Y axis
  2051. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2052. this._yAxis.normalize();
  2053. // Eye angles
  2054. var ex = -Vector3.Dot(this._xAxis, eye);
  2055. var ey = -Vector3.Dot(this._yAxis, eye);
  2056. var ez = -Vector3.Dot(this._zAxis, eye);
  2057. 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);
  2058. };
  2059. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2060. var out = result.m;
  2061. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2062. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2063. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2064. // cc.kmVec3Subtract(f, pCenter, pEye);
  2065. var f = SIMD.float32x4.sub(center, eye);
  2066. // cc.kmVec3Normalize(f, f);
  2067. var tmp = SIMD.float32x4.mul(f, f);
  2068. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2069. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2070. // cc.kmVec3Assign(up, pUp);
  2071. // cc.kmVec3Normalize(up, up);
  2072. tmp = SIMD.float32x4.mul(up, up);
  2073. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2074. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2075. // cc.kmVec3Cross(s, f, up);
  2076. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2077. // cc.kmVec3Normalize(s, s);
  2078. tmp = SIMD.float32x4.mul(s, s);
  2079. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2080. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2081. // cc.kmVec3Cross(u, s, f);
  2082. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2083. // cc.kmVec3Normalize(s, s);
  2084. tmp = SIMD.float32x4.mul(s, s);
  2085. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2086. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2087. var zero = SIMD.float32x4.splat(0.0);
  2088. s = SIMD.float32x4.neg(s);
  2089. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2090. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2091. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2092. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2093. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2094. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2095. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2096. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2097. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2098. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2099. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2100. var b3 = SIMD.float32x4.neg(eye);
  2101. b3 = SIMD.float32x4.withW(b3, 1.0);
  2102. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2103. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2104. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2105. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2106. };
  2107. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2108. var matrix = Matrix.Zero();
  2109. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2110. return matrix;
  2111. };
  2112. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2113. var hw = 2.0 / width;
  2114. var hh = 2.0 / height;
  2115. var id = 1.0 / (zfar - znear);
  2116. var nid = znear / (znear - zfar);
  2117. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2118. };
  2119. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2120. var matrix = Matrix.Zero();
  2121. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2122. return matrix;
  2123. };
  2124. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2125. result.m[0] = 2.0 / (right - left);
  2126. result.m[1] = result.m[2] = result.m[3] = 0;
  2127. result.m[5] = 2.0 / (top - bottom);
  2128. result.m[4] = result.m[6] = result.m[7] = 0;
  2129. result.m[10] = -1.0 / (znear - zfar);
  2130. result.m[8] = result.m[9] = result.m[11] = 0;
  2131. result.m[12] = (left + right) / (left - right);
  2132. result.m[13] = (top + bottom) / (bottom - top);
  2133. result.m[14] = znear / (znear - zfar);
  2134. result.m[15] = 1.0;
  2135. };
  2136. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2137. var matrix = Matrix.Zero();
  2138. matrix.m[0] = (2.0 * znear) / width;
  2139. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2140. matrix.m[5] = (2.0 * znear) / height;
  2141. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2142. matrix.m[10] = -zfar / (znear - zfar);
  2143. matrix.m[8] = matrix.m[9] = 0.0;
  2144. matrix.m[11] = 1.0;
  2145. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2146. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2147. return matrix;
  2148. };
  2149. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2150. var matrix = Matrix.Zero();
  2151. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2152. return matrix;
  2153. };
  2154. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2155. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2156. var tan = 1.0 / (Math.tan(fov * 0.5));
  2157. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2158. if (v_fixed) {
  2159. result.m[0] = tan / aspect;
  2160. }
  2161. else {
  2162. result.m[0] = tan;
  2163. }
  2164. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2165. if (v_fixed) {
  2166. result.m[5] = tan;
  2167. }
  2168. else {
  2169. result.m[5] = tan * aspect;
  2170. }
  2171. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2172. result.m[8] = result.m[9] = 0.0;
  2173. result.m[10] = -zfar / (znear - zfar);
  2174. result.m[11] = 1.0;
  2175. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2176. result.m[14] = (znear * zfar) / (znear - zfar);
  2177. };
  2178. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2179. var cw = viewport.width;
  2180. var ch = viewport.height;
  2181. var cx = viewport.x;
  2182. var cy = viewport.y;
  2183. 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);
  2184. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2185. };
  2186. Matrix.GetAsMatrix2x2 = function (matrix) {
  2187. return new Float32Array([
  2188. matrix.m[0], matrix.m[1],
  2189. matrix.m[4], matrix.m[5]
  2190. ]);
  2191. };
  2192. Matrix.GetAsMatrix3x3 = function (matrix) {
  2193. return new Float32Array([
  2194. matrix.m[0], matrix.m[1], matrix.m[2],
  2195. matrix.m[4], matrix.m[5], matrix.m[6],
  2196. matrix.m[8], matrix.m[9], matrix.m[10]
  2197. ]);
  2198. };
  2199. Matrix.Transpose = function (matrix) {
  2200. var result = new Matrix();
  2201. result.m[0] = matrix.m[0];
  2202. result.m[1] = matrix.m[4];
  2203. result.m[2] = matrix.m[8];
  2204. result.m[3] = matrix.m[12];
  2205. result.m[4] = matrix.m[1];
  2206. result.m[5] = matrix.m[5];
  2207. result.m[6] = matrix.m[9];
  2208. result.m[7] = matrix.m[13];
  2209. result.m[8] = matrix.m[2];
  2210. result.m[9] = matrix.m[6];
  2211. result.m[10] = matrix.m[10];
  2212. result.m[11] = matrix.m[14];
  2213. result.m[12] = matrix.m[3];
  2214. result.m[13] = matrix.m[7];
  2215. result.m[14] = matrix.m[11];
  2216. result.m[15] = matrix.m[15];
  2217. return result;
  2218. };
  2219. Matrix.Reflection = function (plane) {
  2220. var matrix = new Matrix();
  2221. Matrix.ReflectionToRef(plane, matrix);
  2222. return matrix;
  2223. };
  2224. Matrix.ReflectionToRef = function (plane, result) {
  2225. plane.normalize();
  2226. var x = plane.normal.x;
  2227. var y = plane.normal.y;
  2228. var z = plane.normal.z;
  2229. var temp = -2 * x;
  2230. var temp2 = -2 * y;
  2231. var temp3 = -2 * z;
  2232. result.m[0] = (temp * x) + 1;
  2233. result.m[1] = temp2 * x;
  2234. result.m[2] = temp3 * x;
  2235. result.m[3] = 0.0;
  2236. result.m[4] = temp * y;
  2237. result.m[5] = (temp2 * y) + 1;
  2238. result.m[6] = temp3 * y;
  2239. result.m[7] = 0.0;
  2240. result.m[8] = temp * z;
  2241. result.m[9] = temp2 * z;
  2242. result.m[10] = (temp3 * z) + 1;
  2243. result.m[11] = 0.0;
  2244. result.m[12] = temp * plane.d;
  2245. result.m[13] = temp2 * plane.d;
  2246. result.m[14] = temp3 * plane.d;
  2247. result.m[15] = 1.0;
  2248. };
  2249. Matrix._tempQuaternion = new Quaternion();
  2250. Matrix._xAxis = Vector3.Zero();
  2251. Matrix._yAxis = Vector3.Zero();
  2252. Matrix._zAxis = Vector3.Zero();
  2253. return Matrix;
  2254. })();
  2255. BABYLON.Matrix = Matrix;
  2256. var Plane = (function () {
  2257. function Plane(a, b, c, d) {
  2258. this.normal = new Vector3(a, b, c);
  2259. this.d = d;
  2260. }
  2261. Plane.prototype.asArray = function () {
  2262. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2263. };
  2264. // Methods
  2265. Plane.prototype.clone = function () {
  2266. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2267. };
  2268. Plane.prototype.normalize = function () {
  2269. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2270. var magnitude = 0;
  2271. if (norm !== 0) {
  2272. magnitude = 1.0 / norm;
  2273. }
  2274. this.normal.x *= magnitude;
  2275. this.normal.y *= magnitude;
  2276. this.normal.z *= magnitude;
  2277. this.d *= magnitude;
  2278. return this;
  2279. };
  2280. Plane.prototype.transform = function (transformation) {
  2281. var transposedMatrix = Matrix.Transpose(transformation);
  2282. var x = this.normal.x;
  2283. var y = this.normal.y;
  2284. var z = this.normal.z;
  2285. var d = this.d;
  2286. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2287. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2288. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2289. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2290. return new Plane(normalX, normalY, normalZ, finalD);
  2291. };
  2292. Plane.prototype.dotCoordinate = function (point) {
  2293. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2294. };
  2295. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2296. var x1 = point2.x - point1.x;
  2297. var y1 = point2.y - point1.y;
  2298. var z1 = point2.z - point1.z;
  2299. var x2 = point3.x - point1.x;
  2300. var y2 = point3.y - point1.y;
  2301. var z2 = point3.z - point1.z;
  2302. var yz = (y1 * z2) - (z1 * y2);
  2303. var xz = (z1 * x2) - (x1 * z2);
  2304. var xy = (x1 * y2) - (y1 * x2);
  2305. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2306. var invPyth;
  2307. if (pyth !== 0) {
  2308. invPyth = 1.0 / pyth;
  2309. }
  2310. else {
  2311. invPyth = 0;
  2312. }
  2313. this.normal.x = yz * invPyth;
  2314. this.normal.y = xz * invPyth;
  2315. this.normal.z = xy * invPyth;
  2316. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2317. return this;
  2318. };
  2319. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2320. var dot = Vector3.Dot(this.normal, direction);
  2321. return (dot <= epsilon);
  2322. };
  2323. Plane.prototype.signedDistanceTo = function (point) {
  2324. return Vector3.Dot(point, this.normal) + this.d;
  2325. };
  2326. // Statics
  2327. Plane.FromArray = function (array) {
  2328. return new Plane(array[0], array[1], array[2], array[3]);
  2329. };
  2330. Plane.FromPoints = function (point1, point2, point3) {
  2331. var result = new Plane(0, 0, 0, 0);
  2332. result.copyFromPoints(point1, point2, point3);
  2333. return result;
  2334. };
  2335. Plane.FromPositionAndNormal = function (origin, normal) {
  2336. var result = new Plane(0, 0, 0, 0);
  2337. normal.normalize();
  2338. result.normal = normal;
  2339. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2340. return result;
  2341. };
  2342. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2343. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2344. return Vector3.Dot(point, normal) + d;
  2345. };
  2346. return Plane;
  2347. })();
  2348. BABYLON.Plane = Plane;
  2349. var Viewport = (function () {
  2350. function Viewport(x, y, width, height) {
  2351. this.x = x;
  2352. this.y = y;
  2353. this.width = width;
  2354. this.height = height;
  2355. }
  2356. Viewport.prototype.toGlobal = function (engine) {
  2357. var width = engine.getRenderWidth();
  2358. var height = engine.getRenderHeight();
  2359. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2360. };
  2361. return Viewport;
  2362. })();
  2363. BABYLON.Viewport = Viewport;
  2364. var Frustum = (function () {
  2365. function Frustum() {
  2366. }
  2367. Frustum.GetPlanes = function (transform) {
  2368. var frustumPlanes = [];
  2369. for (var index = 0; index < 6; index++) {
  2370. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2371. }
  2372. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2373. return frustumPlanes;
  2374. };
  2375. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2376. // Near
  2377. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2378. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2379. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2380. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2381. frustumPlanes[0].normalize();
  2382. // Far
  2383. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2384. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2385. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2386. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2387. frustumPlanes[1].normalize();
  2388. // Left
  2389. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2390. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2391. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2392. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2393. frustumPlanes[2].normalize();
  2394. // Right
  2395. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2396. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2397. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2398. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2399. frustumPlanes[3].normalize();
  2400. // Top
  2401. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2402. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2403. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2404. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2405. frustumPlanes[4].normalize();
  2406. // Bottom
  2407. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2408. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2409. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2410. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2411. frustumPlanes[5].normalize();
  2412. };
  2413. return Frustum;
  2414. })();
  2415. BABYLON.Frustum = Frustum;
  2416. var Ray = (function () {
  2417. function Ray(origin, direction, length) {
  2418. if (length === void 0) { length = Number.MAX_VALUE; }
  2419. this.origin = origin;
  2420. this.direction = direction;
  2421. this.length = length;
  2422. }
  2423. // Methods
  2424. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2425. var d = 0.0;
  2426. var maxValue = Number.MAX_VALUE;
  2427. var inv;
  2428. var min;
  2429. var max;
  2430. var temp;
  2431. if (Math.abs(this.direction.x) < 0.0000001) {
  2432. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2433. return false;
  2434. }
  2435. }
  2436. else {
  2437. inv = 1.0 / this.direction.x;
  2438. min = (minimum.x - this.origin.x) * inv;
  2439. max = (maximum.x - this.origin.x) * inv;
  2440. if (max === -Infinity) {
  2441. max = Infinity;
  2442. }
  2443. if (min > max) {
  2444. temp = min;
  2445. min = max;
  2446. max = temp;
  2447. }
  2448. d = Math.max(min, d);
  2449. maxValue = Math.min(max, maxValue);
  2450. if (d > maxValue) {
  2451. return false;
  2452. }
  2453. }
  2454. if (Math.abs(this.direction.y) < 0.0000001) {
  2455. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2456. return false;
  2457. }
  2458. }
  2459. else {
  2460. inv = 1.0 / this.direction.y;
  2461. min = (minimum.y - this.origin.y) * inv;
  2462. max = (maximum.y - this.origin.y) * inv;
  2463. if (max === -Infinity) {
  2464. max = Infinity;
  2465. }
  2466. if (min > max) {
  2467. temp = min;
  2468. min = max;
  2469. max = temp;
  2470. }
  2471. d = Math.max(min, d);
  2472. maxValue = Math.min(max, maxValue);
  2473. if (d > maxValue) {
  2474. return false;
  2475. }
  2476. }
  2477. if (Math.abs(this.direction.z) < 0.0000001) {
  2478. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2479. return false;
  2480. }
  2481. }
  2482. else {
  2483. inv = 1.0 / this.direction.z;
  2484. min = (minimum.z - this.origin.z) * inv;
  2485. max = (maximum.z - this.origin.z) * inv;
  2486. if (max === -Infinity) {
  2487. max = Infinity;
  2488. }
  2489. if (min > max) {
  2490. temp = min;
  2491. min = max;
  2492. max = temp;
  2493. }
  2494. d = Math.max(min, d);
  2495. maxValue = Math.min(max, maxValue);
  2496. if (d > maxValue) {
  2497. return false;
  2498. }
  2499. }
  2500. return true;
  2501. };
  2502. Ray.prototype.intersectsBox = function (box) {
  2503. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2504. };
  2505. Ray.prototype.intersectsSphere = function (sphere) {
  2506. var x = sphere.center.x - this.origin.x;
  2507. var y = sphere.center.y - this.origin.y;
  2508. var z = sphere.center.z - this.origin.z;
  2509. var pyth = (x * x) + (y * y) + (z * z);
  2510. var rr = sphere.radius * sphere.radius;
  2511. if (pyth <= rr) {
  2512. return true;
  2513. }
  2514. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2515. if (dot < 0.0) {
  2516. return false;
  2517. }
  2518. var temp = pyth - (dot * dot);
  2519. return temp <= rr;
  2520. };
  2521. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2522. if (!this._edge1) {
  2523. this._edge1 = Vector3.Zero();
  2524. this._edge2 = Vector3.Zero();
  2525. this._pvec = Vector3.Zero();
  2526. this._tvec = Vector3.Zero();
  2527. this._qvec = Vector3.Zero();
  2528. }
  2529. vertex1.subtractToRef(vertex0, this._edge1);
  2530. vertex2.subtractToRef(vertex0, this._edge2);
  2531. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2532. var det = Vector3.Dot(this._edge1, this._pvec);
  2533. if (det === 0) {
  2534. return null;
  2535. }
  2536. var invdet = 1 / det;
  2537. this.origin.subtractToRef(vertex0, this._tvec);
  2538. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2539. if (bu < 0 || bu > 1.0) {
  2540. return null;
  2541. }
  2542. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2543. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2544. if (bv < 0 || bu + bv > 1.0) {
  2545. return null;
  2546. }
  2547. //check if the distance is longer than the predefined length.
  2548. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2549. if (distance > this.length) {
  2550. return null;
  2551. }
  2552. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2553. };
  2554. // Statics
  2555. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2556. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2557. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2558. var direction = end.subtract(start);
  2559. direction.normalize();
  2560. return new Ray(start, direction);
  2561. };
  2562. /**
  2563. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2564. * transformed to the given world matrix.
  2565. * @param origin The origin point
  2566. * @param end The end point
  2567. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2568. */
  2569. Ray.CreateNewFromTo = function (origin, end, world) {
  2570. if (world === void 0) { world = Matrix.Identity(); }
  2571. var direction = end.subtract(origin);
  2572. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2573. direction.normalize();
  2574. return Ray.Transform(new Ray(origin, direction, length), world);
  2575. };
  2576. Ray.Transform = function (ray, matrix) {
  2577. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2578. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2579. return new Ray(newOrigin, newDirection, ray.length);
  2580. };
  2581. return Ray;
  2582. })();
  2583. BABYLON.Ray = Ray;
  2584. (function (Space) {
  2585. Space[Space["LOCAL"] = 0] = "LOCAL";
  2586. Space[Space["WORLD"] = 1] = "WORLD";
  2587. })(BABYLON.Space || (BABYLON.Space = {}));
  2588. var Space = BABYLON.Space;
  2589. var Axis = (function () {
  2590. function Axis() {
  2591. }
  2592. Axis.X = new Vector3(1, 0, 0);
  2593. Axis.Y = new Vector3(0, 1, 0);
  2594. Axis.Z = new Vector3(0, 0, 1);
  2595. return Axis;
  2596. })();
  2597. BABYLON.Axis = Axis;
  2598. ;
  2599. var BezierCurve = (function () {
  2600. function BezierCurve() {
  2601. }
  2602. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2603. // Extract X (which is equal to time here)
  2604. var f0 = 1 - 3 * x2 + 3 * x1;
  2605. var f1 = 3 * x2 - 6 * x1;
  2606. var f2 = 3 * x1;
  2607. var refinedT = t;
  2608. for (var i = 0; i < 5; i++) {
  2609. var refinedT2 = refinedT * refinedT;
  2610. var refinedT3 = refinedT2 * refinedT;
  2611. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2612. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2613. refinedT -= (x - t) * slope;
  2614. refinedT = Math.min(1, Math.max(0, refinedT));
  2615. }
  2616. // Resolve cubic bezier for the given x
  2617. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2618. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2619. Math.pow(refinedT, 3);
  2620. };
  2621. return BezierCurve;
  2622. })();
  2623. BABYLON.BezierCurve = BezierCurve;
  2624. (function (Orientation) {
  2625. Orientation[Orientation["CW"] = 0] = "CW";
  2626. Orientation[Orientation["CCW"] = 1] = "CCW";
  2627. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2628. var Orientation = BABYLON.Orientation;
  2629. var Angle = (function () {
  2630. function Angle(radians) {
  2631. var _this = this;
  2632. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2633. this.radians = function () { return _this._radians; };
  2634. this._radians = radians;
  2635. if (this._radians < 0)
  2636. this._radians += (2 * Math.PI);
  2637. }
  2638. Angle.BetweenTwoPoints = function (a, b) {
  2639. var delta = b.subtract(a);
  2640. var theta = Math.atan2(delta.y, delta.x);
  2641. return new Angle(theta);
  2642. };
  2643. Angle.FromRadians = function (radians) {
  2644. return new Angle(radians);
  2645. };
  2646. Angle.FromDegrees = function (degrees) {
  2647. return new Angle(degrees * Math.PI / 180);
  2648. };
  2649. return Angle;
  2650. })();
  2651. BABYLON.Angle = Angle;
  2652. var Arc2 = (function () {
  2653. function Arc2(startPoint, midPoint, endPoint) {
  2654. this.startPoint = startPoint;
  2655. this.midPoint = midPoint;
  2656. this.endPoint = endPoint;
  2657. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2658. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2659. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2660. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2661. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2662. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2663. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2664. var a1 = this.startAngle.degrees();
  2665. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2666. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2667. // angles correction
  2668. if (a2 - a1 > +180.0)
  2669. a2 -= 360.0;
  2670. if (a2 - a1 < -180.0)
  2671. a2 += 360.0;
  2672. if (a3 - a2 > +180.0)
  2673. a3 -= 360.0;
  2674. if (a3 - a2 < -180.0)
  2675. a3 += 360.0;
  2676. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2677. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2678. }
  2679. return Arc2;
  2680. })();
  2681. BABYLON.Arc2 = Arc2;
  2682. var PathCursor = (function () {
  2683. function PathCursor(path) {
  2684. this.path = path;
  2685. this._onchange = new Array();
  2686. this.value = 0;
  2687. this.animations = new Array();
  2688. }
  2689. PathCursor.prototype.getPoint = function () {
  2690. var point = this.path.getPointAtLengthPosition(this.value);
  2691. return new Vector3(point.x, 0, point.y);
  2692. };
  2693. PathCursor.prototype.moveAhead = function (step) {
  2694. if (step === void 0) { step = 0.002; }
  2695. this.move(step);
  2696. return this;
  2697. };
  2698. PathCursor.prototype.moveBack = function (step) {
  2699. if (step === void 0) { step = 0.002; }
  2700. this.move(-step);
  2701. return this;
  2702. };
  2703. PathCursor.prototype.move = function (step) {
  2704. if (Math.abs(step) > 1) {
  2705. throw "step size should be less than 1.";
  2706. }
  2707. this.value += step;
  2708. this.ensureLimits();
  2709. this.raiseOnChange();
  2710. return this;
  2711. };
  2712. PathCursor.prototype.ensureLimits = function () {
  2713. while (this.value > 1) {
  2714. this.value -= 1;
  2715. }
  2716. while (this.value < 0) {
  2717. this.value += 1;
  2718. }
  2719. return this;
  2720. };
  2721. // used by animation engine
  2722. PathCursor.prototype.markAsDirty = function (propertyName) {
  2723. this.ensureLimits();
  2724. this.raiseOnChange();
  2725. return this;
  2726. };
  2727. PathCursor.prototype.raiseOnChange = function () {
  2728. var _this = this;
  2729. this._onchange.forEach(function (f) { return f(_this); });
  2730. return this;
  2731. };
  2732. PathCursor.prototype.onchange = function (f) {
  2733. this._onchange.push(f);
  2734. return this;
  2735. };
  2736. return PathCursor;
  2737. })();
  2738. BABYLON.PathCursor = PathCursor;
  2739. var Path2 = (function () {
  2740. function Path2(x, y) {
  2741. this._points = new Array();
  2742. this._length = 0;
  2743. this.closed = false;
  2744. this._points.push(new Vector2(x, y));
  2745. }
  2746. Path2.prototype.addLineTo = function (x, y) {
  2747. if (closed) {
  2748. BABYLON.Tools.Error("cannot add lines to closed paths");
  2749. return this;
  2750. }
  2751. var newPoint = new Vector2(x, y);
  2752. var previousPoint = this._points[this._points.length - 1];
  2753. this._points.push(newPoint);
  2754. this._length += newPoint.subtract(previousPoint).length();
  2755. return this;
  2756. };
  2757. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2758. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2759. if (closed) {
  2760. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2761. return this;
  2762. }
  2763. var startPoint = this._points[this._points.length - 1];
  2764. var midPoint = new Vector2(midX, midY);
  2765. var endPoint = new Vector2(endX, endY);
  2766. var arc = new Arc2(startPoint, midPoint, endPoint);
  2767. var increment = arc.angle.radians() / numberOfSegments;
  2768. if (arc.orientation === Orientation.CW)
  2769. increment *= -1;
  2770. var currentAngle = arc.startAngle.radians() + increment;
  2771. for (var i = 0; i < numberOfSegments; i++) {
  2772. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2773. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2774. this.addLineTo(x, y);
  2775. currentAngle += increment;
  2776. }
  2777. return this;
  2778. };
  2779. Path2.prototype.close = function () {
  2780. this.closed = true;
  2781. return this;
  2782. };
  2783. Path2.prototype.length = function () {
  2784. var result = this._length;
  2785. if (!this.closed) {
  2786. var lastPoint = this._points[this._points.length - 1];
  2787. var firstPoint = this._points[0];
  2788. result += (firstPoint.subtract(lastPoint).length());
  2789. }
  2790. return result;
  2791. };
  2792. Path2.prototype.getPoints = function () {
  2793. return this._points;
  2794. };
  2795. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2796. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2797. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2798. return Vector2.Zero();
  2799. }
  2800. var lengthPosition = normalizedLengthPosition * this.length();
  2801. var previousOffset = 0;
  2802. for (var i = 0; i < this._points.length; i++) {
  2803. var j = (i + 1) % this._points.length;
  2804. var a = this._points[i];
  2805. var b = this._points[j];
  2806. var bToA = b.subtract(a);
  2807. var nextOffset = (bToA.length() + previousOffset);
  2808. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2809. var dir = bToA.normalize();
  2810. var localOffset = lengthPosition - previousOffset;
  2811. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2812. }
  2813. previousOffset = nextOffset;
  2814. }
  2815. BABYLON.Tools.Error("internal error");
  2816. return Vector2.Zero();
  2817. };
  2818. Path2.StartingAt = function (x, y) {
  2819. return new Path2(x, y);
  2820. };
  2821. return Path2;
  2822. })();
  2823. BABYLON.Path2 = Path2;
  2824. var Path3D = (function () {
  2825. function Path3D(path, firstNormal) {
  2826. this.path = path;
  2827. this._curve = new Array();
  2828. this._distances = new Array();
  2829. this._tangents = new Array();
  2830. this._normals = new Array();
  2831. this._binormals = new Array();
  2832. for (var p = 0; p < path.length; p++) {
  2833. this._curve[p] = path[p].clone(); // hard copy
  2834. }
  2835. this._compute(firstNormal);
  2836. }
  2837. Path3D.prototype.getCurve = function () {
  2838. return this._curve;
  2839. };
  2840. Path3D.prototype.getTangents = function () {
  2841. return this._tangents;
  2842. };
  2843. Path3D.prototype.getNormals = function () {
  2844. return this._normals;
  2845. };
  2846. Path3D.prototype.getBinormals = function () {
  2847. return this._binormals;
  2848. };
  2849. Path3D.prototype.getDistances = function () {
  2850. return this._distances;
  2851. };
  2852. Path3D.prototype.update = function (path, firstNormal) {
  2853. for (var p = 0; p < path.length; p++) {
  2854. this._curve[p].x = path[p].x;
  2855. this._curve[p].y = path[p].y;
  2856. this._curve[p].z = path[p].z;
  2857. }
  2858. this._compute(firstNormal);
  2859. return this;
  2860. };
  2861. // private function compute() : computes tangents, normals and binormals
  2862. Path3D.prototype._compute = function (firstNormal) {
  2863. var l = this._curve.length;
  2864. // first and last tangents
  2865. this._tangents[0] = this._getFirstNonNullVector(0);
  2866. this._tangents[0].normalize();
  2867. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2868. this._tangents[l - 1].normalize();
  2869. // normals and binormals at first point : arbitrary vector with _normalVector()
  2870. var tg0 = this._tangents[0];
  2871. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2872. this._normals[0] = pp0;
  2873. this._normals[0].normalize();
  2874. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2875. this._binormals[0].normalize();
  2876. this._distances[0] = 0;
  2877. // normals and binormals : next points
  2878. var prev; // previous vector (segment)
  2879. var cur; // current vector (segment)
  2880. var curTang; // current tangent
  2881. // previous normal
  2882. var prevBinor; // previous binormal
  2883. for (var i = 1; i < l; i++) {
  2884. // tangents
  2885. prev = this._getLastNonNullVector(i);
  2886. if (i < l - 1) {
  2887. cur = this._getFirstNonNullVector(i);
  2888. this._tangents[i] = prev.add(cur);
  2889. this._tangents[i].normalize();
  2890. }
  2891. this._distances[i] = this._distances[i - 1] + prev.length();
  2892. // normals and binormals
  2893. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2894. curTang = this._tangents[i];
  2895. prevBinor = this._binormals[i - 1];
  2896. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2897. this._normals[i].normalize();
  2898. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2899. this._binormals[i].normalize();
  2900. }
  2901. };
  2902. // private function getFirstNonNullVector(index)
  2903. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2904. Path3D.prototype._getFirstNonNullVector = function (index) {
  2905. var i = 1;
  2906. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2907. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2908. i++;
  2909. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2910. }
  2911. return nNVector;
  2912. };
  2913. // private function getLastNonNullVector(index)
  2914. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2915. Path3D.prototype._getLastNonNullVector = function (index) {
  2916. var i = 1;
  2917. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2918. while (nLVector.length() === 0 && index > i + 1) {
  2919. i++;
  2920. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2921. }
  2922. return nLVector;
  2923. };
  2924. // private function normalVector(v0, vt, va) :
  2925. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2926. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2927. Path3D.prototype._normalVector = function (v0, vt, va) {
  2928. var normal0;
  2929. if (va === undefined || va === null) {
  2930. var point;
  2931. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2932. point = new Vector3(0, -1, 0);
  2933. }
  2934. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2935. point = new Vector3(1, 0, 0);
  2936. }
  2937. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2938. point = new Vector3(0, 0, 1);
  2939. }
  2940. normal0 = Vector3.Cross(vt, point);
  2941. }
  2942. else {
  2943. normal0 = Vector3.Cross(vt, va);
  2944. Vector3.CrossToRef(normal0, vt, normal0);
  2945. }
  2946. normal0.normalize();
  2947. return normal0;
  2948. };
  2949. return Path3D;
  2950. })();
  2951. BABYLON.Path3D = Path3D;
  2952. var Curve3 = (function () {
  2953. function Curve3(points) {
  2954. this._length = 0;
  2955. this._points = points;
  2956. this._length = this._computeLength(points);
  2957. }
  2958. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2959. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2960. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2961. var bez = new Array();
  2962. var equation = function (t, val0, val1, val2) {
  2963. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2964. return res;
  2965. };
  2966. for (var i = 0; i <= nbPoints; i++) {
  2967. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2968. }
  2969. return new Curve3(bez);
  2970. };
  2971. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2972. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2973. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2974. var bez = new Array();
  2975. var equation = function (t, val0, val1, val2, val3) {
  2976. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2977. return res;
  2978. };
  2979. for (var i = 0; i <= nbPoints; i++) {
  2980. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2981. }
  2982. return new Curve3(bez);
  2983. };
  2984. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2985. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2986. var hermite = new Array();
  2987. var step = 1 / nbPoints;
  2988. for (var i = 0; i <= nbPoints; i++) {
  2989. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2990. }
  2991. return new Curve3(hermite);
  2992. };
  2993. Curve3.prototype.getPoints = function () {
  2994. return this._points;
  2995. };
  2996. Curve3.prototype.length = function () {
  2997. return this._length;
  2998. };
  2999. Curve3.prototype.continue = function (curve) {
  3000. var lastPoint = this._points[this._points.length - 1];
  3001. var continuedPoints = this._points.slice();
  3002. var curvePoints = curve.getPoints();
  3003. for (var i = 1; i < curvePoints.length; i++) {
  3004. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3005. }
  3006. var continuedCurve = new Curve3(continuedPoints);
  3007. return continuedCurve;
  3008. };
  3009. Curve3.prototype._computeLength = function (path) {
  3010. var l = 0;
  3011. for (var i = 1; i < path.length; i++) {
  3012. l += (path[i].subtract(path[i - 1])).length();
  3013. }
  3014. return l;
  3015. };
  3016. return Curve3;
  3017. })();
  3018. BABYLON.Curve3 = Curve3;
  3019. // Vertex formats
  3020. var PositionNormalVertex = (function () {
  3021. function PositionNormalVertex(position, normal) {
  3022. if (position === void 0) { position = Vector3.Zero(); }
  3023. if (normal === void 0) { normal = Vector3.Up(); }
  3024. this.position = position;
  3025. this.normal = normal;
  3026. }
  3027. PositionNormalVertex.prototype.clone = function () {
  3028. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3029. };
  3030. return PositionNormalVertex;
  3031. })();
  3032. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3033. var PositionNormalTextureVertex = (function () {
  3034. function PositionNormalTextureVertex(position, normal, uv) {
  3035. if (position === void 0) { position = Vector3.Zero(); }
  3036. if (normal === void 0) { normal = Vector3.Up(); }
  3037. if (uv === void 0) { uv = Vector2.Zero(); }
  3038. this.position = position;
  3039. this.normal = normal;
  3040. this.uv = uv;
  3041. }
  3042. PositionNormalTextureVertex.prototype.clone = function () {
  3043. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3044. };
  3045. return PositionNormalTextureVertex;
  3046. })();
  3047. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3048. // SIMD
  3049. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3050. var previousInvertToRef = Matrix.prototype.invertToRef;
  3051. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3052. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3053. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3054. var SIMDHelper = (function () {
  3055. function SIMDHelper() {
  3056. }
  3057. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3058. get: function () {
  3059. return SIMDHelper._isEnabled;
  3060. },
  3061. enumerable: true,
  3062. configurable: true
  3063. });
  3064. SIMDHelper.DisableSIMD = function () {
  3065. // Replace functions
  3066. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3067. Matrix.prototype.invertToRef = previousInvertToRef;
  3068. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3069. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3070. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3071. SIMDHelper._isEnabled = false;
  3072. };
  3073. SIMDHelper.EnableSIMD = function () {
  3074. if (window.SIMD === undefined) {
  3075. return;
  3076. }
  3077. // Replace functions
  3078. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3079. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3080. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3081. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3082. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3083. Object.defineProperty(Vector3.prototype, "x", {
  3084. get: function () { return this._data[0]; },
  3085. set: function (value) {
  3086. if (!this._data) {
  3087. this._data = new Float32Array(3);
  3088. }
  3089. this._data[0] = value;
  3090. }
  3091. });
  3092. Object.defineProperty(Vector3.prototype, "y", {
  3093. get: function () { return this._data[1]; },
  3094. set: function (value) {
  3095. this._data[1] = value;
  3096. }
  3097. });
  3098. Object.defineProperty(Vector3.prototype, "z", {
  3099. get: function () { return this._data[2]; },
  3100. set: function (value) {
  3101. this._data[2] = value;
  3102. }
  3103. });
  3104. SIMDHelper._isEnabled = true;
  3105. };
  3106. SIMDHelper._isEnabled = false;
  3107. return SIMDHelper;
  3108. })();
  3109. BABYLON.SIMDHelper = SIMDHelper;
  3110. })(BABYLON || (BABYLON = {}));
  3111. var BABYLON;
  3112. (function (BABYLON) {
  3113. var Database = (function () {
  3114. function Database(urlToScene, callbackManifestChecked) {
  3115. // Handling various flavors of prefixed version of IndexedDB
  3116. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3117. this.callbackManifestChecked = callbackManifestChecked;
  3118. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3119. this.db = null;
  3120. this.enableSceneOffline = false;
  3121. this.enableTexturesOffline = false;
  3122. this.manifestVersionFound = 0;
  3123. this.mustUpdateRessources = false;
  3124. this.hasReachedQuota = false;
  3125. if (!Database.IDBStorageEnabled) {
  3126. this.callbackManifestChecked(true);
  3127. }
  3128. else {
  3129. this.checkManifestFile();
  3130. }
  3131. }
  3132. Database.prototype.checkManifestFile = function () {
  3133. var _this = this;
  3134. function noManifestFile() {
  3135. that.enableSceneOffline = false;
  3136. that.enableTexturesOffline = false;
  3137. that.callbackManifestChecked(false);
  3138. }
  3139. var that = this;
  3140. var manifestURL = this.currentSceneUrl + ".manifest";
  3141. var xhr = new XMLHttpRequest();
  3142. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3143. xhr.open("GET", manifestURLTimeStamped, true);
  3144. xhr.addEventListener("load", function () {
  3145. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3146. try {
  3147. var manifestFile = JSON.parse(xhr.response);
  3148. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3149. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3150. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3151. _this.manifestVersionFound = manifestFile.version;
  3152. }
  3153. if (_this.callbackManifestChecked) {
  3154. _this.callbackManifestChecked(true);
  3155. }
  3156. }
  3157. catch (ex) {
  3158. noManifestFile();
  3159. }
  3160. }
  3161. else {
  3162. noManifestFile();
  3163. }
  3164. }, false);
  3165. xhr.addEventListener("error", function (event) {
  3166. noManifestFile();
  3167. }, false);
  3168. try {
  3169. xhr.send();
  3170. }
  3171. catch (ex) {
  3172. BABYLON.Tools.Error("Error on XHR send request.");
  3173. that.callbackManifestChecked(false);
  3174. }
  3175. };
  3176. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3177. var _this = this;
  3178. function handleError() {
  3179. that.isSupported = false;
  3180. if (errorCallback)
  3181. errorCallback();
  3182. }
  3183. var that = this;
  3184. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3185. // Your browser doesn't support IndexedDB
  3186. this.isSupported = false;
  3187. if (errorCallback)
  3188. errorCallback();
  3189. }
  3190. else {
  3191. // If the DB hasn't been opened or created yet
  3192. if (!this.db) {
  3193. this.hasReachedQuota = false;
  3194. this.isSupported = true;
  3195. var request = this.idbFactory.open("babylonjs", 1);
  3196. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3197. request.onerror = function (event) {
  3198. handleError();
  3199. };
  3200. // executes when a version change transaction cannot complete due to other active transactions
  3201. request.onblocked = function (event) {
  3202. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3203. handleError();
  3204. };
  3205. // DB has been opened successfully
  3206. request.onsuccess = function (event) {
  3207. _this.db = request.result;
  3208. successCallback();
  3209. };
  3210. // Initialization of the DB. Creating Scenes & Textures stores
  3211. request.onupgradeneeded = function (event) {
  3212. _this.db = (event.target).result;
  3213. try {
  3214. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3215. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3216. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3217. }
  3218. catch (ex) {
  3219. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3220. handleError();
  3221. }
  3222. };
  3223. }
  3224. else {
  3225. if (successCallback)
  3226. successCallback();
  3227. }
  3228. }
  3229. };
  3230. Database.prototype.loadImageFromDB = function (url, image) {
  3231. var _this = this;
  3232. var completeURL = Database.ReturnFullUrlLocation(url);
  3233. var saveAndLoadImage = function () {
  3234. if (!_this.hasReachedQuota && _this.db !== null) {
  3235. // the texture is not yet in the DB, let's try to save it
  3236. _this._saveImageIntoDBAsync(completeURL, image);
  3237. }
  3238. else {
  3239. image.src = url;
  3240. }
  3241. };
  3242. if (!this.mustUpdateRessources) {
  3243. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3244. }
  3245. else {
  3246. saveAndLoadImage();
  3247. }
  3248. };
  3249. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3250. if (this.isSupported && this.db !== null) {
  3251. var texture;
  3252. var transaction = this.db.transaction(["textures"]);
  3253. transaction.onabort = function (event) {
  3254. image.src = url;
  3255. };
  3256. transaction.oncomplete = function (event) {
  3257. var blobTextureURL;
  3258. if (texture) {
  3259. var URL = window.URL || window.webkitURL;
  3260. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3261. image.onerror = function () {
  3262. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3263. image.src = url;
  3264. };
  3265. image.src = blobTextureURL;
  3266. }
  3267. else {
  3268. notInDBCallback();
  3269. }
  3270. };
  3271. var getRequest = transaction.objectStore("textures").get(url);
  3272. getRequest.onsuccess = function (event) {
  3273. texture = (event.target).result;
  3274. };
  3275. getRequest.onerror = function (event) {
  3276. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3277. image.src = url;
  3278. };
  3279. }
  3280. else {
  3281. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3282. image.src = url;
  3283. }
  3284. };
  3285. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3286. var _this = this;
  3287. if (this.isSupported) {
  3288. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3289. var generateBlobUrl = function () {
  3290. var blobTextureURL;
  3291. if (blob) {
  3292. var URL = window.URL || window.webkitURL;
  3293. try {
  3294. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3295. }
  3296. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3297. catch (ex) {
  3298. blobTextureURL = URL.createObjectURL(blob);
  3299. }
  3300. }
  3301. image.src = blobTextureURL;
  3302. };
  3303. if (Database.IsUASupportingBlobStorage) {
  3304. var xhr = new XMLHttpRequest(), blob;
  3305. xhr.open("GET", url, true);
  3306. xhr.responseType = "blob";
  3307. xhr.addEventListener("load", function () {
  3308. if (xhr.status === 200) {
  3309. // Blob as response (XHR2)
  3310. blob = xhr.response;
  3311. var transaction = _this.db.transaction(["textures"], "readwrite");
  3312. // the transaction could abort because of a QuotaExceededError error
  3313. transaction.onabort = function (event) {
  3314. try {
  3315. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3316. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3317. this.hasReachedQuota = true;
  3318. }
  3319. }
  3320. catch (ex) { }
  3321. generateBlobUrl();
  3322. };
  3323. transaction.oncomplete = function (event) {
  3324. generateBlobUrl();
  3325. };
  3326. var newTexture = { textureUrl: url, data: blob };
  3327. try {
  3328. // Put the blob into the dabase
  3329. var addRequest = transaction.objectStore("textures").put(newTexture);
  3330. addRequest.onsuccess = function (event) {
  3331. };
  3332. addRequest.onerror = function (event) {
  3333. generateBlobUrl();
  3334. };
  3335. }
  3336. catch (ex) {
  3337. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3338. if (ex.code === 25) {
  3339. Database.IsUASupportingBlobStorage = false;
  3340. }
  3341. image.src = url;
  3342. }
  3343. }
  3344. else {
  3345. image.src = url;
  3346. }
  3347. }, false);
  3348. xhr.addEventListener("error", function (event) {
  3349. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3350. image.src = url;
  3351. }, false);
  3352. xhr.send();
  3353. }
  3354. else {
  3355. image.src = url;
  3356. }
  3357. }
  3358. else {
  3359. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3360. image.src = url;
  3361. }
  3362. };
  3363. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3364. var _this = this;
  3365. var updateVersion = function (event) {
  3366. // the version is not yet in the DB or we need to update it
  3367. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3368. };
  3369. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3370. };
  3371. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3372. var _this = this;
  3373. if (this.isSupported) {
  3374. var version;
  3375. try {
  3376. var transaction = this.db.transaction(["versions"]);
  3377. transaction.oncomplete = function (event) {
  3378. if (version) {
  3379. // If the version in the JSON file is > than the version in DB
  3380. if (_this.manifestVersionFound > version.data) {
  3381. _this.mustUpdateRessources = true;
  3382. updateInDBCallback();
  3383. }
  3384. else {
  3385. callback(version.data);
  3386. }
  3387. }
  3388. else {
  3389. _this.mustUpdateRessources = true;
  3390. updateInDBCallback();
  3391. }
  3392. };
  3393. transaction.onabort = function (event) {
  3394. callback(-1);
  3395. };
  3396. var getRequest = transaction.objectStore("versions").get(url);
  3397. getRequest.onsuccess = function (event) {
  3398. version = (event.target).result;
  3399. };
  3400. getRequest.onerror = function (event) {
  3401. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3402. callback(-1);
  3403. };
  3404. }
  3405. catch (ex) {
  3406. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3407. callback(-1);
  3408. }
  3409. }
  3410. else {
  3411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3412. callback(-1);
  3413. }
  3414. };
  3415. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3416. var _this = this;
  3417. if (this.isSupported && !this.hasReachedQuota) {
  3418. try {
  3419. // Open a transaction to the database
  3420. var transaction = this.db.transaction(["versions"], "readwrite");
  3421. // the transaction could abort because of a QuotaExceededError error
  3422. transaction.onabort = function (event) {
  3423. try {
  3424. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3425. _this.hasReachedQuota = true;
  3426. }
  3427. }
  3428. catch (ex) { }
  3429. callback(-1);
  3430. };
  3431. transaction.oncomplete = function (event) {
  3432. callback(_this.manifestVersionFound);
  3433. };
  3434. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3435. // Put the scene into the database
  3436. var addRequest = transaction.objectStore("versions").put(newVersion);
  3437. addRequest.onsuccess = function (event) {
  3438. };
  3439. addRequest.onerror = function (event) {
  3440. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3441. };
  3442. }
  3443. catch (ex) {
  3444. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3445. callback(-1);
  3446. }
  3447. }
  3448. else {
  3449. callback(-1);
  3450. }
  3451. };
  3452. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3453. var _this = this;
  3454. var completeUrl = Database.ReturnFullUrlLocation(url);
  3455. var saveAndLoadFile = function (event) {
  3456. // the scene is not yet in the DB, let's try to save it
  3457. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3458. };
  3459. this._checkVersionFromDB(completeUrl, function (version) {
  3460. if (version !== -1) {
  3461. if (!_this.mustUpdateRessources) {
  3462. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3463. }
  3464. else {
  3465. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3466. }
  3467. }
  3468. else {
  3469. errorCallback();
  3470. }
  3471. });
  3472. };
  3473. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3474. if (this.isSupported) {
  3475. var targetStore;
  3476. if (url.indexOf(".babylon") !== -1) {
  3477. targetStore = "scenes";
  3478. }
  3479. else {
  3480. targetStore = "textures";
  3481. }
  3482. var file;
  3483. var transaction = this.db.transaction([targetStore]);
  3484. transaction.oncomplete = function (event) {
  3485. if (file) {
  3486. callback(file.data);
  3487. }
  3488. else {
  3489. notInDBCallback();
  3490. }
  3491. };
  3492. transaction.onabort = function (event) {
  3493. notInDBCallback();
  3494. };
  3495. var getRequest = transaction.objectStore(targetStore).get(url);
  3496. getRequest.onsuccess = function (event) {
  3497. file = (event.target).result;
  3498. };
  3499. getRequest.onerror = function (event) {
  3500. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3501. notInDBCallback();
  3502. };
  3503. }
  3504. else {
  3505. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3506. callback();
  3507. }
  3508. };
  3509. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3510. var _this = this;
  3511. if (this.isSupported) {
  3512. var targetStore;
  3513. if (url.indexOf(".babylon") !== -1) {
  3514. targetStore = "scenes";
  3515. }
  3516. else {
  3517. targetStore = "textures";
  3518. }
  3519. // Create XHR
  3520. var xhr = new XMLHttpRequest(), fileData;
  3521. xhr.open("GET", url, true);
  3522. if (useArrayBuffer) {
  3523. xhr.responseType = "arraybuffer";
  3524. }
  3525. xhr.onprogress = progressCallback;
  3526. xhr.addEventListener("load", function () {
  3527. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3528. // Blob as response (XHR2)
  3529. //fileData = xhr.responseText;
  3530. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3531. if (!_this.hasReachedQuota) {
  3532. // Open a transaction to the database
  3533. var transaction = _this.db.transaction([targetStore], "readwrite");
  3534. // the transaction could abort because of a QuotaExceededError error
  3535. transaction.onabort = function (event) {
  3536. try {
  3537. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3538. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3539. this.hasReachedQuota = true;
  3540. }
  3541. }
  3542. catch (ex) { }
  3543. callback(fileData);
  3544. };
  3545. transaction.oncomplete = function (event) {
  3546. callback(fileData);
  3547. };
  3548. var newFile;
  3549. if (targetStore === "scenes") {
  3550. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3551. }
  3552. else {
  3553. newFile = { textureUrl: url, data: fileData };
  3554. }
  3555. try {
  3556. // Put the scene into the database
  3557. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3558. addRequest.onsuccess = function (event) {
  3559. };
  3560. addRequest.onerror = function (event) {
  3561. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3562. };
  3563. }
  3564. catch (ex) {
  3565. callback(fileData);
  3566. }
  3567. }
  3568. else {
  3569. callback(fileData);
  3570. }
  3571. }
  3572. else {
  3573. callback();
  3574. }
  3575. }, false);
  3576. xhr.addEventListener("error", function (event) {
  3577. BABYLON.Tools.Error("error on XHR request.");
  3578. callback();
  3579. }, false);
  3580. xhr.send();
  3581. }
  3582. else {
  3583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3584. callback();
  3585. }
  3586. };
  3587. Database.IsUASupportingBlobStorage = true;
  3588. Database.IDBStorageEnabled = true;
  3589. Database.parseURL = function (url) {
  3590. var a = document.createElement('a');
  3591. a.href = url;
  3592. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3593. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3594. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3595. return absLocation;
  3596. };
  3597. Database.ReturnFullUrlLocation = function (url) {
  3598. if (url.indexOf("http:/") === -1) {
  3599. return (Database.parseURL(window.location.href) + url);
  3600. }
  3601. else {
  3602. return url;
  3603. }
  3604. };
  3605. return Database;
  3606. })();
  3607. BABYLON.Database = Database;
  3608. })(BABYLON || (BABYLON = {}));
  3609. var BABYLON;
  3610. (function (BABYLON) {
  3611. var Internals;
  3612. (function (Internals) {
  3613. /*
  3614. * Based on jsTGALoader - Javascript loader for TGA file
  3615. * By Vincent Thibault
  3616. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3617. */
  3618. var TGATools = (function () {
  3619. function TGATools() {
  3620. }
  3621. TGATools.GetTGAHeader = function (data) {
  3622. var offset = 0;
  3623. var header = {
  3624. id_length: data[offset++],
  3625. colormap_type: data[offset++],
  3626. image_type: data[offset++],
  3627. colormap_index: data[offset++] | data[offset++] << 8,
  3628. colormap_length: data[offset++] | data[offset++] << 8,
  3629. colormap_size: data[offset++],
  3630. origin: [
  3631. data[offset++] | data[offset++] << 8,
  3632. data[offset++] | data[offset++] << 8
  3633. ],
  3634. width: data[offset++] | data[offset++] << 8,
  3635. height: data[offset++] | data[offset++] << 8,
  3636. pixel_size: data[offset++],
  3637. flags: data[offset++]
  3638. };
  3639. return header;
  3640. };
  3641. TGATools.UploadContent = function (gl, data) {
  3642. // Not enough data to contain header ?
  3643. if (data.length < 19) {
  3644. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3645. return;
  3646. }
  3647. // Read Header
  3648. var offset = 18;
  3649. var header = TGATools.GetTGAHeader(data);
  3650. // Assume it's a valid Targa file.
  3651. if (header.id_length + offset > data.length) {
  3652. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3653. return;
  3654. }
  3655. // Skip not needed data
  3656. offset += header.id_length;
  3657. var use_rle = false;
  3658. var use_pal = false;
  3659. var use_rgb = false;
  3660. var use_grey = false;
  3661. // Get some informations.
  3662. switch (header.image_type) {
  3663. case TGATools._TYPE_RLE_INDEXED:
  3664. use_rle = true;
  3665. case TGATools._TYPE_INDEXED:
  3666. use_pal = true;
  3667. break;
  3668. case TGATools._TYPE_RLE_RGB:
  3669. use_rle = true;
  3670. case TGATools._TYPE_RGB:
  3671. use_rgb = true;
  3672. break;
  3673. case TGATools._TYPE_RLE_GREY:
  3674. use_rle = true;
  3675. case TGATools._TYPE_GREY:
  3676. use_grey = true;
  3677. break;
  3678. }
  3679. var pixel_data;
  3680. var numAlphaBits = header.flags & 0xf;
  3681. var pixel_size = header.pixel_size >> 3;
  3682. var pixel_total = header.width * header.height * pixel_size;
  3683. // Read palettes
  3684. var palettes;
  3685. if (use_pal) {
  3686. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3687. }
  3688. // Read LRE
  3689. if (use_rle) {
  3690. pixel_data = new Uint8Array(pixel_total);
  3691. var c, count, i;
  3692. var localOffset = 0;
  3693. var pixels = new Uint8Array(pixel_size);
  3694. while (offset < pixel_total && localOffset < pixel_total) {
  3695. c = data[offset++];
  3696. count = (c & 0x7f) + 1;
  3697. // RLE pixels
  3698. if (c & 0x80) {
  3699. // Bind pixel tmp array
  3700. for (i = 0; i < pixel_size; ++i) {
  3701. pixels[i] = data[offset++];
  3702. }
  3703. // Copy pixel array
  3704. for (i = 0; i < count; ++i) {
  3705. pixel_data.set(pixels, localOffset + i * pixel_size);
  3706. }
  3707. localOffset += pixel_size * count;
  3708. }
  3709. else {
  3710. count *= pixel_size;
  3711. for (i = 0; i < count; ++i) {
  3712. pixel_data[localOffset + i] = data[offset++];
  3713. }
  3714. localOffset += count;
  3715. }
  3716. }
  3717. }
  3718. else {
  3719. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3720. }
  3721. // Load to texture
  3722. var x_start, y_start, x_step, y_step, y_end, x_end;
  3723. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3724. default:
  3725. case TGATools._ORIGIN_UL:
  3726. x_start = 0;
  3727. x_step = 1;
  3728. x_end = header.width;
  3729. y_start = 0;
  3730. y_step = 1;
  3731. y_end = header.height;
  3732. break;
  3733. case TGATools._ORIGIN_BL:
  3734. x_start = 0;
  3735. x_step = 1;
  3736. x_end = header.width;
  3737. y_start = header.height - 1;
  3738. y_step = -1;
  3739. y_end = -1;
  3740. break;
  3741. case TGATools._ORIGIN_UR:
  3742. x_start = header.width - 1;
  3743. x_step = -1;
  3744. x_end = -1;
  3745. y_start = 0;
  3746. y_step = 1;
  3747. y_end = header.height;
  3748. break;
  3749. case TGATools._ORIGIN_BR:
  3750. x_start = header.width - 1;
  3751. x_step = -1;
  3752. x_end = -1;
  3753. y_start = header.height - 1;
  3754. y_step = -1;
  3755. y_end = -1;
  3756. break;
  3757. }
  3758. // Load the specify method
  3759. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3760. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3761. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3762. };
  3763. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3764. var image = pixel_data, colormap = palettes;
  3765. var width = header.width, height = header.height;
  3766. var color, i = 0, x, y;
  3767. var imageData = new Uint8Array(width * height * 4);
  3768. for (y = y_start; y !== y_end; y += y_step) {
  3769. for (x = x_start; x !== x_end; x += x_step, i++) {
  3770. color = image[i];
  3771. imageData[(x + width * y) * 4 + 3] = 255;
  3772. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3773. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3774. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3775. }
  3776. }
  3777. return imageData;
  3778. };
  3779. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3780. var image = pixel_data;
  3781. var width = header.width, height = header.height;
  3782. var color, i = 0, x, y;
  3783. var imageData = new Uint8Array(width * height * 4);
  3784. for (y = y_start; y !== y_end; y += y_step) {
  3785. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3786. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3787. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3788. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3789. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3790. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3791. }
  3792. }
  3793. return imageData;
  3794. };
  3795. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3796. var image = pixel_data;
  3797. var width = header.width, height = header.height;
  3798. var i = 0, x, y;
  3799. var imageData = new Uint8Array(width * height * 4);
  3800. for (y = y_start; y !== y_end; y += y_step) {
  3801. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3802. imageData[(x + width * y) * 4 + 3] = 255;
  3803. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3804. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3805. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3806. }
  3807. }
  3808. return imageData;
  3809. };
  3810. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3811. var image = pixel_data;
  3812. var width = header.width, height = header.height;
  3813. var i = 0, x, y;
  3814. var imageData = new Uint8Array(width * height * 4);
  3815. for (y = y_start; y !== y_end; y += y_step) {
  3816. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3817. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3818. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3819. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3820. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3821. }
  3822. }
  3823. return imageData;
  3824. };
  3825. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3826. var image = pixel_data;
  3827. var width = header.width, height = header.height;
  3828. var color, i = 0, x, y;
  3829. var imageData = new Uint8Array(width * height * 4);
  3830. for (y = y_start; y !== y_end; y += y_step) {
  3831. for (x = x_start; x !== x_end; x += x_step, i++) {
  3832. color = image[i];
  3833. imageData[(x + width * y) * 4 + 0] = color;
  3834. imageData[(x + width * y) * 4 + 1] = color;
  3835. imageData[(x + width * y) * 4 + 2] = color;
  3836. imageData[(x + width * y) * 4 + 3] = 255;
  3837. }
  3838. }
  3839. return imageData;
  3840. };
  3841. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3842. var image = pixel_data;
  3843. var width = header.width, height = header.height;
  3844. var i = 0, x, y;
  3845. var imageData = new Uint8Array(width * height * 4);
  3846. for (y = y_start; y !== y_end; y += y_step) {
  3847. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3848. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3849. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3850. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3851. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3852. }
  3853. }
  3854. return imageData;
  3855. };
  3856. TGATools._TYPE_NO_DATA = 0;
  3857. TGATools._TYPE_INDEXED = 1;
  3858. TGATools._TYPE_RGB = 2;
  3859. TGATools._TYPE_GREY = 3;
  3860. TGATools._TYPE_RLE_INDEXED = 9;
  3861. TGATools._TYPE_RLE_RGB = 10;
  3862. TGATools._TYPE_RLE_GREY = 11;
  3863. TGATools._ORIGIN_MASK = 0x30;
  3864. TGATools._ORIGIN_SHIFT = 0x04;
  3865. TGATools._ORIGIN_BL = 0x00;
  3866. TGATools._ORIGIN_BR = 0x01;
  3867. TGATools._ORIGIN_UL = 0x02;
  3868. TGATools._ORIGIN_UR = 0x03;
  3869. return TGATools;
  3870. })();
  3871. Internals.TGATools = TGATools;
  3872. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3873. })(BABYLON || (BABYLON = {}));
  3874. var BABYLON;
  3875. (function (BABYLON) {
  3876. var Internals;
  3877. (function (Internals) {
  3878. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3879. // All values and structures referenced from:
  3880. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3881. var DDS_MAGIC = 0x20534444;
  3882. 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;
  3883. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3884. 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;
  3885. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3886. function FourCCToInt32(value) {
  3887. return value.charCodeAt(0) +
  3888. (value.charCodeAt(1) << 8) +
  3889. (value.charCodeAt(2) << 16) +
  3890. (value.charCodeAt(3) << 24);
  3891. }
  3892. function Int32ToFourCC(value) {
  3893. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3894. }
  3895. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3896. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3897. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3898. var headerLengthInt = 31; // The header length in 32 bit ints
  3899. // Offsets into the header array
  3900. var off_magic = 0;
  3901. var off_size = 1;
  3902. var off_flags = 2;
  3903. var off_height = 3;
  3904. var off_width = 4;
  3905. var off_mipmapCount = 7;
  3906. var off_pfFlags = 20;
  3907. var off_pfFourCC = 21;
  3908. var off_RGBbpp = 22;
  3909. var off_RMask = 23;
  3910. var off_GMask = 24;
  3911. var off_BMask = 25;
  3912. var off_AMask = 26;
  3913. var off_caps1 = 27;
  3914. var off_caps2 = 28;
  3915. ;
  3916. var DDSTools = (function () {
  3917. function DDSTools() {
  3918. }
  3919. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3920. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3921. var mipmapCount = 1;
  3922. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3923. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3924. }
  3925. return {
  3926. width: header[off_width],
  3927. height: header[off_height],
  3928. mipmapCount: mipmapCount,
  3929. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3930. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3931. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3932. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3933. };
  3934. };
  3935. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3936. var byteArray = new Uint8Array(dataLength);
  3937. var srcData = new Uint8Array(arrayBuffer);
  3938. var index = 0;
  3939. for (var y = height - 1; y >= 0; y--) {
  3940. for (var x = 0; x < width; x++) {
  3941. var srcPos = dataOffset + (x + y * width) * 4;
  3942. byteArray[index + 2] = srcData[srcPos];
  3943. byteArray[index + 1] = srcData[srcPos + 1];
  3944. byteArray[index] = srcData[srcPos + 2];
  3945. byteArray[index + 3] = srcData[srcPos + 3];
  3946. index += 4;
  3947. }
  3948. }
  3949. return byteArray;
  3950. };
  3951. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3952. var byteArray = new Uint8Array(dataLength);
  3953. var srcData = new Uint8Array(arrayBuffer);
  3954. var index = 0;
  3955. for (var y = height - 1; y >= 0; y--) {
  3956. for (var x = 0; x < width; x++) {
  3957. var srcPos = dataOffset + (x + y * width) * 3;
  3958. byteArray[index + 2] = srcData[srcPos];
  3959. byteArray[index + 1] = srcData[srcPos + 1];
  3960. byteArray[index] = srcData[srcPos + 2];
  3961. index += 3;
  3962. }
  3963. }
  3964. return byteArray;
  3965. };
  3966. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3967. var byteArray = new Uint8Array(dataLength);
  3968. var srcData = new Uint8Array(arrayBuffer);
  3969. var index = 0;
  3970. for (var y = height - 1; y >= 0; y--) {
  3971. for (var x = 0; x < width; x++) {
  3972. var srcPos = dataOffset + (x + y * width);
  3973. byteArray[index] = srcData[srcPos];
  3974. index++;
  3975. }
  3976. }
  3977. return byteArray;
  3978. };
  3979. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3980. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3981. if (header[off_magic] != DDS_MAGIC) {
  3982. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3983. return;
  3984. }
  3985. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3986. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3987. return;
  3988. }
  3989. if (info.isFourCC) {
  3990. fourCC = header[off_pfFourCC];
  3991. switch (fourCC) {
  3992. case FOURCC_DXT1:
  3993. blockBytes = 8;
  3994. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3995. break;
  3996. case FOURCC_DXT3:
  3997. blockBytes = 16;
  3998. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3999. break;
  4000. case FOURCC_DXT5:
  4001. blockBytes = 16;
  4002. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4003. break;
  4004. default:
  4005. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4006. return;
  4007. }
  4008. }
  4009. mipmapCount = 1;
  4010. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4011. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4012. }
  4013. var bpp = header[off_RGBbpp];
  4014. for (var face = 0; face < faces; face++) {
  4015. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4016. width = header[off_width];
  4017. height = header[off_height];
  4018. dataOffset = header[off_size] + 4;
  4019. for (i = 0; i < mipmapCount; ++i) {
  4020. if (info.isRGB) {
  4021. if (bpp == 24) {
  4022. dataLength = width * height * 3;
  4023. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4024. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4025. }
  4026. else {
  4027. dataLength = width * height * 4;
  4028. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4029. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4030. }
  4031. }
  4032. else if (info.isLuminance) {
  4033. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4034. var unpaddedRowSize = width;
  4035. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4036. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4037. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4038. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4039. }
  4040. else {
  4041. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4042. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4043. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4044. }
  4045. dataOffset += dataLength;
  4046. width *= 0.5;
  4047. height *= 0.5;
  4048. width = Math.max(1.0, width);
  4049. height = Math.max(1.0, height);
  4050. }
  4051. }
  4052. };
  4053. return DDSTools;
  4054. })();
  4055. Internals.DDSTools = DDSTools;
  4056. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4057. })(BABYLON || (BABYLON = {}));
  4058. var BABYLON;
  4059. (function (BABYLON) {
  4060. var SmartArray = (function () {
  4061. function SmartArray(capacity) {
  4062. this.length = 0;
  4063. this._duplicateId = 0;
  4064. this.data = new Array(capacity);
  4065. this._id = SmartArray._GlobalId++;
  4066. }
  4067. SmartArray.prototype.push = function (value) {
  4068. this.data[this.length++] = value;
  4069. if (this.length > this.data.length) {
  4070. this.data.length *= 2;
  4071. }
  4072. if (!value.__smartArrayFlags) {
  4073. value.__smartArrayFlags = {};
  4074. }
  4075. value.__smartArrayFlags[this._id] = this._duplicateId;
  4076. };
  4077. SmartArray.prototype.pushNoDuplicate = function (value) {
  4078. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4079. return;
  4080. }
  4081. this.push(value);
  4082. };
  4083. SmartArray.prototype.sort = function (compareFn) {
  4084. this.data.sort(compareFn);
  4085. };
  4086. SmartArray.prototype.reset = function () {
  4087. this.length = 0;
  4088. this._duplicateId++;
  4089. };
  4090. SmartArray.prototype.concat = function (array) {
  4091. if (array.length === 0) {
  4092. return;
  4093. }
  4094. if (this.length + array.length > this.data.length) {
  4095. this.data.length = (this.length + array.length) * 2;
  4096. }
  4097. for (var index = 0; index < array.length; index++) {
  4098. this.data[this.length++] = (array.data || array)[index];
  4099. }
  4100. };
  4101. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4102. if (array.length === 0) {
  4103. return;
  4104. }
  4105. if (this.length + array.length > this.data.length) {
  4106. this.data.length = (this.length + array.length) * 2;
  4107. }
  4108. for (var index = 0; index < array.length; index++) {
  4109. var item = (array.data || array)[index];
  4110. this.pushNoDuplicate(item);
  4111. }
  4112. };
  4113. SmartArray.prototype.indexOf = function (value) {
  4114. var position = this.data.indexOf(value);
  4115. if (position >= this.length) {
  4116. return -1;
  4117. }
  4118. return position;
  4119. };
  4120. // Statics
  4121. SmartArray._GlobalId = 0;
  4122. return SmartArray;
  4123. })();
  4124. BABYLON.SmartArray = SmartArray;
  4125. })(BABYLON || (BABYLON = {}));
  4126. var BABYLON;
  4127. (function (BABYLON) {
  4128. var SmartCollection = (function () {
  4129. function SmartCollection(capacity) {
  4130. if (capacity === void 0) { capacity = 10; }
  4131. this.count = 0;
  4132. this._initialCapacity = capacity;
  4133. this.items = {};
  4134. this._keys = new Array(this._initialCapacity);
  4135. }
  4136. SmartCollection.prototype.add = function (key, item) {
  4137. if (this.items[key] != undefined) {
  4138. return -1;
  4139. }
  4140. this.items[key] = item;
  4141. //literal keys are always strings, but we keep source type of key in _keys array
  4142. this._keys[this.count++] = key;
  4143. if (this.count > this._keys.length) {
  4144. this._keys.length *= 2;
  4145. }
  4146. return this.count;
  4147. };
  4148. SmartCollection.prototype.remove = function (key) {
  4149. if (this.items[key] == undefined) {
  4150. return -1;
  4151. }
  4152. return this.removeItemOfIndex(this.indexOf(key));
  4153. };
  4154. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4155. if (index < this.count && index > -1) {
  4156. delete this.items[this._keys[index]];
  4157. //here, shifting by hand is better optimised than .splice
  4158. while (index < this.count) {
  4159. this._keys[index] = this._keys[index + 1];
  4160. index++;
  4161. }
  4162. }
  4163. else {
  4164. return -1;
  4165. }
  4166. return --this.count;
  4167. };
  4168. SmartCollection.prototype.indexOf = function (key) {
  4169. for (var i = 0; i !== this.count; i++) {
  4170. if (this._keys[i] === key) {
  4171. return i;
  4172. }
  4173. }
  4174. return -1;
  4175. };
  4176. SmartCollection.prototype.item = function (key) {
  4177. return this.items[key];
  4178. };
  4179. SmartCollection.prototype.getAllKeys = function () {
  4180. if (this.count > 0) {
  4181. var keys = new Array(this.count);
  4182. for (var i = 0; i < this.count; i++) {
  4183. keys[i] = this._keys[i];
  4184. }
  4185. return keys;
  4186. }
  4187. else {
  4188. return undefined;
  4189. }
  4190. };
  4191. SmartCollection.prototype.getKeyByIndex = function (index) {
  4192. if (index < this.count && index > -1) {
  4193. return this._keys[index];
  4194. }
  4195. else {
  4196. return undefined;
  4197. }
  4198. };
  4199. SmartCollection.prototype.getItemByIndex = function (index) {
  4200. if (index < this.count && index > -1) {
  4201. return this.items[this._keys[index]];
  4202. }
  4203. else {
  4204. return undefined;
  4205. }
  4206. };
  4207. SmartCollection.prototype.empty = function () {
  4208. if (this.count > 0) {
  4209. this.count = 0;
  4210. this.items = {};
  4211. this._keys = new Array(this._initialCapacity);
  4212. }
  4213. };
  4214. SmartCollection.prototype.forEach = function (block) {
  4215. var key;
  4216. for (key in this.items) {
  4217. if (this.items.hasOwnProperty(key)) {
  4218. block(this.items[key]);
  4219. }
  4220. }
  4221. };
  4222. return SmartCollection;
  4223. })();
  4224. BABYLON.SmartCollection = SmartCollection;
  4225. })(BABYLON || (BABYLON = {}));
  4226. var BABYLON;
  4227. (function (BABYLON) {
  4228. // Screenshots
  4229. var screenshotCanvas;
  4230. var cloneValue = function (source, destinationObject) {
  4231. if (!source)
  4232. return null;
  4233. if (source instanceof BABYLON.Mesh) {
  4234. return null;
  4235. }
  4236. if (source instanceof BABYLON.SubMesh) {
  4237. return source.clone(destinationObject);
  4238. }
  4239. else if (source.clone) {
  4240. return source.clone();
  4241. }
  4242. return null;
  4243. };
  4244. var Tools = (function () {
  4245. function Tools() {
  4246. }
  4247. Tools.ToHex = function (i) {
  4248. var str = i.toString(16);
  4249. if (i <= 15) {
  4250. return ("0" + str).toUpperCase();
  4251. }
  4252. return str.toUpperCase();
  4253. };
  4254. Tools.SetImmediate = function (action) {
  4255. if (window.setImmediate) {
  4256. window.setImmediate(action);
  4257. }
  4258. else {
  4259. setTimeout(action, 1);
  4260. }
  4261. };
  4262. Tools.IsExponantOfTwo = function (value) {
  4263. var count = 1;
  4264. do {
  4265. count *= 2;
  4266. } while (count < value);
  4267. return count === value;
  4268. };
  4269. Tools.GetExponantOfTwo = function (value, max) {
  4270. var count = 1;
  4271. do {
  4272. count *= 2;
  4273. } while (count < value);
  4274. if (count > max)
  4275. count = max;
  4276. return count;
  4277. };
  4278. Tools.GetFilename = function (path) {
  4279. var index = path.lastIndexOf("/");
  4280. if (index < 0)
  4281. return path;
  4282. return path.substring(index + 1);
  4283. };
  4284. Tools.GetDOMTextContent = function (element) {
  4285. var result = "";
  4286. var child = element.firstChild;
  4287. while (child) {
  4288. if (child.nodeType === 3) {
  4289. result += child.textContent;
  4290. }
  4291. child = child.nextSibling;
  4292. }
  4293. return result;
  4294. };
  4295. Tools.ToDegrees = function (angle) {
  4296. return angle * 180 / Math.PI;
  4297. };
  4298. Tools.ToRadians = function (angle) {
  4299. return angle * Math.PI / 180;
  4300. };
  4301. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4302. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4303. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4304. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4305. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4306. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4307. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4308. }
  4309. return {
  4310. minimum: minimum,
  4311. maximum: maximum
  4312. };
  4313. };
  4314. Tools.ExtractMinAndMax = function (positions, start, count) {
  4315. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4316. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4317. for (var index = start; index < start + count; index++) {
  4318. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4319. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4320. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4321. }
  4322. return {
  4323. minimum: minimum,
  4324. maximum: maximum
  4325. };
  4326. };
  4327. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4328. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4329. return undefined;
  4330. return Array.isArray(obj) ? obj : [obj];
  4331. };
  4332. // Misc.
  4333. Tools.GetPointerPrefix = function () {
  4334. var eventPrefix = "pointer";
  4335. // Check if hand.js is referenced or if the browser natively supports pointer events
  4336. if (!navigator.pointerEnabled) {
  4337. eventPrefix = "mouse";
  4338. }
  4339. return eventPrefix;
  4340. };
  4341. Tools.QueueNewFrame = function (func) {
  4342. if (window.requestAnimationFrame)
  4343. window.requestAnimationFrame(func);
  4344. else if (window.msRequestAnimationFrame)
  4345. window.msRequestAnimationFrame(func);
  4346. else if (window.webkitRequestAnimationFrame)
  4347. window.webkitRequestAnimationFrame(func);
  4348. else if (window.mozRequestAnimationFrame)
  4349. window.mozRequestAnimationFrame(func);
  4350. else if (window.oRequestAnimationFrame)
  4351. window.oRequestAnimationFrame(func);
  4352. else {
  4353. window.setTimeout(func, 16);
  4354. }
  4355. };
  4356. Tools.RequestFullscreen = function (element) {
  4357. if (element.requestFullscreen)
  4358. element.requestFullscreen();
  4359. else if (element.msRequestFullscreen)
  4360. element.msRequestFullscreen();
  4361. else if (element.webkitRequestFullscreen)
  4362. element.webkitRequestFullscreen();
  4363. else if (element.mozRequestFullScreen)
  4364. element.mozRequestFullScreen();
  4365. };
  4366. Tools.ExitFullscreen = function () {
  4367. if (document.exitFullscreen) {
  4368. document.exitFullscreen();
  4369. }
  4370. else if (document.mozCancelFullScreen) {
  4371. document.mozCancelFullScreen();
  4372. }
  4373. else if (document.webkitCancelFullScreen) {
  4374. document.webkitCancelFullScreen();
  4375. }
  4376. else if (document.msCancelFullScreen) {
  4377. document.msCancelFullScreen();
  4378. }
  4379. };
  4380. // External files
  4381. Tools.CleanUrl = function (url) {
  4382. url = url.replace(/#/mg, "%23");
  4383. return url;
  4384. };
  4385. Tools.LoadImage = function (url, onload, onerror, database) {
  4386. url = Tools.CleanUrl(url);
  4387. var img = new Image();
  4388. if (url.substr(0, 5) !== "data:")
  4389. img.crossOrigin = 'anonymous';
  4390. img.onload = function () {
  4391. onload(img);
  4392. };
  4393. img.onerror = function (err) {
  4394. Tools.Error("Error while trying to load texture: " + url);
  4395. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4396. onload(img);
  4397. };
  4398. var noIndexedDB = function () {
  4399. img.src = url;
  4400. };
  4401. var loadFromIndexedDB = function () {
  4402. database.loadImageFromDB(url, img);
  4403. };
  4404. //ANY database to do!
  4405. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4406. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4407. }
  4408. else {
  4409. if (url.indexOf("file:") === -1) {
  4410. noIndexedDB();
  4411. }
  4412. else {
  4413. try {
  4414. var textureName = url.substring(5);
  4415. var blobURL;
  4416. try {
  4417. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4418. }
  4419. catch (ex) {
  4420. // Chrome doesn't support oneTimeOnly parameter
  4421. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4422. }
  4423. img.src = blobURL;
  4424. }
  4425. catch (e) {
  4426. img.src = null;
  4427. }
  4428. }
  4429. }
  4430. return img;
  4431. };
  4432. //ANY
  4433. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4434. url = Tools.CleanUrl(url);
  4435. var noIndexedDB = function () {
  4436. var request = new XMLHttpRequest();
  4437. var loadUrl = Tools.BaseUrl + url;
  4438. request.open('GET', loadUrl, true);
  4439. if (useArrayBuffer) {
  4440. request.responseType = "arraybuffer";
  4441. }
  4442. request.onprogress = progressCallBack;
  4443. request.onreadystatechange = function () {
  4444. if (request.readyState === 4) {
  4445. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4446. callback(!useArrayBuffer ? request.responseText : request.response);
  4447. }
  4448. else {
  4449. if (onError) {
  4450. onError();
  4451. }
  4452. else {
  4453. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4454. }
  4455. }
  4456. }
  4457. };
  4458. request.send(null);
  4459. };
  4460. var loadFromIndexedDB = function () {
  4461. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4462. };
  4463. if (url.indexOf("file:") !== -1) {
  4464. var fileName = url.substring(5);
  4465. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4466. }
  4467. else {
  4468. // Caching all files
  4469. if (database && database.enableSceneOffline) {
  4470. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4471. }
  4472. else {
  4473. noIndexedDB();
  4474. }
  4475. }
  4476. };
  4477. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4478. var reader = new FileReader();
  4479. reader.onload = function (e) {
  4480. //target doesn't have result from ts 1.3
  4481. callback(e.target['result']);
  4482. };
  4483. reader.onprogress = progressCallback;
  4484. reader.readAsDataURL(fileToLoad);
  4485. };
  4486. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4487. var reader = new FileReader();
  4488. reader.onerror = function (e) {
  4489. Tools.Log("Error while reading file: " + fileToLoad.name);
  4490. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4491. };
  4492. reader.onload = function (e) {
  4493. //target doesn't have result from ts 1.3
  4494. callback(e.target['result']);
  4495. };
  4496. reader.onprogress = progressCallBack;
  4497. if (!useArrayBuffer) {
  4498. // Asynchronous read
  4499. reader.readAsText(fileToLoad);
  4500. }
  4501. else {
  4502. reader.readAsArrayBuffer(fileToLoad);
  4503. }
  4504. };
  4505. // Misc.
  4506. Tools.Clamp = function (value, min, max) {
  4507. if (min === void 0) { min = 0; }
  4508. if (max === void 0) { max = 1; }
  4509. return Math.min(max, Math.max(min, value));
  4510. };
  4511. // Returns -1 when value is a negative number and
  4512. // +1 when value is a positive number.
  4513. Tools.Sign = function (value) {
  4514. value = +value; // convert to a number
  4515. if (value === 0 || isNaN(value))
  4516. return value;
  4517. return value > 0 ? 1 : -1;
  4518. };
  4519. Tools.Format = function (value, decimals) {
  4520. if (decimals === void 0) { decimals = 2; }
  4521. return value.toFixed(decimals);
  4522. };
  4523. Tools.CheckExtends = function (v, min, max) {
  4524. if (v.x < min.x)
  4525. min.x = v.x;
  4526. if (v.y < min.y)
  4527. min.y = v.y;
  4528. if (v.z < min.z)
  4529. min.z = v.z;
  4530. if (v.x > max.x)
  4531. max.x = v.x;
  4532. if (v.y > max.y)
  4533. max.y = v.y;
  4534. if (v.z > max.z)
  4535. max.z = v.z;
  4536. };
  4537. Tools.WithinEpsilon = function (a, b, epsilon) {
  4538. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4539. var num = a - b;
  4540. return -epsilon <= num && num <= epsilon;
  4541. };
  4542. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4543. for (var prop in source) {
  4544. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4545. continue;
  4546. }
  4547. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4548. continue;
  4549. }
  4550. var sourceValue = source[prop];
  4551. var typeOfSourceValue = typeof sourceValue;
  4552. if (typeOfSourceValue === "function") {
  4553. continue;
  4554. }
  4555. if (typeOfSourceValue === "object") {
  4556. if (sourceValue instanceof Array) {
  4557. destination[prop] = [];
  4558. if (sourceValue.length > 0) {
  4559. if (typeof sourceValue[0] == "object") {
  4560. for (var index = 0; index < sourceValue.length; index++) {
  4561. var clonedValue = cloneValue(sourceValue[index], destination);
  4562. if (destination[prop].indexOf(clonedValue) === -1) {
  4563. destination[prop].push(clonedValue);
  4564. }
  4565. }
  4566. }
  4567. else {
  4568. destination[prop] = sourceValue.slice(0);
  4569. }
  4570. }
  4571. }
  4572. else {
  4573. destination[prop] = cloneValue(sourceValue, destination);
  4574. }
  4575. }
  4576. else {
  4577. destination[prop] = sourceValue;
  4578. }
  4579. }
  4580. };
  4581. Tools.IsEmpty = function (obj) {
  4582. for (var i in obj) {
  4583. return false;
  4584. }
  4585. return true;
  4586. };
  4587. Tools.RegisterTopRootEvents = function (events) {
  4588. for (var index = 0; index < events.length; index++) {
  4589. var event = events[index];
  4590. window.addEventListener(event.name, event.handler, false);
  4591. try {
  4592. if (window.parent) {
  4593. window.parent.addEventListener(event.name, event.handler, false);
  4594. }
  4595. }
  4596. catch (e) {
  4597. }
  4598. }
  4599. };
  4600. Tools.UnregisterTopRootEvents = function (events) {
  4601. for (var index = 0; index < events.length; index++) {
  4602. var event = events[index];
  4603. window.removeEventListener(event.name, event.handler);
  4604. try {
  4605. if (window.parent) {
  4606. window.parent.removeEventListener(event.name, event.handler);
  4607. }
  4608. }
  4609. catch (e) {
  4610. }
  4611. }
  4612. };
  4613. Tools.DumpFramebuffer = function (width, height, engine) {
  4614. // Read the contents of the framebuffer
  4615. var numberOfChannelsByLine = width * 4;
  4616. var halfHeight = height / 2;
  4617. //Reading datas from WebGL
  4618. var data = engine.readPixels(0, 0, width, height);
  4619. //To flip image on Y axis.
  4620. for (var i = 0; i < halfHeight; i++) {
  4621. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4622. var currentCell = j + i * numberOfChannelsByLine;
  4623. var targetLine = height - i - 1;
  4624. var targetCell = j + targetLine * numberOfChannelsByLine;
  4625. var temp = data[currentCell];
  4626. data[currentCell] = data[targetCell];
  4627. data[targetCell] = temp;
  4628. }
  4629. }
  4630. // Create a 2D canvas to store the result
  4631. if (!screenshotCanvas) {
  4632. screenshotCanvas = document.createElement('canvas');
  4633. }
  4634. screenshotCanvas.width = width;
  4635. screenshotCanvas.height = height;
  4636. var context = screenshotCanvas.getContext('2d');
  4637. // Copy the pixels to a 2D canvas
  4638. var imageData = context.createImageData(width, height);
  4639. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4640. var castData = imageData.data;
  4641. castData.set(data);
  4642. context.putImageData(imageData, 0, 0);
  4643. var base64Image = screenshotCanvas.toDataURL();
  4644. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4645. if (("download" in document.createElement("a"))) {
  4646. var a = window.document.createElement("a");
  4647. a.href = base64Image;
  4648. var date = new Date();
  4649. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4650. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4651. window.document.body.appendChild(a);
  4652. a.addEventListener("click", function () {
  4653. a.parentElement.removeChild(a);
  4654. });
  4655. a.click();
  4656. }
  4657. else {
  4658. var newWindow = window.open("");
  4659. var img = newWindow.document.createElement("img");
  4660. img.src = base64Image;
  4661. newWindow.document.body.appendChild(img);
  4662. }
  4663. };
  4664. Tools.CreateScreenshot = function (engine, camera, size) {
  4665. var width;
  4666. var height;
  4667. var scene = camera.getScene();
  4668. var previousCamera = null;
  4669. if (scene.activeCamera !== camera) {
  4670. previousCamera = scene.activeCamera;
  4671. scene.activeCamera = camera;
  4672. }
  4673. //If a precision value is specified
  4674. if (size.precision) {
  4675. width = Math.round(engine.getRenderWidth() * size.precision);
  4676. height = Math.round(width / engine.getAspectRatio(camera));
  4677. size = { width: width, height: height };
  4678. }
  4679. else if (size.width && size.height) {
  4680. width = size.width;
  4681. height = size.height;
  4682. }
  4683. else if (size.width && !size.height) {
  4684. width = size.width;
  4685. height = Math.round(width / engine.getAspectRatio(camera));
  4686. size = { width: width, height: height };
  4687. }
  4688. else if (size.height && !size.width) {
  4689. height = size.height;
  4690. width = Math.round(height * engine.getAspectRatio(camera));
  4691. size = { width: width, height: height };
  4692. }
  4693. else if (!isNaN(size)) {
  4694. height = size;
  4695. width = size;
  4696. }
  4697. else {
  4698. Tools.Error("Invalid 'size' parameter !");
  4699. return;
  4700. }
  4701. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4702. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4703. texture.renderList = scene.meshes;
  4704. texture.onAfterRender = function () {
  4705. Tools.DumpFramebuffer(width, height, engine);
  4706. };
  4707. scene.incrementRenderId();
  4708. texture.render(true);
  4709. texture.dispose();
  4710. if (previousCamera) {
  4711. scene.activeCamera = previousCamera;
  4712. }
  4713. };
  4714. // XHR response validator for local file scenario
  4715. Tools.ValidateXHRData = function (xhr, dataType) {
  4716. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4717. if (dataType === void 0) { dataType = 7; }
  4718. try {
  4719. if (dataType & 1) {
  4720. if (xhr.responseText && xhr.responseText.length > 0) {
  4721. return true;
  4722. }
  4723. else if (dataType === 1) {
  4724. return false;
  4725. }
  4726. }
  4727. if (dataType & 2) {
  4728. // Check header width and height since there is no "TGA" magic number
  4729. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4730. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4731. return true;
  4732. }
  4733. else if (dataType === 2) {
  4734. return false;
  4735. }
  4736. }
  4737. if (dataType & 4) {
  4738. // Check for the "DDS" magic number
  4739. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4740. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4741. return true;
  4742. }
  4743. else {
  4744. return false;
  4745. }
  4746. }
  4747. }
  4748. catch (e) {
  4749. }
  4750. return false;
  4751. };
  4752. Object.defineProperty(Tools, "NoneLogLevel", {
  4753. get: function () {
  4754. return Tools._NoneLogLevel;
  4755. },
  4756. enumerable: true,
  4757. configurable: true
  4758. });
  4759. Object.defineProperty(Tools, "MessageLogLevel", {
  4760. get: function () {
  4761. return Tools._MessageLogLevel;
  4762. },
  4763. enumerable: true,
  4764. configurable: true
  4765. });
  4766. Object.defineProperty(Tools, "WarningLogLevel", {
  4767. get: function () {
  4768. return Tools._WarningLogLevel;
  4769. },
  4770. enumerable: true,
  4771. configurable: true
  4772. });
  4773. Object.defineProperty(Tools, "ErrorLogLevel", {
  4774. get: function () {
  4775. return Tools._ErrorLogLevel;
  4776. },
  4777. enumerable: true,
  4778. configurable: true
  4779. });
  4780. Object.defineProperty(Tools, "AllLogLevel", {
  4781. get: function () {
  4782. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4783. },
  4784. enumerable: true,
  4785. configurable: true
  4786. });
  4787. Tools._AddLogEntry = function (entry) {
  4788. Tools._LogCache = entry + Tools._LogCache;
  4789. if (Tools.OnNewCacheEntry) {
  4790. Tools.OnNewCacheEntry(entry);
  4791. }
  4792. };
  4793. Tools._FormatMessage = function (message) {
  4794. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4795. var date = new Date();
  4796. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4797. };
  4798. Tools._LogDisabled = function (message) {
  4799. // nothing to do
  4800. };
  4801. Tools._LogEnabled = function (message) {
  4802. var formattedMessage = Tools._FormatMessage(message);
  4803. console.log("BJS - " + formattedMessage);
  4804. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4805. Tools._AddLogEntry(entry);
  4806. };
  4807. Tools._WarnDisabled = function (message) {
  4808. // nothing to do
  4809. };
  4810. Tools._WarnEnabled = function (message) {
  4811. var formattedMessage = Tools._FormatMessage(message);
  4812. console.warn("BJS - " + formattedMessage);
  4813. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4814. Tools._AddLogEntry(entry);
  4815. };
  4816. Tools._ErrorDisabled = function (message) {
  4817. // nothing to do
  4818. };
  4819. Tools._ErrorEnabled = function (message) {
  4820. Tools.errorsCount++;
  4821. var formattedMessage = Tools._FormatMessage(message);
  4822. console.error("BJS - " + formattedMessage);
  4823. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4824. Tools._AddLogEntry(entry);
  4825. };
  4826. Object.defineProperty(Tools, "LogCache", {
  4827. get: function () {
  4828. return Tools._LogCache;
  4829. },
  4830. enumerable: true,
  4831. configurable: true
  4832. });
  4833. Tools.ClearLogCache = function () {
  4834. Tools._LogCache = "";
  4835. Tools.errorsCount = 0;
  4836. };
  4837. Object.defineProperty(Tools, "LogLevels", {
  4838. set: function (level) {
  4839. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4840. Tools.Log = Tools._LogEnabled;
  4841. }
  4842. else {
  4843. Tools.Log = Tools._LogDisabled;
  4844. }
  4845. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4846. Tools.Warn = Tools._WarnEnabled;
  4847. }
  4848. else {
  4849. Tools.Warn = Tools._WarnDisabled;
  4850. }
  4851. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4852. Tools.Error = Tools._ErrorEnabled;
  4853. }
  4854. else {
  4855. Tools.Error = Tools._ErrorDisabled;
  4856. }
  4857. },
  4858. enumerable: true,
  4859. configurable: true
  4860. });
  4861. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4862. get: function () {
  4863. return Tools._PerformanceNoneLogLevel;
  4864. },
  4865. enumerable: true,
  4866. configurable: true
  4867. });
  4868. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4869. get: function () {
  4870. return Tools._PerformanceUserMarkLogLevel;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4876. get: function () {
  4877. return Tools._PerformanceConsoleLogLevel;
  4878. },
  4879. enumerable: true,
  4880. configurable: true
  4881. });
  4882. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4883. set: function (level) {
  4884. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4885. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4886. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4887. return;
  4888. }
  4889. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4890. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4891. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4892. return;
  4893. }
  4894. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4895. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4896. },
  4897. enumerable: true,
  4898. configurable: true
  4899. });
  4900. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4901. };
  4902. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4903. };
  4904. Tools._StartUserMark = function (counterName, condition) {
  4905. if (condition === void 0) { condition = true; }
  4906. if (!condition || !Tools._performance.mark) {
  4907. return;
  4908. }
  4909. Tools._performance.mark(counterName + "-Begin");
  4910. };
  4911. Tools._EndUserMark = function (counterName, condition) {
  4912. if (condition === void 0) { condition = true; }
  4913. if (!condition || !Tools._performance.mark) {
  4914. return;
  4915. }
  4916. Tools._performance.mark(counterName + "-End");
  4917. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4918. };
  4919. Tools._StartPerformanceConsole = function (counterName, condition) {
  4920. if (condition === void 0) { condition = true; }
  4921. if (!condition) {
  4922. return;
  4923. }
  4924. Tools._StartUserMark(counterName, condition);
  4925. if (console.time) {
  4926. console.time(counterName);
  4927. }
  4928. };
  4929. Tools._EndPerformanceConsole = function (counterName, condition) {
  4930. if (condition === void 0) { condition = true; }
  4931. if (!condition) {
  4932. return;
  4933. }
  4934. Tools._EndUserMark(counterName, condition);
  4935. if (console.time) {
  4936. console.timeEnd(counterName);
  4937. }
  4938. };
  4939. Object.defineProperty(Tools, "Now", {
  4940. get: function () {
  4941. if (window.performance && window.performance.now) {
  4942. return window.performance.now();
  4943. }
  4944. return new Date().getTime();
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. // Deprecated
  4950. Tools.GetFps = function () {
  4951. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4952. return 0;
  4953. };
  4954. Tools.BaseUrl = "";
  4955. // Logs
  4956. Tools._NoneLogLevel = 0;
  4957. Tools._MessageLogLevel = 1;
  4958. Tools._WarningLogLevel = 2;
  4959. Tools._ErrorLogLevel = 4;
  4960. Tools._LogCache = "";
  4961. Tools.errorsCount = 0;
  4962. Tools.Log = Tools._LogEnabled;
  4963. Tools.Warn = Tools._WarnEnabled;
  4964. Tools.Error = Tools._ErrorEnabled;
  4965. // Performances
  4966. Tools._PerformanceNoneLogLevel = 0;
  4967. Tools._PerformanceUserMarkLogLevel = 1;
  4968. Tools._PerformanceConsoleLogLevel = 2;
  4969. Tools._performance = window.performance;
  4970. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4971. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4972. return Tools;
  4973. })();
  4974. BABYLON.Tools = Tools;
  4975. /**
  4976. * An implementation of a loop for asynchronous functions.
  4977. */
  4978. var AsyncLoop = (function () {
  4979. /**
  4980. * Constroctor.
  4981. * @param iterations the number of iterations.
  4982. * @param _fn the function to run each iteration
  4983. * @param _successCallback the callback that will be called upon succesful execution
  4984. * @param offset starting offset.
  4985. */
  4986. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4987. if (offset === void 0) { offset = 0; }
  4988. this.iterations = iterations;
  4989. this._fn = _fn;
  4990. this._successCallback = _successCallback;
  4991. this.index = offset - 1;
  4992. this._done = false;
  4993. }
  4994. /**
  4995. * Execute the next iteration. Must be called after the last iteration was finished.
  4996. */
  4997. AsyncLoop.prototype.executeNext = function () {
  4998. if (!this._done) {
  4999. if (this.index + 1 < this.iterations) {
  5000. ++this.index;
  5001. this._fn(this);
  5002. }
  5003. else {
  5004. this.breakLoop();
  5005. }
  5006. }
  5007. };
  5008. /**
  5009. * Break the loop and run the success callback.
  5010. */
  5011. AsyncLoop.prototype.breakLoop = function () {
  5012. this._done = true;
  5013. this._successCallback();
  5014. };
  5015. /**
  5016. * Helper function
  5017. */
  5018. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5019. if (offset === void 0) { offset = 0; }
  5020. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5021. loop.executeNext();
  5022. return loop;
  5023. };
  5024. /**
  5025. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5026. * @param iterations total number of iterations
  5027. * @param syncedIterations number of synchronous iterations in each async iteration.
  5028. * @param fn the function to call each iteration.
  5029. * @param callback a success call back that will be called when iterating stops.
  5030. * @param breakFunction a break condition (optional)
  5031. * @param timeout timeout settings for the setTimeout function. default - 0.
  5032. * @constructor
  5033. */
  5034. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5035. if (timeout === void 0) { timeout = 0; }
  5036. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5037. if (breakFunction && breakFunction())
  5038. loop.breakLoop();
  5039. else {
  5040. setTimeout(function () {
  5041. for (var i = 0; i < syncedIterations; ++i) {
  5042. var iteration = (loop.index * syncedIterations) + i;
  5043. if (iteration >= iterations)
  5044. break;
  5045. fn(iteration);
  5046. if (breakFunction && breakFunction()) {
  5047. loop.breakLoop();
  5048. break;
  5049. }
  5050. }
  5051. loop.executeNext();
  5052. }, timeout);
  5053. }
  5054. }, callback);
  5055. };
  5056. return AsyncLoop;
  5057. })();
  5058. BABYLON.AsyncLoop = AsyncLoop;
  5059. })(BABYLON || (BABYLON = {}));
  5060. var BABYLON;
  5061. (function (BABYLON) {
  5062. var _DepthCullingState = (function () {
  5063. function _DepthCullingState() {
  5064. this._isDepthTestDirty = false;
  5065. this._isDepthMaskDirty = false;
  5066. this._isDepthFuncDirty = false;
  5067. this._isCullFaceDirty = false;
  5068. this._isCullDirty = false;
  5069. this._isZOffsetDirty = false;
  5070. }
  5071. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5072. get: function () {
  5073. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5074. },
  5075. enumerable: true,
  5076. configurable: true
  5077. });
  5078. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5079. get: function () {
  5080. return this._zOffset;
  5081. },
  5082. set: function (value) {
  5083. if (this._zOffset === value) {
  5084. return;
  5085. }
  5086. this._zOffset = value;
  5087. this._isZOffsetDirty = true;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5093. get: function () {
  5094. return this._cullFace;
  5095. },
  5096. set: function (value) {
  5097. if (this._cullFace === value) {
  5098. return;
  5099. }
  5100. this._cullFace = value;
  5101. this._isCullFaceDirty = true;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5107. get: function () {
  5108. return this._cull;
  5109. },
  5110. set: function (value) {
  5111. if (this._cull === value) {
  5112. return;
  5113. }
  5114. this._cull = value;
  5115. this._isCullDirty = true;
  5116. },
  5117. enumerable: true,
  5118. configurable: true
  5119. });
  5120. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5121. get: function () {
  5122. return this._depthFunc;
  5123. },
  5124. set: function (value) {
  5125. if (this._depthFunc === value) {
  5126. return;
  5127. }
  5128. this._depthFunc = value;
  5129. this._isDepthFuncDirty = true;
  5130. },
  5131. enumerable: true,
  5132. configurable: true
  5133. });
  5134. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5135. get: function () {
  5136. return this._depthMask;
  5137. },
  5138. set: function (value) {
  5139. if (this._depthMask === value) {
  5140. return;
  5141. }
  5142. this._depthMask = value;
  5143. this._isDepthMaskDirty = true;
  5144. },
  5145. enumerable: true,
  5146. configurable: true
  5147. });
  5148. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5149. get: function () {
  5150. return this._depthTest;
  5151. },
  5152. set: function (value) {
  5153. if (this._depthTest === value) {
  5154. return;
  5155. }
  5156. this._depthTest = value;
  5157. this._isDepthTestDirty = true;
  5158. },
  5159. enumerable: true,
  5160. configurable: true
  5161. });
  5162. _DepthCullingState.prototype.reset = function () {
  5163. this._depthMask = true;
  5164. this._depthTest = true;
  5165. this._depthFunc = null;
  5166. this._cull = null;
  5167. this._cullFace = null;
  5168. this._zOffset = 0;
  5169. this._isDepthTestDirty = true;
  5170. this._isDepthMaskDirty = true;
  5171. this._isDepthFuncDirty = false;
  5172. this._isCullFaceDirty = false;
  5173. this._isCullDirty = false;
  5174. this._isZOffsetDirty = false;
  5175. };
  5176. _DepthCullingState.prototype.apply = function (gl) {
  5177. if (!this.isDirty) {
  5178. return;
  5179. }
  5180. // Cull
  5181. if (this._isCullDirty) {
  5182. if (this.cull) {
  5183. gl.enable(gl.CULL_FACE);
  5184. }
  5185. else {
  5186. gl.disable(gl.CULL_FACE);
  5187. }
  5188. this._isCullDirty = false;
  5189. }
  5190. // Cull face
  5191. if (this._isCullFaceDirty) {
  5192. gl.cullFace(this.cullFace);
  5193. this._isCullFaceDirty = false;
  5194. }
  5195. // Depth mask
  5196. if (this._isDepthMaskDirty) {
  5197. gl.depthMask(this.depthMask);
  5198. this._isDepthMaskDirty = false;
  5199. }
  5200. // Depth test
  5201. if (this._isDepthTestDirty) {
  5202. if (this.depthTest) {
  5203. gl.enable(gl.DEPTH_TEST);
  5204. }
  5205. else {
  5206. gl.disable(gl.DEPTH_TEST);
  5207. }
  5208. this._isDepthTestDirty = false;
  5209. }
  5210. // Depth func
  5211. if (this._isDepthFuncDirty) {
  5212. gl.depthFunc(this.depthFunc);
  5213. this._isDepthFuncDirty = false;
  5214. }
  5215. // zOffset
  5216. if (this._isZOffsetDirty) {
  5217. if (this.zOffset) {
  5218. gl.enable(gl.POLYGON_OFFSET_FILL);
  5219. gl.polygonOffset(this.zOffset, 0);
  5220. }
  5221. else {
  5222. gl.disable(gl.POLYGON_OFFSET_FILL);
  5223. }
  5224. this._isZOffsetDirty = false;
  5225. }
  5226. };
  5227. return _DepthCullingState;
  5228. })();
  5229. BABYLON._DepthCullingState = _DepthCullingState;
  5230. var _AlphaState = (function () {
  5231. function _AlphaState() {
  5232. this._isAlphaBlendDirty = false;
  5233. this._isBlendFunctionParametersDirty = false;
  5234. this._alphaBlend = false;
  5235. this._blendFunctionParameters = new Array(4);
  5236. }
  5237. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5238. get: function () {
  5239. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5245. get: function () {
  5246. return this._alphaBlend;
  5247. },
  5248. set: function (value) {
  5249. if (this._alphaBlend === value) {
  5250. return;
  5251. }
  5252. this._alphaBlend = value;
  5253. this._isAlphaBlendDirty = true;
  5254. },
  5255. enumerable: true,
  5256. configurable: true
  5257. });
  5258. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5259. if (this._blendFunctionParameters[0] === value0 &&
  5260. this._blendFunctionParameters[1] === value1 &&
  5261. this._blendFunctionParameters[2] === value2 &&
  5262. this._blendFunctionParameters[3] === value3) {
  5263. return;
  5264. }
  5265. this._blendFunctionParameters[0] = value0;
  5266. this._blendFunctionParameters[1] = value1;
  5267. this._blendFunctionParameters[2] = value2;
  5268. this._blendFunctionParameters[3] = value3;
  5269. this._isBlendFunctionParametersDirty = true;
  5270. };
  5271. _AlphaState.prototype.reset = function () {
  5272. this._alphaBlend = false;
  5273. this._blendFunctionParameters[0] = null;
  5274. this._blendFunctionParameters[1] = null;
  5275. this._blendFunctionParameters[2] = null;
  5276. this._blendFunctionParameters[3] = null;
  5277. this._isAlphaBlendDirty = true;
  5278. this._isBlendFunctionParametersDirty = false;
  5279. };
  5280. _AlphaState.prototype.apply = function (gl) {
  5281. if (!this.isDirty) {
  5282. return;
  5283. }
  5284. // Alpha blend
  5285. if (this._isAlphaBlendDirty) {
  5286. if (this._alphaBlend) {
  5287. gl.enable(gl.BLEND);
  5288. }
  5289. else {
  5290. gl.disable(gl.BLEND);
  5291. }
  5292. this._isAlphaBlendDirty = false;
  5293. }
  5294. // Alpha function
  5295. if (this._isBlendFunctionParametersDirty) {
  5296. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5297. this._isBlendFunctionParametersDirty = false;
  5298. }
  5299. };
  5300. return _AlphaState;
  5301. })();
  5302. BABYLON._AlphaState = _AlphaState;
  5303. var compileShader = function (gl, source, type, defines) {
  5304. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5305. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5306. gl.compileShader(shader);
  5307. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5308. throw new Error(gl.getShaderInfoLog(shader));
  5309. }
  5310. return shader;
  5311. };
  5312. var getWebGLTextureType = function (gl, type) {
  5313. var textureType = gl.UNSIGNED_BYTE;
  5314. if (type === Engine.TEXTURETYPE_FLOAT)
  5315. textureType = gl.FLOAT;
  5316. return textureType;
  5317. };
  5318. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5319. var magFilter = gl.NEAREST;
  5320. var minFilter = gl.NEAREST;
  5321. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5322. magFilter = gl.LINEAR;
  5323. if (generateMipMaps) {
  5324. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5325. }
  5326. else {
  5327. minFilter = gl.LINEAR;
  5328. }
  5329. }
  5330. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5331. magFilter = gl.LINEAR;
  5332. if (generateMipMaps) {
  5333. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5334. }
  5335. else {
  5336. minFilter = gl.LINEAR;
  5337. }
  5338. }
  5339. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5340. magFilter = gl.NEAREST;
  5341. if (generateMipMaps) {
  5342. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5343. }
  5344. else {
  5345. minFilter = gl.NEAREST;
  5346. }
  5347. }
  5348. return {
  5349. min: minFilter,
  5350. mag: magFilter
  5351. };
  5352. };
  5353. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5355. var engine = scene.getEngine();
  5356. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5357. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5358. gl.bindTexture(gl.TEXTURE_2D, texture);
  5359. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5360. texture._baseWidth = width;
  5361. texture._baseHeight = height;
  5362. texture._width = potWidth;
  5363. texture._height = potHeight;
  5364. texture.isReady = true;
  5365. processFunction(potWidth, potHeight);
  5366. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5369. if (!noMipmap && !isCompressed) {
  5370. gl.generateMipmap(gl.TEXTURE_2D);
  5371. }
  5372. gl.bindTexture(gl.TEXTURE_2D, null);
  5373. engine._activeTexturesCache = [];
  5374. scene._removePendingData(texture);
  5375. };
  5376. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5377. var onload = function () {
  5378. loadedImages[index] = img;
  5379. loadedImages._internalCount++;
  5380. scene._removePendingData(img);
  5381. if (loadedImages._internalCount === 6) {
  5382. onfinish(loadedImages);
  5383. }
  5384. };
  5385. var onerror = function () {
  5386. scene._removePendingData(img);
  5387. };
  5388. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5389. scene._addPendingData(img);
  5390. };
  5391. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5392. var loadedImages = [];
  5393. loadedImages._internalCount = 0;
  5394. for (var index = 0; index < 6; index++) {
  5395. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5396. }
  5397. };
  5398. var EngineCapabilities = (function () {
  5399. function EngineCapabilities() {
  5400. }
  5401. return EngineCapabilities;
  5402. })();
  5403. BABYLON.EngineCapabilities = EngineCapabilities;
  5404. /**
  5405. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5406. */
  5407. var Engine = (function () {
  5408. /**
  5409. * @constructor
  5410. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5411. * @param {boolean} [antialias] - enable antialias
  5412. * @param options - further options to be sent to the getContext function
  5413. */
  5414. function Engine(canvas, antialias, options) {
  5415. var _this = this;
  5416. // Public members
  5417. this.isFullscreen = false;
  5418. this.isPointerLock = false;
  5419. this.cullBackFaces = true;
  5420. this.renderEvenInBackground = true;
  5421. // To enable/disable IDB support and avoid XHR on .manifest
  5422. this.enableOfflineSupport = true;
  5423. this.scenes = new Array();
  5424. this._windowIsBackground = false;
  5425. this._loadingDivBackgroundColor = "black";
  5426. this._drawCalls = 0;
  5427. this._renderingQueueLaunched = false;
  5428. this._activeRenderLoops = [];
  5429. // FPS
  5430. this.fpsRange = 60;
  5431. this.previousFramesDuration = [];
  5432. this.fps = 60;
  5433. this.deltaTime = 0;
  5434. // States
  5435. this._depthCullingState = new _DepthCullingState();
  5436. this._alphaState = new _AlphaState();
  5437. this._alphaMode = Engine.ALPHA_DISABLE;
  5438. // Cache
  5439. this._loadedTexturesCache = new Array();
  5440. this._activeTexturesCache = new Array();
  5441. this._compiledEffects = {};
  5442. this._uintIndicesCurrentlySet = false;
  5443. this._renderingCanvas = canvas;
  5444. options = options || {};
  5445. options.antialias = antialias;
  5446. if (options.preserveDrawingBuffer === undefined) {
  5447. options.preserveDrawingBuffer = false;
  5448. }
  5449. // GL
  5450. try {
  5451. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5452. }
  5453. catch (e) {
  5454. throw new Error("WebGL not supported");
  5455. }
  5456. if (!this._gl) {
  5457. throw new Error("WebGL not supported");
  5458. }
  5459. this._onBlur = function () {
  5460. _this._windowIsBackground = true;
  5461. };
  5462. this._onFocus = function () {
  5463. _this._windowIsBackground = false;
  5464. };
  5465. window.addEventListener("blur", this._onBlur);
  5466. window.addEventListener("focus", this._onFocus);
  5467. // Viewport
  5468. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5469. this.resize();
  5470. // Caps
  5471. this._caps = new EngineCapabilities();
  5472. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5473. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5474. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5475. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5476. // Infos
  5477. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5478. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5479. if (rendererInfo != null) {
  5480. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5481. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5482. }
  5483. if (!this._glVendor) {
  5484. this._glVendor = "Unknown vendor";
  5485. }
  5486. if (!this._glRenderer) {
  5487. this._glRenderer = "Unknown renderer";
  5488. }
  5489. // Extensions
  5490. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5491. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5492. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5493. 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');
  5494. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5495. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5496. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5497. this._caps.highPrecisionShaderSupported = true;
  5498. if (this._gl.getShaderPrecisionFormat) {
  5499. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5500. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5501. }
  5502. // Depth buffer
  5503. this.setDepthBuffer(true);
  5504. this.setDepthFunctionToLessOrEqual();
  5505. this.setDepthWrite(true);
  5506. // Fullscreen
  5507. this._onFullscreenChange = function () {
  5508. if (document.fullscreen !== undefined) {
  5509. _this.isFullscreen = document.fullscreen;
  5510. }
  5511. else if (document.mozFullScreen !== undefined) {
  5512. _this.isFullscreen = document.mozFullScreen;
  5513. }
  5514. else if (document.webkitIsFullScreen !== undefined) {
  5515. _this.isFullscreen = document.webkitIsFullScreen;
  5516. }
  5517. else if (document.msIsFullScreen !== undefined) {
  5518. _this.isFullscreen = document.msIsFullScreen;
  5519. }
  5520. // Pointer lock
  5521. if (_this.isFullscreen && _this._pointerLockRequested) {
  5522. canvas.requestPointerLock = canvas.requestPointerLock ||
  5523. canvas.msRequestPointerLock ||
  5524. canvas.mozRequestPointerLock ||
  5525. canvas.webkitRequestPointerLock;
  5526. if (canvas.requestPointerLock) {
  5527. canvas.requestPointerLock();
  5528. }
  5529. }
  5530. };
  5531. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5532. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5533. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5534. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5535. // Pointer lock
  5536. this._onPointerLockChange = function () {
  5537. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5538. document.webkitPointerLockElement === canvas ||
  5539. document.msPointerLockElement === canvas ||
  5540. document.pointerLockElement === canvas);
  5541. };
  5542. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5543. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5544. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5545. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5546. if (!Engine.audioEngine) {
  5547. Engine.audioEngine = new BABYLON.AudioEngine();
  5548. }
  5549. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5550. }
  5551. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5552. get: function () {
  5553. return Engine._ALPHA_DISABLE;
  5554. },
  5555. enumerable: true,
  5556. configurable: true
  5557. });
  5558. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5559. get: function () {
  5560. return Engine._ALPHA_ONEONE;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. Object.defineProperty(Engine, "ALPHA_ADD", {
  5566. get: function () {
  5567. return Engine._ALPHA_ADD;
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5573. get: function () {
  5574. return Engine._ALPHA_COMBINE;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5580. get: function () {
  5581. return Engine._ALPHA_SUBTRACT;
  5582. },
  5583. enumerable: true,
  5584. configurable: true
  5585. });
  5586. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5587. get: function () {
  5588. return Engine._ALPHA_MULTIPLY;
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5594. get: function () {
  5595. return Engine._ALPHA_MAXIMIZED;
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5601. get: function () {
  5602. return Engine._DELAYLOADSTATE_NONE;
  5603. },
  5604. enumerable: true,
  5605. configurable: true
  5606. });
  5607. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5608. get: function () {
  5609. return Engine._DELAYLOADSTATE_LOADED;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5615. get: function () {
  5616. return Engine._DELAYLOADSTATE_LOADING;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5622. get: function () {
  5623. return Engine._DELAYLOADSTATE_NOTLOADED;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5629. get: function () {
  5630. return Engine._TEXTUREFORMAT_ALPHA;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5636. get: function () {
  5637. return Engine._TEXTUREFORMAT_LUMINANCE;
  5638. },
  5639. enumerable: true,
  5640. configurable: true
  5641. });
  5642. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5643. get: function () {
  5644. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5650. get: function () {
  5651. return Engine._TEXTUREFORMAT_RGB;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5657. get: function () {
  5658. return Engine._TEXTUREFORMAT_RGBA;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5664. get: function () {
  5665. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5671. get: function () {
  5672. return Engine._TEXTURETYPE_FLOAT;
  5673. },
  5674. enumerable: true,
  5675. configurable: true
  5676. });
  5677. Object.defineProperty(Engine, "Version", {
  5678. get: function () {
  5679. return "2.2.0-beta";
  5680. },
  5681. enumerable: true,
  5682. configurable: true
  5683. });
  5684. Engine.prototype._prepareWorkingCanvas = function () {
  5685. if (this._workingCanvas) {
  5686. return;
  5687. }
  5688. this._workingCanvas = document.createElement("canvas");
  5689. this._workingContext = this._workingCanvas.getContext("2d");
  5690. };
  5691. Engine.prototype.getGlInfo = function () {
  5692. return {
  5693. vendor: this._glVendor,
  5694. renderer: this._glRenderer,
  5695. version: this._glVersion
  5696. };
  5697. };
  5698. Engine.prototype.getAspectRatio = function (camera) {
  5699. var viewport = camera.viewport;
  5700. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5701. };
  5702. Engine.prototype.getRenderWidth = function () {
  5703. if (this._currentRenderTarget) {
  5704. return this._currentRenderTarget._width;
  5705. }
  5706. return this._renderingCanvas.width;
  5707. };
  5708. Engine.prototype.getRenderHeight = function () {
  5709. if (this._currentRenderTarget) {
  5710. return this._currentRenderTarget._height;
  5711. }
  5712. return this._renderingCanvas.height;
  5713. };
  5714. Engine.prototype.getRenderingCanvas = function () {
  5715. return this._renderingCanvas;
  5716. };
  5717. Engine.prototype.getRenderingCanvasClientRect = function () {
  5718. return this._renderingCanvas.getBoundingClientRect();
  5719. };
  5720. Engine.prototype.setHardwareScalingLevel = function (level) {
  5721. this._hardwareScalingLevel = level;
  5722. this.resize();
  5723. };
  5724. Engine.prototype.getHardwareScalingLevel = function () {
  5725. return this._hardwareScalingLevel;
  5726. };
  5727. Engine.prototype.getLoadedTexturesCache = function () {
  5728. return this._loadedTexturesCache;
  5729. };
  5730. Engine.prototype.getCaps = function () {
  5731. return this._caps;
  5732. };
  5733. Object.defineProperty(Engine.prototype, "drawCalls", {
  5734. get: function () {
  5735. return this._drawCalls;
  5736. },
  5737. enumerable: true,
  5738. configurable: true
  5739. });
  5740. // Methods
  5741. Engine.prototype.resetDrawCalls = function () {
  5742. this._drawCalls = 0;
  5743. };
  5744. Engine.prototype.setDepthFunctionToGreater = function () {
  5745. this._depthCullingState.depthFunc = this._gl.GREATER;
  5746. };
  5747. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5748. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5749. };
  5750. Engine.prototype.setDepthFunctionToLess = function () {
  5751. this._depthCullingState.depthFunc = this._gl.LESS;
  5752. };
  5753. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5754. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5755. };
  5756. /**
  5757. * stop executing a render loop function and remove it from the execution array
  5758. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5759. */
  5760. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5761. if (!renderFunction) {
  5762. this._activeRenderLoops = [];
  5763. return;
  5764. }
  5765. var index = this._activeRenderLoops.indexOf(renderFunction);
  5766. if (index >= 0) {
  5767. this._activeRenderLoops.splice(index, 1);
  5768. }
  5769. };
  5770. Engine.prototype._renderLoop = function () {
  5771. var _this = this;
  5772. var shouldRender = true;
  5773. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5774. shouldRender = false;
  5775. }
  5776. if (shouldRender) {
  5777. // Start new frame
  5778. this.beginFrame();
  5779. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5780. var renderFunction = this._activeRenderLoops[index];
  5781. renderFunction();
  5782. }
  5783. // Present
  5784. this.endFrame();
  5785. }
  5786. if (this._activeRenderLoops.length > 0) {
  5787. // Register new frame
  5788. BABYLON.Tools.QueueNewFrame(function () {
  5789. _this._renderLoop();
  5790. });
  5791. }
  5792. else {
  5793. this._renderingQueueLaunched = false;
  5794. }
  5795. };
  5796. /**
  5797. * Register and execute a render loop. The engine can have more than one render function.
  5798. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5799. * @example
  5800. * engine.runRenderLoop(function () {
  5801. * scene.render()
  5802. * })
  5803. */
  5804. Engine.prototype.runRenderLoop = function (renderFunction) {
  5805. var _this = this;
  5806. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5807. return;
  5808. }
  5809. this._activeRenderLoops.push(renderFunction);
  5810. if (!this._renderingQueueLaunched) {
  5811. this._renderingQueueLaunched = true;
  5812. BABYLON.Tools.QueueNewFrame(function () {
  5813. _this._renderLoop();
  5814. });
  5815. }
  5816. };
  5817. /**
  5818. * Toggle full screen mode.
  5819. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5820. */
  5821. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5822. if (this.isFullscreen) {
  5823. BABYLON.Tools.ExitFullscreen();
  5824. }
  5825. else {
  5826. this._pointerLockRequested = requestPointerLock;
  5827. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5828. }
  5829. };
  5830. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5831. this.applyStates();
  5832. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5833. if (this._depthCullingState.depthMask) {
  5834. this._gl.clearDepth(1.0);
  5835. }
  5836. var mode = 0;
  5837. if (backBuffer)
  5838. mode |= this._gl.COLOR_BUFFER_BIT;
  5839. if (depthStencil && this._depthCullingState.depthMask)
  5840. mode |= this._gl.DEPTH_BUFFER_BIT;
  5841. this._gl.clear(mode);
  5842. };
  5843. /**
  5844. * Set the WebGL's viewport
  5845. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5846. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5847. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5848. */
  5849. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5850. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5851. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5852. var x = viewport.x || 0;
  5853. var y = viewport.y || 0;
  5854. this._cachedViewport = viewport;
  5855. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5856. };
  5857. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5858. this._cachedViewport = null;
  5859. this._gl.viewport(x, y, width, height);
  5860. };
  5861. Engine.prototype.beginFrame = function () {
  5862. this._measureFps();
  5863. };
  5864. Engine.prototype.endFrame = function () {
  5865. //this.flushFramebuffer();
  5866. };
  5867. /**
  5868. * resize the view according to the canvas' size.
  5869. * @example
  5870. * window.addEventListener("resize", function () {
  5871. * engine.resize();
  5872. * });
  5873. */
  5874. Engine.prototype.resize = function () {
  5875. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5876. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5877. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5878. };
  5879. /**
  5880. * force a specific size of the canvas
  5881. * @param {number} width - the new canvas' width
  5882. * @param {number} height - the new canvas' height
  5883. */
  5884. Engine.prototype.setSize = function (width, height) {
  5885. this._renderingCanvas.width = width;
  5886. this._renderingCanvas.height = height;
  5887. for (var index = 0; index < this.scenes.length; index++) {
  5888. var scene = this.scenes[index];
  5889. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5890. var cam = scene.cameras[camIndex];
  5891. cam._currentRenderId = 0;
  5892. }
  5893. }
  5894. };
  5895. Engine.prototype.bindFramebuffer = function (texture) {
  5896. this._currentRenderTarget = texture;
  5897. var gl = this._gl;
  5898. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5899. this._gl.viewport(0, 0, texture._width, texture._height);
  5900. this.wipeCaches();
  5901. };
  5902. Engine.prototype.unBindFramebuffer = function (texture) {
  5903. this._currentRenderTarget = null;
  5904. if (texture.generateMipMaps) {
  5905. var gl = this._gl;
  5906. gl.bindTexture(gl.TEXTURE_2D, texture);
  5907. gl.generateMipmap(gl.TEXTURE_2D);
  5908. gl.bindTexture(gl.TEXTURE_2D, null);
  5909. }
  5910. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5911. };
  5912. Engine.prototype.flushFramebuffer = function () {
  5913. this._gl.flush();
  5914. };
  5915. Engine.prototype.restoreDefaultFramebuffer = function () {
  5916. this._currentRenderTarget = null;
  5917. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5918. this.setViewport(this._cachedViewport);
  5919. this.wipeCaches();
  5920. };
  5921. // VBOs
  5922. Engine.prototype._resetVertexBufferBinding = function () {
  5923. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5924. this._cachedVertexBuffers = null;
  5925. };
  5926. Engine.prototype.createVertexBuffer = function (vertices) {
  5927. var vbo = this._gl.createBuffer();
  5928. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5929. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5930. this._resetVertexBufferBinding();
  5931. vbo.references = 1;
  5932. return vbo;
  5933. };
  5934. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5935. var vbo = this._gl.createBuffer();
  5936. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5937. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5938. this._resetVertexBufferBinding();
  5939. vbo.references = 1;
  5940. return vbo;
  5941. };
  5942. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5943. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5944. if (offset === undefined) {
  5945. offset = 0;
  5946. }
  5947. if (vertices instanceof Float32Array) {
  5948. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5949. }
  5950. else {
  5951. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5952. }
  5953. this._resetVertexBufferBinding();
  5954. };
  5955. Engine.prototype._resetIndexBufferBinding = function () {
  5956. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5957. this._cachedIndexBuffer = null;
  5958. };
  5959. Engine.prototype.createIndexBuffer = function (indices) {
  5960. var vbo = this._gl.createBuffer();
  5961. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5962. // Check for 32 bits indices
  5963. var arrayBuffer;
  5964. var need32Bits = false;
  5965. if (this._caps.uintIndices) {
  5966. for (var index = 0; index < indices.length; index++) {
  5967. if (indices[index] > 65535) {
  5968. need32Bits = true;
  5969. break;
  5970. }
  5971. }
  5972. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5973. }
  5974. else {
  5975. arrayBuffer = new Uint16Array(indices);
  5976. }
  5977. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5978. this._resetIndexBufferBinding();
  5979. vbo.references = 1;
  5980. vbo.is32Bits = need32Bits;
  5981. return vbo;
  5982. };
  5983. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5984. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5985. this._cachedVertexBuffers = vertexBuffer;
  5986. this._cachedEffectForVertexBuffers = effect;
  5987. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5988. var offset = 0;
  5989. for (var index = 0; index < vertexDeclaration.length; index++) {
  5990. var order = effect.getAttributeLocation(index);
  5991. if (order >= 0) {
  5992. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5993. }
  5994. offset += vertexDeclaration[index] * 4;
  5995. }
  5996. }
  5997. if (this._cachedIndexBuffer !== indexBuffer) {
  5998. this._cachedIndexBuffer = indexBuffer;
  5999. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6000. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6001. }
  6002. };
  6003. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6004. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6005. this._cachedVertexBuffers = vertexBuffers;
  6006. this._cachedEffectForVertexBuffers = effect;
  6007. var attributes = effect.getAttributesNames();
  6008. for (var index = 0; index < attributes.length; index++) {
  6009. var order = effect.getAttributeLocation(index);
  6010. if (order >= 0) {
  6011. var vertexBuffer = vertexBuffers[attributes[index]];
  6012. if (!vertexBuffer) {
  6013. continue;
  6014. }
  6015. var stride = vertexBuffer.getStrideSize();
  6016. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6017. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6018. }
  6019. }
  6020. }
  6021. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6022. this._cachedIndexBuffer = indexBuffer;
  6023. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6024. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6025. }
  6026. };
  6027. Engine.prototype._releaseBuffer = function (buffer) {
  6028. buffer.references--;
  6029. if (buffer.references === 0) {
  6030. this._gl.deleteBuffer(buffer);
  6031. return true;
  6032. }
  6033. return false;
  6034. };
  6035. Engine.prototype.createInstancesBuffer = function (capacity) {
  6036. var buffer = this._gl.createBuffer();
  6037. buffer.capacity = capacity;
  6038. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6039. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6040. return buffer;
  6041. };
  6042. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6043. this._gl.deleteBuffer(buffer);
  6044. };
  6045. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6046. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6047. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6048. for (var index = 0; index < 4; index++) {
  6049. var offsetLocation = offsetLocations[index];
  6050. this._gl.enableVertexAttribArray(offsetLocation);
  6051. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6052. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6053. }
  6054. };
  6055. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6056. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6057. for (var index = 0; index < 4; index++) {
  6058. var offsetLocation = offsetLocations[index];
  6059. this._gl.disableVertexAttribArray(offsetLocation);
  6060. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6061. }
  6062. };
  6063. Engine.prototype.applyStates = function () {
  6064. this._depthCullingState.apply(this._gl);
  6065. this._alphaState.apply(this._gl);
  6066. };
  6067. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6068. // Apply states
  6069. this.applyStates();
  6070. this._drawCalls++;
  6071. // Render
  6072. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6073. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6074. if (instancesCount) {
  6075. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6076. return;
  6077. }
  6078. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6079. };
  6080. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6081. // Apply states
  6082. this.applyStates();
  6083. this._drawCalls++;
  6084. if (instancesCount) {
  6085. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6086. return;
  6087. }
  6088. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6089. };
  6090. // Shaders
  6091. Engine.prototype._releaseEffect = function (effect) {
  6092. if (this._compiledEffects[effect._key]) {
  6093. delete this._compiledEffects[effect._key];
  6094. if (effect.getProgram()) {
  6095. this._gl.deleteProgram(effect.getProgram());
  6096. }
  6097. }
  6098. };
  6099. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6100. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6101. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6102. var name = vertex + "+" + fragment + "@" + defines;
  6103. if (this._compiledEffects[name]) {
  6104. return this._compiledEffects[name];
  6105. }
  6106. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6107. effect._key = name;
  6108. this._compiledEffects[name] = effect;
  6109. return effect;
  6110. };
  6111. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6112. if (uniformsNames === void 0) { uniformsNames = []; }
  6113. if (samplers === void 0) { samplers = []; }
  6114. if (defines === void 0) { defines = ""; }
  6115. return this.createEffect({
  6116. vertex: "particles",
  6117. fragmentElement: fragmentName
  6118. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6119. };
  6120. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6121. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6122. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6123. var shaderProgram = this._gl.createProgram();
  6124. this._gl.attachShader(shaderProgram, vertexShader);
  6125. this._gl.attachShader(shaderProgram, fragmentShader);
  6126. this._gl.linkProgram(shaderProgram);
  6127. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6128. if (!linked) {
  6129. var error = this._gl.getProgramInfoLog(shaderProgram);
  6130. if (error) {
  6131. throw new Error(error);
  6132. }
  6133. }
  6134. this._gl.deleteShader(vertexShader);
  6135. this._gl.deleteShader(fragmentShader);
  6136. return shaderProgram;
  6137. };
  6138. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6139. var results = [];
  6140. for (var index = 0; index < uniformsNames.length; index++) {
  6141. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6142. }
  6143. return results;
  6144. };
  6145. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6146. var results = [];
  6147. for (var index = 0; index < attributesNames.length; index++) {
  6148. try {
  6149. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6150. }
  6151. catch (e) {
  6152. results.push(-1);
  6153. }
  6154. }
  6155. return results;
  6156. };
  6157. Engine.prototype.enableEffect = function (effect) {
  6158. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6159. if (effect && effect.onBind) {
  6160. effect.onBind(effect);
  6161. }
  6162. return;
  6163. }
  6164. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6165. // Use program
  6166. this._gl.useProgram(effect.getProgram());
  6167. for (var i in this._vertexAttribArrays) {
  6168. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6169. continue;
  6170. }
  6171. this._vertexAttribArrays[i] = false;
  6172. this._gl.disableVertexAttribArray(i);
  6173. }
  6174. var attributesCount = effect.getAttributesCount();
  6175. for (var index = 0; index < attributesCount; index++) {
  6176. // Attributes
  6177. var order = effect.getAttributeLocation(index);
  6178. if (order >= 0) {
  6179. this._vertexAttribArrays[order] = true;
  6180. this._gl.enableVertexAttribArray(order);
  6181. }
  6182. }
  6183. this._currentEffect = effect;
  6184. if (effect.onBind) {
  6185. effect.onBind(effect);
  6186. }
  6187. };
  6188. Engine.prototype.setArray = function (uniform, array) {
  6189. if (!uniform)
  6190. return;
  6191. this._gl.uniform1fv(uniform, array);
  6192. };
  6193. Engine.prototype.setArray2 = function (uniform, array) {
  6194. if (!uniform || array.length % 2 !== 0)
  6195. return;
  6196. this._gl.uniform2fv(uniform, array);
  6197. };
  6198. Engine.prototype.setArray3 = function (uniform, array) {
  6199. if (!uniform || array.length % 3 !== 0)
  6200. return;
  6201. this._gl.uniform3fv(uniform, array);
  6202. };
  6203. Engine.prototype.setArray4 = function (uniform, array) {
  6204. if (!uniform || array.length % 4 !== 0)
  6205. return;
  6206. this._gl.uniform4fv(uniform, array);
  6207. };
  6208. Engine.prototype.setMatrices = function (uniform, matrices) {
  6209. if (!uniform)
  6210. return;
  6211. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6212. };
  6213. Engine.prototype.setMatrix = function (uniform, matrix) {
  6214. if (!uniform)
  6215. return;
  6216. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6217. };
  6218. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6219. if (!uniform)
  6220. return;
  6221. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6222. };
  6223. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6224. if (!uniform)
  6225. return;
  6226. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6227. };
  6228. Engine.prototype.setFloat = function (uniform, value) {
  6229. if (!uniform)
  6230. return;
  6231. this._gl.uniform1f(uniform, value);
  6232. };
  6233. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6234. if (!uniform)
  6235. return;
  6236. this._gl.uniform2f(uniform, x, y);
  6237. };
  6238. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6239. if (!uniform)
  6240. return;
  6241. this._gl.uniform3f(uniform, x, y, z);
  6242. };
  6243. Engine.prototype.setBool = function (uniform, bool) {
  6244. if (!uniform)
  6245. return;
  6246. this._gl.uniform1i(uniform, bool);
  6247. };
  6248. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6249. if (!uniform)
  6250. return;
  6251. this._gl.uniform4f(uniform, x, y, z, w);
  6252. };
  6253. Engine.prototype.setColor3 = function (uniform, color3) {
  6254. if (!uniform)
  6255. return;
  6256. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6257. };
  6258. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6259. if (!uniform)
  6260. return;
  6261. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6262. };
  6263. // States
  6264. Engine.prototype.setState = function (culling, zOffset, force) {
  6265. if (zOffset === void 0) { zOffset = 0; }
  6266. // Culling
  6267. if (this._depthCullingState.cull !== culling || force) {
  6268. if (culling) {
  6269. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6270. this._depthCullingState.cull = true;
  6271. }
  6272. else {
  6273. this._depthCullingState.cull = false;
  6274. }
  6275. }
  6276. // Z offset
  6277. this._depthCullingState.zOffset = zOffset;
  6278. };
  6279. Engine.prototype.setDepthBuffer = function (enable) {
  6280. this._depthCullingState.depthTest = enable;
  6281. };
  6282. Engine.prototype.getDepthWrite = function () {
  6283. return this._depthCullingState.depthMask;
  6284. };
  6285. Engine.prototype.setDepthWrite = function (enable) {
  6286. this._depthCullingState.depthMask = enable;
  6287. };
  6288. Engine.prototype.setColorWrite = function (enable) {
  6289. this._gl.colorMask(enable, enable, enable, enable);
  6290. };
  6291. Engine.prototype.setAlphaMode = function (mode) {
  6292. if (this._alphaMode == mode) {
  6293. return;
  6294. }
  6295. switch (mode) {
  6296. case Engine.ALPHA_DISABLE:
  6297. this.setDepthWrite(true);
  6298. this._alphaState.alphaBlend = false;
  6299. break;
  6300. case Engine.ALPHA_COMBINE:
  6301. this.setDepthWrite(false);
  6302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6303. this._alphaState.alphaBlend = true;
  6304. break;
  6305. case Engine.ALPHA_ONEONE:
  6306. this.setDepthWrite(false);
  6307. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6308. this._alphaState.alphaBlend = true;
  6309. break;
  6310. case Engine.ALPHA_ADD:
  6311. this.setDepthWrite(false);
  6312. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6313. this._alphaState.alphaBlend = true;
  6314. break;
  6315. case Engine.ALPHA_SUBTRACT:
  6316. this.setDepthWrite(false);
  6317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6318. this._alphaState.alphaBlend = true;
  6319. break;
  6320. case Engine.ALPHA_MULTIPLY:
  6321. this.setDepthWrite(false);
  6322. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6323. this._alphaState.alphaBlend = true;
  6324. break;
  6325. case Engine.ALPHA_MAXIMIZED:
  6326. this.setDepthWrite(false);
  6327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6328. this._alphaState.alphaBlend = true;
  6329. break;
  6330. }
  6331. this._alphaMode = mode;
  6332. };
  6333. Engine.prototype.getAlphaMode = function () {
  6334. return this._alphaMode;
  6335. };
  6336. Engine.prototype.setAlphaTesting = function (enable) {
  6337. this._alphaTest = enable;
  6338. };
  6339. Engine.prototype.getAlphaTesting = function () {
  6340. return this._alphaTest;
  6341. };
  6342. // Textures
  6343. Engine.prototype.wipeCaches = function () {
  6344. this._activeTexturesCache = [];
  6345. this._currentEffect = null;
  6346. this._depthCullingState.reset();
  6347. this._alphaState.reset();
  6348. this._cachedVertexBuffers = null;
  6349. this._cachedIndexBuffer = null;
  6350. this._cachedEffectForVertexBuffers = null;
  6351. };
  6352. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6353. var gl = this._gl;
  6354. gl.bindTexture(gl.TEXTURE_2D, texture);
  6355. var magFilter = gl.NEAREST;
  6356. var minFilter = gl.NEAREST;
  6357. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6358. magFilter = gl.LINEAR;
  6359. minFilter = gl.LINEAR;
  6360. }
  6361. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6362. magFilter = gl.LINEAR;
  6363. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6364. }
  6365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6367. gl.bindTexture(gl.TEXTURE_2D, null);
  6368. texture.samplingMode = samplingMode;
  6369. };
  6370. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6371. var _this = this;
  6372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6373. if (onLoad === void 0) { onLoad = null; }
  6374. if (onError === void 0) { onError = null; }
  6375. if (buffer === void 0) { buffer = null; }
  6376. var texture = this._gl.createTexture();
  6377. var extension;
  6378. var fromData = false;
  6379. if (url.substr(0, 5) === "data:") {
  6380. fromData = true;
  6381. }
  6382. if (!fromData)
  6383. extension = url.substr(url.length - 4, 4).toLowerCase();
  6384. else {
  6385. var oldUrl = url;
  6386. fromData = oldUrl.split(':');
  6387. url = oldUrl;
  6388. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6389. }
  6390. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6391. var isTGA = (extension === ".tga");
  6392. scene._addPendingData(texture);
  6393. texture.url = url;
  6394. texture.noMipmap = noMipmap;
  6395. texture.references = 1;
  6396. texture.samplingMode = samplingMode;
  6397. this._loadedTexturesCache.push(texture);
  6398. var onerror = function () {
  6399. scene._removePendingData(texture);
  6400. if (onError) {
  6401. onError();
  6402. }
  6403. };
  6404. if (isTGA) {
  6405. var callback = function (arrayBuffer) {
  6406. var data = new Uint8Array(arrayBuffer);
  6407. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6408. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6409. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6410. if (onLoad) {
  6411. onLoad();
  6412. }
  6413. }, samplingMode);
  6414. };
  6415. if (!(fromData instanceof Array))
  6416. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6417. callback(arrayBuffer);
  6418. }, onerror, scene.database, true);
  6419. else
  6420. callback(buffer);
  6421. }
  6422. else if (isDDS) {
  6423. callback = function (data) {
  6424. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6425. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6426. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6427. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6428. if (onLoad) {
  6429. onLoad();
  6430. }
  6431. }, samplingMode);
  6432. };
  6433. if (!(fromData instanceof Array))
  6434. BABYLON.Tools.LoadFile(url, function (data) {
  6435. callback(data);
  6436. }, onerror, scene.database, true);
  6437. else
  6438. callback(buffer);
  6439. }
  6440. else {
  6441. var onload = function (img) {
  6442. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6443. var isPot = (img.width === potWidth && img.height === potHeight);
  6444. if (!isPot) {
  6445. _this._prepareWorkingCanvas();
  6446. _this._workingCanvas.width = potWidth;
  6447. _this._workingCanvas.height = potHeight;
  6448. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6449. _this._workingContext.imageSmoothingEnabled = false;
  6450. _this._workingContext.mozImageSmoothingEnabled = false;
  6451. _this._workingContext.oImageSmoothingEnabled = false;
  6452. _this._workingContext.webkitImageSmoothingEnabled = false;
  6453. _this._workingContext.msImageSmoothingEnabled = false;
  6454. }
  6455. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6456. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6457. _this._workingContext.imageSmoothingEnabled = true;
  6458. _this._workingContext.mozImageSmoothingEnabled = true;
  6459. _this._workingContext.oImageSmoothingEnabled = true;
  6460. _this._workingContext.webkitImageSmoothingEnabled = true;
  6461. _this._workingContext.msImageSmoothingEnabled = true;
  6462. }
  6463. }
  6464. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6465. if (onLoad) {
  6466. onLoad();
  6467. }
  6468. }, samplingMode);
  6469. };
  6470. if (!(fromData instanceof Array))
  6471. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6472. else
  6473. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6474. }
  6475. return texture;
  6476. };
  6477. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6478. if (compression === void 0) { compression = null; }
  6479. var internalFormat = this._gl.RGBA;
  6480. switch (format) {
  6481. case Engine.TEXTUREFORMAT_ALPHA:
  6482. internalFormat = this._gl.ALPHA;
  6483. break;
  6484. case Engine.TEXTUREFORMAT_LUMINANCE:
  6485. internalFormat = this._gl.LUMINANCE;
  6486. break;
  6487. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6488. internalFormat = this._gl.LUMINANCE_ALPHA;
  6489. break;
  6490. case Engine.TEXTUREFORMAT_RGB:
  6491. internalFormat = this._gl.RGB;
  6492. break;
  6493. case Engine.TEXTUREFORMAT_RGBA:
  6494. internalFormat = this._gl.RGBA;
  6495. break;
  6496. }
  6497. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6498. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6499. if (compression) {
  6500. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6501. }
  6502. else {
  6503. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6504. }
  6505. if (texture.generateMipMaps) {
  6506. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6507. }
  6508. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6509. this._activeTexturesCache = [];
  6510. texture.isReady = true;
  6511. };
  6512. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6513. if (compression === void 0) { compression = null; }
  6514. var texture = this._gl.createTexture();
  6515. texture._baseWidth = width;
  6516. texture._baseHeight = height;
  6517. texture._width = width;
  6518. texture._height = height;
  6519. texture.references = 1;
  6520. this.updateRawTexture(texture, data, format, invertY, compression);
  6521. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6522. // Filters
  6523. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6524. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6525. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6526. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6527. texture.samplingMode = samplingMode;
  6528. this._loadedTexturesCache.push(texture);
  6529. return texture;
  6530. };
  6531. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6532. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6533. var texture = this._gl.createTexture();
  6534. texture._baseWidth = width;
  6535. texture._baseHeight = height;
  6536. if (forceExponantOfTwo) {
  6537. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6538. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6539. }
  6540. this._activeTexturesCache = [];
  6541. texture._width = width;
  6542. texture._height = height;
  6543. texture.isReady = false;
  6544. texture.generateMipMaps = generateMipMaps;
  6545. texture.references = 1;
  6546. texture.samplingMode = samplingMode;
  6547. this.updateTextureSamplingMode(samplingMode, texture);
  6548. this._loadedTexturesCache.push(texture);
  6549. return texture;
  6550. };
  6551. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6552. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6553. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6554. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6555. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6556. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6557. };
  6558. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6559. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6560. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6561. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6562. if (texture.generateMipMaps) {
  6563. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6564. }
  6565. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6566. this._activeTexturesCache = [];
  6567. texture.isReady = true;
  6568. };
  6569. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6570. if (texture._isDisabled) {
  6571. return;
  6572. }
  6573. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6574. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6575. try {
  6576. // Testing video texture support
  6577. if (this._videoTextureSupported === undefined) {
  6578. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6579. if (this._gl.getError() !== 0) {
  6580. this._videoTextureSupported = false;
  6581. }
  6582. else {
  6583. this._videoTextureSupported = true;
  6584. }
  6585. }
  6586. // Copy video through the current working canvas if video texture is not supported
  6587. if (!this._videoTextureSupported) {
  6588. if (!texture._workingCanvas) {
  6589. texture._workingCanvas = document.createElement("canvas");
  6590. texture._workingContext = texture._workingCanvas.getContext("2d");
  6591. texture._workingCanvas.width = texture._width;
  6592. texture._workingCanvas.height = texture._height;
  6593. }
  6594. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6595. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6596. }
  6597. else {
  6598. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6599. }
  6600. if (texture.generateMipMaps) {
  6601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6602. }
  6603. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6604. this._activeTexturesCache = [];
  6605. texture.isReady = true;
  6606. }
  6607. catch (ex) {
  6608. // Something unexpected
  6609. // Let's disable the texture
  6610. texture._isDisabled = true;
  6611. }
  6612. };
  6613. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6614. // old version had a "generateMipMaps" arg instead of options.
  6615. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6616. // in the same way, generateDepthBuffer is defaulted to true
  6617. var generateMipMaps = false;
  6618. var generateDepthBuffer = true;
  6619. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6620. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6621. if (options !== undefined) {
  6622. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6623. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6624. type = options.type === undefined ? type : options.type;
  6625. if (options.samplingMode !== undefined) {
  6626. samplingMode = options.samplingMode;
  6627. }
  6628. if (type === Engine.TEXTURETYPE_FLOAT) {
  6629. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6630. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6631. }
  6632. }
  6633. var gl = this._gl;
  6634. var texture = gl.createTexture();
  6635. gl.bindTexture(gl.TEXTURE_2D, texture);
  6636. var width = size.width || size;
  6637. var height = size.height || size;
  6638. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6639. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6640. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6641. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6642. }
  6643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6647. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6648. var depthBuffer;
  6649. // Create the depth buffer
  6650. if (generateDepthBuffer) {
  6651. depthBuffer = gl.createRenderbuffer();
  6652. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6653. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6654. }
  6655. // Create the framebuffer
  6656. var framebuffer = gl.createFramebuffer();
  6657. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6658. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6659. if (generateDepthBuffer) {
  6660. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6661. }
  6662. if (generateMipMaps) {
  6663. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6664. }
  6665. // Unbind
  6666. gl.bindTexture(gl.TEXTURE_2D, null);
  6667. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6668. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6669. texture._framebuffer = framebuffer;
  6670. if (generateDepthBuffer) {
  6671. texture._depthBuffer = depthBuffer;
  6672. }
  6673. texture._width = width;
  6674. texture._height = height;
  6675. texture.isReady = true;
  6676. texture.generateMipMaps = generateMipMaps;
  6677. texture.references = 1;
  6678. texture.samplingMode = samplingMode;
  6679. this._activeTexturesCache = [];
  6680. this._loadedTexturesCache.push(texture);
  6681. return texture;
  6682. };
  6683. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6684. var _this = this;
  6685. var gl = this._gl;
  6686. var texture = gl.createTexture();
  6687. texture.isCube = true;
  6688. texture.url = rootUrl;
  6689. texture.references = 1;
  6690. this._loadedTexturesCache.push(texture);
  6691. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6692. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6693. if (isDDS) {
  6694. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6695. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6696. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6697. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6698. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6699. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6700. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6701. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6702. }
  6703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6707. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6708. _this._activeTexturesCache = [];
  6709. texture._width = info.width;
  6710. texture._height = info.height;
  6711. texture.isReady = true;
  6712. }, null, null, true);
  6713. }
  6714. else {
  6715. cascadeLoad(rootUrl, scene, function (imgs) {
  6716. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6717. var height = width;
  6718. _this._prepareWorkingCanvas();
  6719. _this._workingCanvas.width = width;
  6720. _this._workingCanvas.height = height;
  6721. var faces = [
  6722. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6723. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6724. ];
  6725. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6726. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6727. for (var index = 0; index < faces.length; index++) {
  6728. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6729. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6730. }
  6731. if (!noMipmap) {
  6732. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6733. }
  6734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6738. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6739. _this._activeTexturesCache = [];
  6740. texture._width = width;
  6741. texture._height = height;
  6742. texture.isReady = true;
  6743. }, extensions);
  6744. }
  6745. return texture;
  6746. };
  6747. Engine.prototype._releaseTexture = function (texture) {
  6748. var gl = this._gl;
  6749. if (texture._framebuffer) {
  6750. gl.deleteFramebuffer(texture._framebuffer);
  6751. }
  6752. if (texture._depthBuffer) {
  6753. gl.deleteRenderbuffer(texture._depthBuffer);
  6754. }
  6755. gl.deleteTexture(texture);
  6756. // Unbind channels
  6757. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6758. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6759. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6760. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6761. this._activeTexturesCache[channel] = null;
  6762. }
  6763. var index = this._loadedTexturesCache.indexOf(texture);
  6764. if (index !== -1) {
  6765. this._loadedTexturesCache.splice(index, 1);
  6766. }
  6767. };
  6768. Engine.prototype.bindSamplers = function (effect) {
  6769. this._gl.useProgram(effect.getProgram());
  6770. var samplers = effect.getSamplers();
  6771. for (var index = 0; index < samplers.length; index++) {
  6772. var uniform = effect.getUniform(samplers[index]);
  6773. this._gl.uniform1i(uniform, index);
  6774. }
  6775. this._currentEffect = null;
  6776. };
  6777. Engine.prototype._bindTexture = function (channel, texture) {
  6778. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6779. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6780. this._activeTexturesCache[channel] = null;
  6781. };
  6782. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6783. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6784. };
  6785. Engine.prototype.setTexture = function (channel, texture) {
  6786. if (channel < 0) {
  6787. return;
  6788. }
  6789. // Not ready?
  6790. if (!texture || !texture.isReady()) {
  6791. if (this._activeTexturesCache[channel] != null) {
  6792. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6793. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6794. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6795. this._activeTexturesCache[channel] = null;
  6796. }
  6797. return;
  6798. }
  6799. // Video
  6800. if (texture instanceof BABYLON.VideoTexture) {
  6801. if (texture.update()) {
  6802. this._activeTexturesCache[channel] = null;
  6803. }
  6804. }
  6805. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6806. texture.delayLoad();
  6807. return;
  6808. }
  6809. if (this._activeTexturesCache[channel] === texture) {
  6810. return;
  6811. }
  6812. this._activeTexturesCache[channel] = texture;
  6813. var internalTexture = texture.getInternalTexture();
  6814. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6815. if (internalTexture.isCube) {
  6816. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6817. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6818. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6819. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6820. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6821. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6822. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6823. }
  6824. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6825. }
  6826. else {
  6827. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6828. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6829. internalTexture._cachedWrapU = texture.wrapU;
  6830. switch (texture.wrapU) {
  6831. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6832. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6833. break;
  6834. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6835. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6836. break;
  6837. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6838. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6839. break;
  6840. }
  6841. }
  6842. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6843. internalTexture._cachedWrapV = texture.wrapV;
  6844. switch (texture.wrapV) {
  6845. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6846. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6847. break;
  6848. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6849. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6850. break;
  6851. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6852. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6853. break;
  6854. }
  6855. }
  6856. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6857. }
  6858. };
  6859. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6860. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6861. var value = texture.anisotropicFilteringLevel;
  6862. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6863. value = 1;
  6864. }
  6865. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6866. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6867. texture._cachedAnisotropicFilteringLevel = value;
  6868. }
  6869. };
  6870. Engine.prototype.readPixels = function (x, y, width, height) {
  6871. var data = new Uint8Array(height * width * 4);
  6872. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6873. return data;
  6874. };
  6875. // Dispose
  6876. Engine.prototype.dispose = function () {
  6877. this.hideLoadingUI();
  6878. this.stopRenderLoop();
  6879. // Release scenes
  6880. while (this.scenes.length) {
  6881. this.scenes[0].dispose();
  6882. }
  6883. // Release audio engine
  6884. Engine.audioEngine.dispose();
  6885. // Release effects
  6886. for (var name in this._compiledEffects) {
  6887. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6888. }
  6889. // Unbind
  6890. for (var i in this._vertexAttribArrays) {
  6891. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6892. continue;
  6893. }
  6894. this._gl.disableVertexAttribArray(i);
  6895. }
  6896. this._gl = null;
  6897. // Events
  6898. window.removeEventListener("blur", this._onBlur);
  6899. window.removeEventListener("focus", this._onFocus);
  6900. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6901. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6902. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6903. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6904. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6905. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6906. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6907. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6908. };
  6909. // Loading screen
  6910. Engine.prototype.displayLoadingUI = function () {
  6911. var _this = this;
  6912. this._loadingDiv = document.createElement("div");
  6913. this._loadingDiv.style.opacity = "0";
  6914. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6915. // Loading text
  6916. this._loadingTextDiv = document.createElement("div");
  6917. this._loadingTextDiv.style.position = "absolute";
  6918. this._loadingTextDiv.style.left = "0";
  6919. this._loadingTextDiv.style.top = "50%";
  6920. this._loadingTextDiv.style.marginTop = "80px";
  6921. this._loadingTextDiv.style.width = "100%";
  6922. this._loadingTextDiv.style.height = "20px";
  6923. this._loadingTextDiv.style.fontFamily = "Arial";
  6924. this._loadingTextDiv.style.fontSize = "14px";
  6925. this._loadingTextDiv.style.color = "white";
  6926. this._loadingTextDiv.style.textAlign = "center";
  6927. this._loadingTextDiv.innerHTML = "Loading";
  6928. this._loadingDiv.appendChild(this._loadingTextDiv);
  6929. // Loading img
  6930. var imgBack = new Image();
  6931. 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==";
  6932. imgBack.style.position = "absolute";
  6933. imgBack.style.left = "50%";
  6934. imgBack.style.top = "50%";
  6935. imgBack.style.marginLeft = "-50px";
  6936. imgBack.style.marginTop = "-50px";
  6937. imgBack.style.transition = "transform 1.0s ease";
  6938. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6939. var deg = 360;
  6940. var onTransitionEnd = function () {
  6941. deg += 360;
  6942. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6943. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6944. };
  6945. imgBack.addEventListener("transitionend", onTransitionEnd);
  6946. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6947. this._loadingDiv.appendChild(imgBack);
  6948. // front image
  6949. var imgFront = new Image();
  6950. 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=";
  6951. imgFront.style.position = "absolute";
  6952. imgFront.style.left = "50%";
  6953. imgFront.style.top = "50%";
  6954. imgFront.style.marginLeft = "-50px";
  6955. imgFront.style.marginTop = "-50px";
  6956. this._loadingDiv.appendChild(imgFront);
  6957. // Resize
  6958. this._resizeLoadingUI = function () {
  6959. var canvasRect = _this.getRenderingCanvasClientRect();
  6960. _this._loadingDiv.style.position = "absolute";
  6961. _this._loadingDiv.style.left = canvasRect.left + "px";
  6962. _this._loadingDiv.style.top = canvasRect.top + "px";
  6963. _this._loadingDiv.style.width = canvasRect.width + "px";
  6964. _this._loadingDiv.style.height = canvasRect.height + "px";
  6965. };
  6966. this._resizeLoadingUI();
  6967. window.addEventListener("resize", this._resizeLoadingUI);
  6968. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6969. document.body.appendChild(this._loadingDiv);
  6970. setTimeout(function () {
  6971. _this._loadingDiv.style.opacity = "1";
  6972. imgBack.style.transform = "rotateZ(360deg)";
  6973. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6974. }, 0);
  6975. };
  6976. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6977. set: function (text) {
  6978. if (!this._loadingDiv) {
  6979. return;
  6980. }
  6981. this._loadingTextDiv.innerHTML = text;
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6987. get: function () {
  6988. return this._loadingDivBackgroundColor;
  6989. },
  6990. set: function (color) {
  6991. this._loadingDivBackgroundColor = color;
  6992. if (!this._loadingDiv) {
  6993. return;
  6994. }
  6995. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6996. },
  6997. enumerable: true,
  6998. configurable: true
  6999. });
  7000. Engine.prototype.hideLoadingUI = function () {
  7001. var _this = this;
  7002. if (!this._loadingDiv) {
  7003. return;
  7004. }
  7005. var onTransitionEnd = function () {
  7006. if (!_this._loadingDiv) {
  7007. return;
  7008. }
  7009. document.body.removeChild(_this._loadingDiv);
  7010. window.removeEventListener("resize", _this._resizeLoadingUI);
  7011. _this._loadingDiv = null;
  7012. };
  7013. this._loadingDiv.style.opacity = "0";
  7014. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  7015. };
  7016. // FPS
  7017. Engine.prototype.getFps = function () {
  7018. return this.fps;
  7019. };
  7020. Engine.prototype.getDeltaTime = function () {
  7021. return this.deltaTime;
  7022. };
  7023. Engine.prototype._measureFps = function () {
  7024. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7025. var length = this.previousFramesDuration.length;
  7026. if (length >= 2) {
  7027. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7028. }
  7029. if (length >= this.fpsRange) {
  7030. if (length > this.fpsRange) {
  7031. this.previousFramesDuration.splice(0, 1);
  7032. length = this.previousFramesDuration.length;
  7033. }
  7034. var sum = 0;
  7035. for (var id = 0; id < length - 1; id++) {
  7036. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7037. }
  7038. this.fps = 1000.0 / (sum / (length - 1));
  7039. }
  7040. };
  7041. // Statics
  7042. Engine.isSupported = function () {
  7043. try {
  7044. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7045. if (navigator.isCocoonJS) {
  7046. return true;
  7047. }
  7048. var tempcanvas = document.createElement("canvas");
  7049. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7050. return gl != null && !!window.WebGLRenderingContext;
  7051. }
  7052. catch (e) {
  7053. return false;
  7054. }
  7055. };
  7056. // Const statics
  7057. Engine._ALPHA_DISABLE = 0;
  7058. Engine._ALPHA_ADD = 1;
  7059. Engine._ALPHA_COMBINE = 2;
  7060. Engine._ALPHA_SUBTRACT = 3;
  7061. Engine._ALPHA_MULTIPLY = 4;
  7062. Engine._ALPHA_MAXIMIZED = 5;
  7063. Engine._ALPHA_ONEONE = 6;
  7064. Engine._DELAYLOADSTATE_NONE = 0;
  7065. Engine._DELAYLOADSTATE_LOADED = 1;
  7066. Engine._DELAYLOADSTATE_LOADING = 2;
  7067. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7068. Engine._TEXTUREFORMAT_ALPHA = 0;
  7069. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7070. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7071. Engine._TEXTUREFORMAT_RGB = 4;
  7072. Engine._TEXTUREFORMAT_RGBA = 5;
  7073. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7074. Engine._TEXTURETYPE_FLOAT = 1;
  7075. // Updatable statics so stick with vars here
  7076. Engine.Epsilon = 0.001;
  7077. Engine.CollisionsEpsilon = 0.001;
  7078. Engine.CodeRepository = "src/";
  7079. Engine.ShadersRepository = "src/Shaders/";
  7080. return Engine;
  7081. })();
  7082. BABYLON.Engine = Engine;
  7083. })(BABYLON || (BABYLON = {}));
  7084. var BABYLON;
  7085. (function (BABYLON) {
  7086. /**
  7087. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7088. */
  7089. var Node = (function () {
  7090. /**
  7091. * @constructor
  7092. * @param {string} name - the name and id to be given to this node
  7093. * @param {BABYLON.Scene} the scene this node will be added to
  7094. */
  7095. function Node(name, scene) {
  7096. this.state = "";
  7097. this.animations = new Array();
  7098. this._childrenFlag = -1;
  7099. this._isEnabled = true;
  7100. this._isReady = true;
  7101. this._currentRenderId = -1;
  7102. this._parentRenderId = -1;
  7103. this.name = name;
  7104. this.id = name;
  7105. this._scene = scene;
  7106. this._initCache();
  7107. }
  7108. Node.prototype.getScene = function () {
  7109. return this._scene;
  7110. };
  7111. Node.prototype.getEngine = function () {
  7112. return this._scene.getEngine();
  7113. };
  7114. // override it in derived class
  7115. Node.prototype.getWorldMatrix = function () {
  7116. return BABYLON.Matrix.Identity();
  7117. };
  7118. // override it in derived class if you add new variables to the cache
  7119. // and call the parent class method
  7120. Node.prototype._initCache = function () {
  7121. this._cache = {};
  7122. this._cache.parent = undefined;
  7123. };
  7124. Node.prototype.updateCache = function (force) {
  7125. if (!force && this.isSynchronized())
  7126. return;
  7127. this._cache.parent = this.parent;
  7128. this._updateCache();
  7129. };
  7130. // override it in derived class if you add new variables to the cache
  7131. // and call the parent class method if !ignoreParentClass
  7132. Node.prototype._updateCache = function (ignoreParentClass) {
  7133. };
  7134. // override it in derived class if you add new variables to the cache
  7135. Node.prototype._isSynchronized = function () {
  7136. return true;
  7137. };
  7138. Node.prototype._markSyncedWithParent = function () {
  7139. this._parentRenderId = this.parent._currentRenderId;
  7140. };
  7141. Node.prototype.isSynchronizedWithParent = function () {
  7142. if (!this.parent) {
  7143. return true;
  7144. }
  7145. if (this._parentRenderId !== this.parent._currentRenderId) {
  7146. return false;
  7147. }
  7148. return this.parent.isSynchronized();
  7149. };
  7150. Node.prototype.isSynchronized = function (updateCache) {
  7151. var check = this.hasNewParent();
  7152. check = check || !this.isSynchronizedWithParent();
  7153. check = check || !this._isSynchronized();
  7154. if (updateCache)
  7155. this.updateCache(true);
  7156. return !check;
  7157. };
  7158. Node.prototype.hasNewParent = function (update) {
  7159. if (this._cache.parent === this.parent)
  7160. return false;
  7161. if (update)
  7162. this._cache.parent = this.parent;
  7163. return true;
  7164. };
  7165. /**
  7166. * Is this node ready to be used/rendered
  7167. * @return {boolean} is it ready
  7168. */
  7169. Node.prototype.isReady = function () {
  7170. return this._isReady;
  7171. };
  7172. /**
  7173. * Is this node enabled.
  7174. * If the node has a parent and is enabled, the parent will be inspected as well.
  7175. * @return {boolean} whether this node (and its parent) is enabled.
  7176. * @see setEnabled
  7177. */
  7178. Node.prototype.isEnabled = function () {
  7179. if (!this._isEnabled) {
  7180. return false;
  7181. }
  7182. if (this.parent) {
  7183. return this.parent.isEnabled();
  7184. }
  7185. return true;
  7186. };
  7187. /**
  7188. * Set the enabled state of this node.
  7189. * @param {boolean} value - the new enabled state
  7190. * @see isEnabled
  7191. */
  7192. Node.prototype.setEnabled = function (value) {
  7193. this._isEnabled = value;
  7194. };
  7195. /**
  7196. * Is this node a descendant of the given node.
  7197. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7198. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7199. * @see parent
  7200. */
  7201. Node.prototype.isDescendantOf = function (ancestor) {
  7202. if (this.parent) {
  7203. if (this.parent === ancestor) {
  7204. return true;
  7205. }
  7206. return this.parent.isDescendantOf(ancestor);
  7207. }
  7208. return false;
  7209. };
  7210. Node.prototype._getDescendants = function (list, results) {
  7211. for (var index = 0; index < list.length; index++) {
  7212. var item = list[index];
  7213. if (item.isDescendantOf(this)) {
  7214. results.push(item);
  7215. }
  7216. }
  7217. };
  7218. /**
  7219. * Will return all nodes that have this node as parent.
  7220. * @return {BABYLON.Node[]} all children nodes of all types.
  7221. */
  7222. Node.prototype.getDescendants = function () {
  7223. var results = [];
  7224. this._getDescendants(this._scene.meshes, results);
  7225. this._getDescendants(this._scene.lights, results);
  7226. this._getDescendants(this._scene.cameras, results);
  7227. return results;
  7228. };
  7229. Node.prototype._setReady = function (state) {
  7230. if (state == this._isReady) {
  7231. return;
  7232. }
  7233. if (!state) {
  7234. this._isReady = false;
  7235. return;
  7236. }
  7237. this._isReady = true;
  7238. if (this.onReady) {
  7239. this.onReady(this);
  7240. }
  7241. };
  7242. return Node;
  7243. })();
  7244. BABYLON.Node = Node;
  7245. })(BABYLON || (BABYLON = {}));
  7246. var BABYLON;
  7247. (function (BABYLON) {
  7248. var FilesInput = (function () {
  7249. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7250. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7251. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7252. this._engine = p_engine;
  7253. this._canvas = p_canvas;
  7254. this._currentScene = p_scene;
  7255. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7256. this._progressCallback = p_progressCallback;
  7257. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7258. this._textureLoadingCallback = p_textureLoadingCallback;
  7259. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7260. }
  7261. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7262. var _this = this;
  7263. if (p_elementToMonitor) {
  7264. this._elementToMonitor = p_elementToMonitor;
  7265. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7266. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7267. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7268. }
  7269. };
  7270. FilesInput.prototype.renderFunction = function () {
  7271. if (this._additionnalRenderLoopLogicCallback) {
  7272. this._additionnalRenderLoopLogicCallback();
  7273. }
  7274. if (this._currentScene) {
  7275. if (this._textureLoadingCallback) {
  7276. var remaining = this._currentScene.getWaitingItemsCount();
  7277. if (remaining > 0) {
  7278. this._textureLoadingCallback(remaining);
  7279. }
  7280. }
  7281. this._currentScene.render();
  7282. }
  7283. };
  7284. FilesInput.prototype.drag = function (e) {
  7285. e.stopPropagation();
  7286. e.preventDefault();
  7287. };
  7288. FilesInput.prototype.drop = function (eventDrop) {
  7289. eventDrop.stopPropagation();
  7290. eventDrop.preventDefault();
  7291. this.loadFiles(eventDrop);
  7292. };
  7293. FilesInput.prototype.loadFiles = function (event) {
  7294. if (this._startingProcessingFilesCallback)
  7295. this._startingProcessingFilesCallback();
  7296. // Handling data transfer via drag'n'drop
  7297. if (event && event.dataTransfer && event.dataTransfer.files) {
  7298. this._filesToLoad = event.dataTransfer.files;
  7299. }
  7300. // Handling files from input files
  7301. if (event && event.target && event.target.files) {
  7302. this._filesToLoad = event.target.files;
  7303. }
  7304. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7305. for (var i = 0; i < this._filesToLoad.length; i++) {
  7306. switch (this._filesToLoad[i].type) {
  7307. case "image/jpeg":
  7308. case "image/png":
  7309. case "image/bmp":
  7310. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7311. break;
  7312. case "image/targa":
  7313. case "image/vnd.ms-dds":
  7314. case "audio/wav":
  7315. case "audio/x-wav":
  7316. case "audio/mp3":
  7317. case "audio/mpeg":
  7318. case "audio/mpeg3":
  7319. case "audio/x-mpeg-3":
  7320. case "audio/ogg":
  7321. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7322. break;
  7323. default:
  7324. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7325. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7326. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7327. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7328. this._sceneFileToLoad = this._filesToLoad[i];
  7329. }
  7330. break;
  7331. }
  7332. }
  7333. this.reload();
  7334. }
  7335. };
  7336. FilesInput.prototype.reload = function () {
  7337. var _this = this;
  7338. var that = this;
  7339. // If a ".babylon" file has been provided
  7340. if (this._sceneFileToLoad) {
  7341. if (this._currentScene) {
  7342. if (BABYLON.Tools.errorsCount > 0) {
  7343. BABYLON.Tools.ClearLogCache();
  7344. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7345. }
  7346. this._engine.stopRenderLoop();
  7347. this._currentScene.dispose();
  7348. }
  7349. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7350. that._currentScene = newScene;
  7351. // Wait for textures and shaders to be ready
  7352. that._currentScene.executeWhenReady(function () {
  7353. // Attach camera to canvas inputs
  7354. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7355. that._currentScene.createDefaultCameraOrLight();
  7356. }
  7357. that._currentScene.activeCamera.attachControl(that._canvas);
  7358. if (that._sceneLoadedCallback) {
  7359. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7360. }
  7361. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7362. });
  7363. }, function (progress) {
  7364. if (_this._progressCallback) {
  7365. _this._progressCallback(progress);
  7366. }
  7367. });
  7368. }
  7369. else {
  7370. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7371. }
  7372. };
  7373. FilesInput.FilesTextures = new Array();
  7374. FilesInput.FilesToLoad = new Array();
  7375. return FilesInput;
  7376. })();
  7377. BABYLON.FilesInput = FilesInput;
  7378. })(BABYLON || (BABYLON = {}));
  7379. var BABYLON;
  7380. (function (BABYLON) {
  7381. var IntersectionInfo = (function () {
  7382. function IntersectionInfo(bu, bv, distance) {
  7383. this.bu = bu;
  7384. this.bv = bv;
  7385. this.distance = distance;
  7386. this.faceId = 0;
  7387. this.subMeshId = 0;
  7388. }
  7389. return IntersectionInfo;
  7390. })();
  7391. BABYLON.IntersectionInfo = IntersectionInfo;
  7392. var PickingInfo = (function () {
  7393. function PickingInfo() {
  7394. this.hit = false;
  7395. this.distance = 0;
  7396. this.pickedPoint = null;
  7397. this.pickedMesh = null;
  7398. this.bu = 0;
  7399. this.bv = 0;
  7400. this.faceId = -1;
  7401. this.subMeshId = 0;
  7402. }
  7403. // Methods
  7404. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7405. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7406. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7407. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7408. return null;
  7409. }
  7410. var indices = this.pickedMesh.getIndices();
  7411. var result;
  7412. if (useVerticesNormals) {
  7413. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7414. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7415. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7416. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7417. normal0 = normal0.scale(this.bu);
  7418. normal1 = normal1.scale(this.bv);
  7419. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7420. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7421. }
  7422. else {
  7423. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7424. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7425. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7426. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7427. var p1p2 = vertex1.subtract(vertex2);
  7428. var p3p2 = vertex3.subtract(vertex2);
  7429. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7430. }
  7431. if (useWorldCoordinates) {
  7432. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7433. }
  7434. return BABYLON.Vector3.Normalize(result);
  7435. };
  7436. PickingInfo.prototype.getTextureCoordinates = function () {
  7437. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7438. return null;
  7439. }
  7440. var indices = this.pickedMesh.getIndices();
  7441. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7442. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7443. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7444. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7445. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7446. uv1 = uv1.scale(this.bu);
  7447. uv2 = uv2.scale(this.bv);
  7448. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7449. };
  7450. return PickingInfo;
  7451. })();
  7452. BABYLON.PickingInfo = PickingInfo;
  7453. })(BABYLON || (BABYLON = {}));
  7454. var BABYLON;
  7455. (function (BABYLON) {
  7456. var BoundingSphere = (function () {
  7457. function BoundingSphere(minimum, maximum) {
  7458. this.minimum = minimum;
  7459. this.maximum = maximum;
  7460. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7461. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7462. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7463. this.radius = distance * 0.5;
  7464. this.centerWorld = BABYLON.Vector3.Zero();
  7465. this._update(BABYLON.Matrix.Identity());
  7466. }
  7467. // Methods
  7468. BoundingSphere.prototype._update = function (world) {
  7469. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7470. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7471. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7472. };
  7473. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7474. for (var i = 0; i < 6; i++) {
  7475. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7476. return false;
  7477. }
  7478. return true;
  7479. };
  7480. BoundingSphere.prototype.intersectsPoint = function (point) {
  7481. var x = this.centerWorld.x - point.x;
  7482. var y = this.centerWorld.y - point.y;
  7483. var z = this.centerWorld.z - point.z;
  7484. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7485. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7486. return false;
  7487. return true;
  7488. };
  7489. // Statics
  7490. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7491. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7492. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7493. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7494. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7495. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7496. return false;
  7497. return true;
  7498. };
  7499. return BoundingSphere;
  7500. })();
  7501. BABYLON.BoundingSphere = BoundingSphere;
  7502. })(BABYLON || (BABYLON = {}));
  7503. var BABYLON;
  7504. (function (BABYLON) {
  7505. var BoundingBox = (function () {
  7506. function BoundingBox(minimum, maximum) {
  7507. this.minimum = minimum;
  7508. this.maximum = maximum;
  7509. this.vectors = new Array();
  7510. this.vectorsWorld = new Array();
  7511. // Bounding vectors
  7512. this.vectors.push(this.minimum.clone());
  7513. this.vectors.push(this.maximum.clone());
  7514. this.vectors.push(this.minimum.clone());
  7515. this.vectors[2].x = this.maximum.x;
  7516. this.vectors.push(this.minimum.clone());
  7517. this.vectors[3].y = this.maximum.y;
  7518. this.vectors.push(this.minimum.clone());
  7519. this.vectors[4].z = this.maximum.z;
  7520. this.vectors.push(this.maximum.clone());
  7521. this.vectors[5].z = this.minimum.z;
  7522. this.vectors.push(this.maximum.clone());
  7523. this.vectors[6].x = this.minimum.x;
  7524. this.vectors.push(this.maximum.clone());
  7525. this.vectors[7].y = this.minimum.y;
  7526. // OBB
  7527. this.center = this.maximum.add(this.minimum).scale(0.5);
  7528. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7529. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7530. // World
  7531. for (var index = 0; index < this.vectors.length; index++) {
  7532. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7533. }
  7534. this.minimumWorld = BABYLON.Vector3.Zero();
  7535. this.maximumWorld = BABYLON.Vector3.Zero();
  7536. this._update(BABYLON.Matrix.Identity());
  7537. }
  7538. // Methods
  7539. BoundingBox.prototype.getWorldMatrix = function () {
  7540. return this._worldMatrix;
  7541. };
  7542. BoundingBox.prototype._update = function (world) {
  7543. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7544. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7545. for (var index = 0; index < this.vectors.length; index++) {
  7546. var v = this.vectorsWorld[index];
  7547. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7548. if (v.x < this.minimumWorld.x)
  7549. this.minimumWorld.x = v.x;
  7550. if (v.y < this.minimumWorld.y)
  7551. this.minimumWorld.y = v.y;
  7552. if (v.z < this.minimumWorld.z)
  7553. this.minimumWorld.z = v.z;
  7554. if (v.x > this.maximumWorld.x)
  7555. this.maximumWorld.x = v.x;
  7556. if (v.y > this.maximumWorld.y)
  7557. this.maximumWorld.y = v.y;
  7558. if (v.z > this.maximumWorld.z)
  7559. this.maximumWorld.z = v.z;
  7560. }
  7561. // OBB
  7562. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7563. this.center.scaleInPlace(0.5);
  7564. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7565. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7566. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7567. this._worldMatrix = world;
  7568. };
  7569. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7570. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7571. };
  7572. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7573. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7574. };
  7575. BoundingBox.prototype.intersectsPoint = function (point) {
  7576. var delta = -BABYLON.Engine.Epsilon;
  7577. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7578. return false;
  7579. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7580. return false;
  7581. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7582. return false;
  7583. return true;
  7584. };
  7585. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7586. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7587. };
  7588. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7589. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7590. return false;
  7591. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7592. return false;
  7593. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7594. return false;
  7595. return true;
  7596. };
  7597. // Statics
  7598. BoundingBox.Intersects = function (box0, box1) {
  7599. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7600. return false;
  7601. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7602. return false;
  7603. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7604. return false;
  7605. return true;
  7606. };
  7607. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7608. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7609. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7610. return (num <= (sphereRadius * sphereRadius));
  7611. };
  7612. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7613. for (var p = 0; p < 6; p++) {
  7614. for (var i = 0; i < 8; i++) {
  7615. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7616. return false;
  7617. }
  7618. }
  7619. }
  7620. return true;
  7621. };
  7622. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7623. for (var p = 0; p < 6; p++) {
  7624. var inCount = 8;
  7625. for (var i = 0; i < 8; i++) {
  7626. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7627. --inCount;
  7628. }
  7629. else {
  7630. break;
  7631. }
  7632. }
  7633. if (inCount === 0)
  7634. return false;
  7635. }
  7636. return true;
  7637. };
  7638. return BoundingBox;
  7639. })();
  7640. BABYLON.BoundingBox = BoundingBox;
  7641. })(BABYLON || (BABYLON = {}));
  7642. var BABYLON;
  7643. (function (BABYLON) {
  7644. var computeBoxExtents = function (axis, box) {
  7645. var p = BABYLON.Vector3.Dot(box.center, axis);
  7646. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7647. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7648. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7649. var r = r0 + r1 + r2;
  7650. return {
  7651. min: p - r,
  7652. max: p + r
  7653. };
  7654. };
  7655. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7656. var axisOverlap = function (axis, box0, box1) {
  7657. var result0 = computeBoxExtents(axis, box0);
  7658. var result1 = computeBoxExtents(axis, box1);
  7659. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7660. };
  7661. var BoundingInfo = (function () {
  7662. function BoundingInfo(minimum, maximum) {
  7663. this.minimum = minimum;
  7664. this.maximum = maximum;
  7665. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7666. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7667. }
  7668. // Methods
  7669. BoundingInfo.prototype._update = function (world) {
  7670. this.boundingBox._update(world);
  7671. this.boundingSphere._update(world);
  7672. };
  7673. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7674. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7675. return false;
  7676. return this.boundingBox.isInFrustum(frustumPlanes);
  7677. };
  7678. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7679. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7680. };
  7681. BoundingInfo.prototype._checkCollision = function (collider) {
  7682. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7683. };
  7684. BoundingInfo.prototype.intersectsPoint = function (point) {
  7685. if (!this.boundingSphere.centerWorld) {
  7686. return false;
  7687. }
  7688. if (!this.boundingSphere.intersectsPoint(point)) {
  7689. return false;
  7690. }
  7691. if (!this.boundingBox.intersectsPoint(point)) {
  7692. return false;
  7693. }
  7694. return true;
  7695. };
  7696. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7697. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7698. return false;
  7699. }
  7700. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7701. return false;
  7702. }
  7703. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7704. return false;
  7705. }
  7706. if (!precise) {
  7707. return true;
  7708. }
  7709. var box0 = this.boundingBox;
  7710. var box1 = boundingInfo.boundingBox;
  7711. if (!axisOverlap(box0.directions[0], box0, box1))
  7712. return false;
  7713. if (!axisOverlap(box0.directions[1], box0, box1))
  7714. return false;
  7715. if (!axisOverlap(box0.directions[2], box0, box1))
  7716. return false;
  7717. if (!axisOverlap(box1.directions[0], box0, box1))
  7718. return false;
  7719. if (!axisOverlap(box1.directions[1], box0, box1))
  7720. return false;
  7721. if (!axisOverlap(box1.directions[2], box0, box1))
  7722. return false;
  7723. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7724. return false;
  7725. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7726. return false;
  7727. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7728. return false;
  7729. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7730. return false;
  7731. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7732. return false;
  7733. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7734. return false;
  7735. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7736. return false;
  7737. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7738. return false;
  7739. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7740. return false;
  7741. return true;
  7742. };
  7743. return BoundingInfo;
  7744. })();
  7745. BABYLON.BoundingInfo = BoundingInfo;
  7746. })(BABYLON || (BABYLON = {}));
  7747. var BABYLON;
  7748. (function (BABYLON) {
  7749. var AbstractMesh = (function (_super) {
  7750. __extends(AbstractMesh, _super);
  7751. function AbstractMesh(name, scene) {
  7752. var _this = this;
  7753. _super.call(this, name, scene);
  7754. // Properties
  7755. this.definedFacingForward = true; // orientation for POV movement & rotation
  7756. this.position = new BABYLON.Vector3(0, 0, 0);
  7757. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7758. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7759. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7760. this.visibility = 1.0;
  7761. this.alphaIndex = Number.MAX_VALUE;
  7762. this.infiniteDistance = false;
  7763. this.isVisible = true;
  7764. this.isPickable = true;
  7765. this.showBoundingBox = false;
  7766. this.showSubMeshesBoundingBox = false;
  7767. this.onDispose = null;
  7768. this.isBlocker = false;
  7769. this.renderingGroupId = 0;
  7770. this.receiveShadows = false;
  7771. this.renderOutline = false;
  7772. this.outlineColor = BABYLON.Color3.Red();
  7773. this.outlineWidth = 0.02;
  7774. this.renderOverlay = false;
  7775. this.overlayColor = BABYLON.Color3.Red();
  7776. this.overlayAlpha = 0.5;
  7777. this.hasVertexAlpha = false;
  7778. this.useVertexColors = true;
  7779. this.applyFog = true;
  7780. this.computeBonesUsingShaders = true;
  7781. this.useOctreeForRenderingSelection = true;
  7782. this.useOctreeForPicking = true;
  7783. this.useOctreeForCollisions = true;
  7784. this.layerMask = 0x0FFFFFFF;
  7785. this.alwaysSelectAsActiveMesh = false;
  7786. // Physics
  7787. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7788. // Collisions
  7789. this._checkCollisions = false;
  7790. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7791. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7792. this._collider = new BABYLON.Collider();
  7793. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7794. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7795. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7796. // Edges
  7797. this.edgesWidth = 1;
  7798. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7799. // Cache
  7800. this._localScaling = BABYLON.Matrix.Zero();
  7801. this._localRotation = BABYLON.Matrix.Zero();
  7802. this._localTranslation = BABYLON.Matrix.Zero();
  7803. this._localBillboard = BABYLON.Matrix.Zero();
  7804. this._localPivotScaling = BABYLON.Matrix.Zero();
  7805. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7806. this._localWorld = BABYLON.Matrix.Zero();
  7807. this._worldMatrix = BABYLON.Matrix.Zero();
  7808. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7809. this._absolutePosition = BABYLON.Vector3.Zero();
  7810. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7811. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7812. this._isDirty = false;
  7813. this._pivotMatrix = BABYLON.Matrix.Identity();
  7814. this._isDisposed = false;
  7815. this._renderId = 0;
  7816. this._intersectionsInProgress = new Array();
  7817. this._onAfterWorldMatrixUpdate = new Array();
  7818. this._isWorldMatrixFrozen = false;
  7819. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7820. if (collidedMesh === void 0) { collidedMesh = null; }
  7821. //TODO move this to the collision coordinator!
  7822. if (_this.getScene().workerCollisions)
  7823. newPosition.multiplyInPlace(_this._collider.radius);
  7824. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7825. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7826. _this.position.addInPlace(_this._diffPositionForCollisions);
  7827. }
  7828. if (_this.onCollide && collidedMesh) {
  7829. _this.onCollide(collidedMesh);
  7830. }
  7831. };
  7832. scene.addMesh(this);
  7833. }
  7834. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7835. get: function () {
  7836. return AbstractMesh._BILLBOARDMODE_NONE;
  7837. },
  7838. enumerable: true,
  7839. configurable: true
  7840. });
  7841. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7842. get: function () {
  7843. return AbstractMesh._BILLBOARDMODE_X;
  7844. },
  7845. enumerable: true,
  7846. configurable: true
  7847. });
  7848. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7849. get: function () {
  7850. return AbstractMesh._BILLBOARDMODE_Y;
  7851. },
  7852. enumerable: true,
  7853. configurable: true
  7854. });
  7855. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7856. get: function () {
  7857. return AbstractMesh._BILLBOARDMODE_Z;
  7858. },
  7859. enumerable: true,
  7860. configurable: true
  7861. });
  7862. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7863. get: function () {
  7864. return AbstractMesh._BILLBOARDMODE_ALL;
  7865. },
  7866. enumerable: true,
  7867. configurable: true
  7868. });
  7869. // Methods
  7870. AbstractMesh.prototype.disableEdgesRendering = function () {
  7871. if (this._edgesRenderer !== undefined) {
  7872. this._edgesRenderer.dispose();
  7873. this._edgesRenderer = undefined;
  7874. }
  7875. };
  7876. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7877. if (epsilon === void 0) { epsilon = 0.95; }
  7878. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7879. this.disableEdgesRendering();
  7880. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7881. };
  7882. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7883. get: function () {
  7884. return false;
  7885. },
  7886. enumerable: true,
  7887. configurable: true
  7888. });
  7889. AbstractMesh.prototype.getLOD = function (camera) {
  7890. return this;
  7891. };
  7892. AbstractMesh.prototype.getTotalVertices = function () {
  7893. return 0;
  7894. };
  7895. AbstractMesh.prototype.getIndices = function () {
  7896. return null;
  7897. };
  7898. AbstractMesh.prototype.getVerticesData = function (kind) {
  7899. return null;
  7900. };
  7901. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7902. return false;
  7903. };
  7904. AbstractMesh.prototype.getBoundingInfo = function () {
  7905. if (this._masterMesh) {
  7906. return this._masterMesh.getBoundingInfo();
  7907. }
  7908. if (!this._boundingInfo) {
  7909. this._updateBoundingInfo();
  7910. }
  7911. return this._boundingInfo;
  7912. };
  7913. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7914. get: function () {
  7915. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. AbstractMesh.prototype._preActivate = function () {
  7921. };
  7922. AbstractMesh.prototype._activate = function (renderId) {
  7923. this._renderId = renderId;
  7924. };
  7925. AbstractMesh.prototype.getWorldMatrix = function () {
  7926. if (this._masterMesh) {
  7927. return this._masterMesh.getWorldMatrix();
  7928. }
  7929. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7930. this.computeWorldMatrix();
  7931. }
  7932. return this._worldMatrix;
  7933. };
  7934. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7935. get: function () {
  7936. return this._worldMatrix;
  7937. },
  7938. enumerable: true,
  7939. configurable: true
  7940. });
  7941. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7942. get: function () {
  7943. return this._absolutePosition;
  7944. },
  7945. enumerable: true,
  7946. configurable: true
  7947. });
  7948. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7949. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7950. this.computeWorldMatrix(true);
  7951. this._isWorldMatrixFrozen = true;
  7952. };
  7953. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7954. this._isWorldMatrixFrozen = false;
  7955. this.computeWorldMatrix(true);
  7956. };
  7957. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7958. get: function () {
  7959. return this._isWorldMatrixFrozen;
  7960. },
  7961. enumerable: true,
  7962. configurable: true
  7963. });
  7964. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7965. axis.normalize();
  7966. if (!this.rotationQuaternion) {
  7967. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7968. this.rotation = BABYLON.Vector3.Zero();
  7969. }
  7970. if (!space || space === BABYLON.Space.LOCAL) {
  7971. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7972. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7973. }
  7974. else {
  7975. if (this.parent) {
  7976. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7977. invertParentWorldMatrix.invert();
  7978. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7979. }
  7980. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7981. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7982. }
  7983. };
  7984. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7985. var displacementVector = axis.scale(distance);
  7986. if (!space || space === BABYLON.Space.LOCAL) {
  7987. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7988. this.setPositionWithLocalVector(tempV3);
  7989. }
  7990. else {
  7991. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7992. }
  7993. };
  7994. AbstractMesh.prototype.getAbsolutePosition = function () {
  7995. this.computeWorldMatrix();
  7996. return this._absolutePosition;
  7997. };
  7998. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7999. if (!absolutePosition) {
  8000. return;
  8001. }
  8002. var absolutePositionX;
  8003. var absolutePositionY;
  8004. var absolutePositionZ;
  8005. if (absolutePosition.x === undefined) {
  8006. if (arguments.length < 3) {
  8007. return;
  8008. }
  8009. absolutePositionX = arguments[0];
  8010. absolutePositionY = arguments[1];
  8011. absolutePositionZ = arguments[2];
  8012. }
  8013. else {
  8014. absolutePositionX = absolutePosition.x;
  8015. absolutePositionY = absolutePosition.y;
  8016. absolutePositionZ = absolutePosition.z;
  8017. }
  8018. if (this.parent) {
  8019. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8020. invertParentWorldMatrix.invert();
  8021. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8022. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8023. }
  8024. else {
  8025. this.position.x = absolutePositionX;
  8026. this.position.y = absolutePositionY;
  8027. this.position.z = absolutePositionZ;
  8028. }
  8029. };
  8030. // ================================== Point of View Movement =================================
  8031. /**
  8032. * Perform relative position change from the point of view of behind the front of the mesh.
  8033. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8034. * Supports definition of mesh facing forward or backward.
  8035. * @param {number} amountRight
  8036. * @param {number} amountUp
  8037. * @param {number} amountForward
  8038. */
  8039. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8040. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8041. };
  8042. /**
  8043. * Calculate relative position change from the point of view of behind the front of the mesh.
  8044. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8045. * Supports definition of mesh facing forward or backward.
  8046. * @param {number} amountRight
  8047. * @param {number} amountUp
  8048. * @param {number} amountForward
  8049. */
  8050. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8051. var rotMatrix = new BABYLON.Matrix();
  8052. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8053. rotQuaternion.toRotationMatrix(rotMatrix);
  8054. var translationDelta = BABYLON.Vector3.Zero();
  8055. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8056. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8057. return translationDelta;
  8058. };
  8059. // ================================== Point of View Rotation =================================
  8060. /**
  8061. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8062. * Supports definition of mesh facing forward or backward.
  8063. * @param {number} flipBack
  8064. * @param {number} twirlClockwise
  8065. * @param {number} tiltRight
  8066. */
  8067. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8068. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8069. };
  8070. /**
  8071. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8072. * Supports definition of mesh facing forward or backward.
  8073. * @param {number} flipBack
  8074. * @param {number} twirlClockwise
  8075. * @param {number} tiltRight
  8076. */
  8077. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8078. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8079. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8080. };
  8081. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8082. this._pivotMatrix = matrix;
  8083. this._cache.pivotMatrixUpdated = true;
  8084. };
  8085. AbstractMesh.prototype.getPivotMatrix = function () {
  8086. return this._pivotMatrix;
  8087. };
  8088. AbstractMesh.prototype._isSynchronized = function () {
  8089. if (this._isDirty) {
  8090. return false;
  8091. }
  8092. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8093. return false;
  8094. if (this._cache.pivotMatrixUpdated) {
  8095. return false;
  8096. }
  8097. if (this.infiniteDistance) {
  8098. return false;
  8099. }
  8100. if (!this._cache.position.equals(this.position))
  8101. return false;
  8102. if (this.rotationQuaternion) {
  8103. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8104. return false;
  8105. }
  8106. else {
  8107. if (!this._cache.rotation.equals(this.rotation))
  8108. return false;
  8109. }
  8110. if (!this._cache.scaling.equals(this.scaling))
  8111. return false;
  8112. return true;
  8113. };
  8114. AbstractMesh.prototype._initCache = function () {
  8115. _super.prototype._initCache.call(this);
  8116. this._cache.localMatrixUpdated = false;
  8117. this._cache.position = BABYLON.Vector3.Zero();
  8118. this._cache.scaling = BABYLON.Vector3.Zero();
  8119. this._cache.rotation = BABYLON.Vector3.Zero();
  8120. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8121. };
  8122. AbstractMesh.prototype.markAsDirty = function (property) {
  8123. if (property === "rotation") {
  8124. this.rotationQuaternion = null;
  8125. }
  8126. this._currentRenderId = Number.MAX_VALUE;
  8127. this._isDirty = true;
  8128. };
  8129. AbstractMesh.prototype._updateBoundingInfo = function () {
  8130. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8131. this._boundingInfo._update(this.worldMatrixFromCache);
  8132. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8133. };
  8134. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8135. if (!this.subMeshes) {
  8136. return;
  8137. }
  8138. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8139. var subMesh = this.subMeshes[subIndex];
  8140. subMesh.updateBoundingInfo(matrix);
  8141. }
  8142. };
  8143. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8144. if (this._isWorldMatrixFrozen) {
  8145. return this._worldMatrix;
  8146. }
  8147. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8148. return this._worldMatrix;
  8149. }
  8150. this._cache.position.copyFrom(this.position);
  8151. this._cache.scaling.copyFrom(this.scaling);
  8152. this._cache.pivotMatrixUpdated = false;
  8153. this._currentRenderId = this.getScene().getRenderId();
  8154. this._isDirty = false;
  8155. // Scaling
  8156. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8157. // Rotation
  8158. if (this.rotationQuaternion) {
  8159. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8160. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8161. }
  8162. else {
  8163. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8164. this._cache.rotation.copyFrom(this.rotation);
  8165. }
  8166. // Translation
  8167. if (this.infiniteDistance && !this.parent) {
  8168. var camera = this.getScene().activeCamera;
  8169. if (camera) {
  8170. var cameraWorldMatrix = camera.getWorldMatrix();
  8171. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8172. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8173. }
  8174. }
  8175. else {
  8176. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8177. }
  8178. // Composing transformations
  8179. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8180. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8181. // Billboarding
  8182. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8183. var localPosition = this.position.clone();
  8184. var zero = this.getScene().activeCamera.globalPosition.clone();
  8185. if (this.parent && this.parent.position) {
  8186. localPosition.addInPlace(this.parent.position);
  8187. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8188. }
  8189. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  8190. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8191. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8192. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8193. zero.y = localPosition.y + 0.001;
  8194. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8195. zero.z = localPosition.z + 0.001;
  8196. }
  8197. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8198. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8199. this._localBillboard.invert();
  8200. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8201. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8202. }
  8203. // Local world
  8204. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8205. // Parent
  8206. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8207. this._markSyncedWithParent();
  8208. if (this._meshToBoneReferal) {
  8209. if (!this._localMeshReferalTransform) {
  8210. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8211. }
  8212. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8213. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8214. }
  8215. else {
  8216. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8217. }
  8218. }
  8219. else {
  8220. this._worldMatrix.copyFrom(this._localWorld);
  8221. }
  8222. // Bounding info
  8223. this._updateBoundingInfo();
  8224. // Absolute position
  8225. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8226. // Callbacks
  8227. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8228. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8229. }
  8230. return this._worldMatrix;
  8231. };
  8232. /**
  8233. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8234. * @param func: callback function to add
  8235. */
  8236. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8237. this._onAfterWorldMatrixUpdate.push(func);
  8238. };
  8239. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8240. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8241. if (index > -1) {
  8242. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8243. }
  8244. };
  8245. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8246. this.computeWorldMatrix();
  8247. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8248. };
  8249. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8250. this.computeWorldMatrix();
  8251. var invLocalWorldMatrix = this._localWorld.clone();
  8252. invLocalWorldMatrix.invert();
  8253. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8254. };
  8255. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8256. this.computeWorldMatrix(true);
  8257. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8258. };
  8259. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8260. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8261. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8262. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8263. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8264. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8265. /// <returns>Mesh oriented towards targetMesh</returns>
  8266. yawCor = yawCor || 0; // default to zero if undefined
  8267. pitchCor = pitchCor || 0;
  8268. rollCor = rollCor || 0;
  8269. var dv = targetPoint.subtract(this.position);
  8270. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8271. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8272. var pitch = Math.atan2(dv.y, len);
  8273. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8274. };
  8275. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8276. this._meshToBoneReferal = affectedMesh;
  8277. this.parent = bone;
  8278. };
  8279. AbstractMesh.prototype.detachFromBone = function () {
  8280. this._meshToBoneReferal = null;
  8281. this.parent = null;
  8282. };
  8283. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8284. return this._boundingInfo.isInFrustum(frustumPlanes);
  8285. };
  8286. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8287. if (!camera) {
  8288. camera = this.getScene().activeCamera;
  8289. }
  8290. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8291. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8292. return false;
  8293. }
  8294. return true;
  8295. };
  8296. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8297. if (!this._boundingInfo || !mesh._boundingInfo) {
  8298. return false;
  8299. }
  8300. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8301. };
  8302. AbstractMesh.prototype.intersectsPoint = function (point) {
  8303. if (!this._boundingInfo) {
  8304. return false;
  8305. }
  8306. return this._boundingInfo.intersectsPoint(point);
  8307. };
  8308. // Physics
  8309. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8310. var physicsEngine = this.getScene().getPhysicsEngine();
  8311. if (!physicsEngine) {
  8312. return;
  8313. }
  8314. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8315. if (impostor.impostor) {
  8316. // Old API
  8317. options = impostor;
  8318. impostor = impostor.impostor;
  8319. }
  8320. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8321. physicsEngine._unregisterMesh(this);
  8322. return;
  8323. }
  8324. if (!options) {
  8325. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8326. }
  8327. else {
  8328. if (!options.mass && options.mass !== 0)
  8329. options.mass = 0;
  8330. if (!options.friction && options.friction !== 0)
  8331. options.friction = 0.2;
  8332. if (!options.restitution && options.restitution !== 0)
  8333. options.restitution = 0.2;
  8334. }
  8335. this._physicImpostor = impostor;
  8336. this._physicsMass = options.mass;
  8337. this._physicsFriction = options.friction;
  8338. this._physicRestitution = options.restitution;
  8339. return physicsEngine._registerMesh(this, impostor, options);
  8340. };
  8341. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8342. if (!this._physicImpostor) {
  8343. return BABYLON.PhysicsEngine.NoImpostor;
  8344. }
  8345. return this._physicImpostor;
  8346. };
  8347. AbstractMesh.prototype.getPhysicsMass = function () {
  8348. if (!this._physicsMass) {
  8349. return 0;
  8350. }
  8351. return this._physicsMass;
  8352. };
  8353. AbstractMesh.prototype.getPhysicsFriction = function () {
  8354. if (!this._physicsFriction) {
  8355. return 0;
  8356. }
  8357. return this._physicsFriction;
  8358. };
  8359. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8360. if (!this._physicRestitution) {
  8361. return 0;
  8362. }
  8363. return this._physicRestitution;
  8364. };
  8365. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8366. if (!camera) {
  8367. camera = this.getScene().activeCamera;
  8368. }
  8369. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8370. };
  8371. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8372. if (!camera) {
  8373. camera = this.getScene().activeCamera;
  8374. }
  8375. return this.absolutePosition.subtract(camera.position).length();
  8376. };
  8377. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8378. if (!this._physicImpostor) {
  8379. return;
  8380. }
  8381. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8382. };
  8383. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8384. if (!this._physicImpostor) {
  8385. return;
  8386. }
  8387. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8388. };
  8389. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8390. if (!this._physicImpostor) {
  8391. return;
  8392. }
  8393. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8394. };
  8395. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8396. // Collisions
  8397. get: function () {
  8398. return this._checkCollisions;
  8399. },
  8400. set: function (collisionEnabled) {
  8401. this._checkCollisions = collisionEnabled;
  8402. if (this.getScene().workerCollisions) {
  8403. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8404. }
  8405. },
  8406. enumerable: true,
  8407. configurable: true
  8408. });
  8409. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8410. var globalPosition = this.getAbsolutePosition();
  8411. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8412. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8413. this._collider.radius = this.ellipsoid;
  8414. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8415. };
  8416. // Submeshes octree
  8417. /**
  8418. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8419. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8420. */
  8421. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8422. if (maxCapacity === void 0) { maxCapacity = 64; }
  8423. if (maxDepth === void 0) { maxDepth = 2; }
  8424. if (!this._submeshesOctree) {
  8425. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8426. }
  8427. this.computeWorldMatrix(true);
  8428. // Update octree
  8429. var bbox = this.getBoundingInfo().boundingBox;
  8430. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8431. return this._submeshesOctree;
  8432. };
  8433. // Collisions
  8434. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8435. this._generatePointsArray();
  8436. // Transformation
  8437. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8438. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8439. subMesh._lastColliderWorldVertices = [];
  8440. subMesh._trianglePlanes = [];
  8441. var start = subMesh.verticesStart;
  8442. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8443. for (var i = start; i < end; i++) {
  8444. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8445. }
  8446. }
  8447. // Collide
  8448. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8449. if (collider.collisionFound) {
  8450. collider.collidedMesh = this;
  8451. }
  8452. };
  8453. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8454. var subMeshes;
  8455. var len;
  8456. // Octrees
  8457. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8458. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8459. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8460. len = intersections.length;
  8461. subMeshes = intersections.data;
  8462. }
  8463. else {
  8464. subMeshes = this.subMeshes;
  8465. len = subMeshes.length;
  8466. }
  8467. for (var index = 0; index < len; index++) {
  8468. var subMesh = subMeshes[index];
  8469. // Bounding test
  8470. if (len > 1 && !subMesh._checkCollision(collider))
  8471. continue;
  8472. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8473. }
  8474. };
  8475. AbstractMesh.prototype._checkCollision = function (collider) {
  8476. // Bounding box test
  8477. if (!this._boundingInfo._checkCollision(collider))
  8478. return;
  8479. // Transformation matrix
  8480. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8481. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8482. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8483. };
  8484. // Picking
  8485. AbstractMesh.prototype._generatePointsArray = function () {
  8486. return false;
  8487. };
  8488. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8489. var pickingInfo = new BABYLON.PickingInfo();
  8490. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8491. return pickingInfo;
  8492. }
  8493. if (!this._generatePointsArray()) {
  8494. return pickingInfo;
  8495. }
  8496. var intersectInfo = null;
  8497. // Octrees
  8498. var subMeshes;
  8499. var len;
  8500. if (this._submeshesOctree && this.useOctreeForPicking) {
  8501. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8502. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8503. len = intersections.length;
  8504. subMeshes = intersections.data;
  8505. }
  8506. else {
  8507. subMeshes = this.subMeshes;
  8508. len = subMeshes.length;
  8509. }
  8510. for (var index = 0; index < len; index++) {
  8511. var subMesh = subMeshes[index];
  8512. // Bounding test
  8513. if (len > 1 && !subMesh.canIntersects(ray))
  8514. continue;
  8515. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8516. if (currentIntersectInfo) {
  8517. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8518. intersectInfo = currentIntersectInfo;
  8519. intersectInfo.subMeshId = index;
  8520. if (fastCheck) {
  8521. break;
  8522. }
  8523. }
  8524. }
  8525. }
  8526. if (intersectInfo) {
  8527. // Get picked point
  8528. var world = this.getWorldMatrix();
  8529. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8530. var direction = ray.direction.clone();
  8531. direction = direction.scale(intersectInfo.distance);
  8532. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8533. var pickedPoint = worldOrigin.add(worldDirection);
  8534. // Return result
  8535. pickingInfo.hit = true;
  8536. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8537. pickingInfo.pickedPoint = pickedPoint;
  8538. pickingInfo.pickedMesh = this;
  8539. pickingInfo.bu = intersectInfo.bu;
  8540. pickingInfo.bv = intersectInfo.bv;
  8541. pickingInfo.faceId = intersectInfo.faceId;
  8542. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8543. return pickingInfo;
  8544. }
  8545. return pickingInfo;
  8546. };
  8547. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8548. return null;
  8549. };
  8550. AbstractMesh.prototype.releaseSubMeshes = function () {
  8551. if (this.subMeshes) {
  8552. while (this.subMeshes.length) {
  8553. this.subMeshes[0].dispose();
  8554. }
  8555. }
  8556. else {
  8557. this.subMeshes = new Array();
  8558. }
  8559. };
  8560. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8561. var index;
  8562. // Physics
  8563. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8564. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8565. }
  8566. // Intersections in progress
  8567. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8568. var other = this._intersectionsInProgress[index];
  8569. var pos = other._intersectionsInProgress.indexOf(this);
  8570. other._intersectionsInProgress.splice(pos, 1);
  8571. }
  8572. this._intersectionsInProgress = [];
  8573. // Edges
  8574. if (this._edgesRenderer) {
  8575. this._edgesRenderer.dispose();
  8576. this._edgesRenderer = null;
  8577. }
  8578. // SubMeshes
  8579. this.releaseSubMeshes();
  8580. // Remove from scene
  8581. this.getScene().removeMesh(this);
  8582. if (!doNotRecurse) {
  8583. // Particles
  8584. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8585. if (this.getScene().particleSystems[index].emitter === this) {
  8586. this.getScene().particleSystems[index].dispose();
  8587. index--;
  8588. }
  8589. }
  8590. // Children
  8591. var objects = this.getScene().meshes.slice(0);
  8592. for (index = 0; index < objects.length; index++) {
  8593. if (objects[index].parent === this) {
  8594. objects[index].dispose();
  8595. }
  8596. }
  8597. }
  8598. else {
  8599. for (index = 0; index < this.getScene().meshes.length; index++) {
  8600. var obj = this.getScene().meshes[index];
  8601. if (obj.parent === this) {
  8602. obj.parent = null;
  8603. obj.computeWorldMatrix(true);
  8604. }
  8605. }
  8606. }
  8607. this._onAfterWorldMatrixUpdate = [];
  8608. this._isDisposed = true;
  8609. // Callback
  8610. if (this.onDispose) {
  8611. this.onDispose();
  8612. }
  8613. };
  8614. // Statics
  8615. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8616. AbstractMesh._BILLBOARDMODE_X = 1;
  8617. AbstractMesh._BILLBOARDMODE_Y = 2;
  8618. AbstractMesh._BILLBOARDMODE_Z = 4;
  8619. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8620. return AbstractMesh;
  8621. })(BABYLON.Node);
  8622. BABYLON.AbstractMesh = AbstractMesh;
  8623. })(BABYLON || (BABYLON = {}));
  8624. var BABYLON;
  8625. (function (BABYLON) {
  8626. var Light = (function (_super) {
  8627. __extends(Light, _super);
  8628. function Light(name, scene) {
  8629. _super.call(this, name, scene);
  8630. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8631. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8632. this.intensity = 1.0;
  8633. this.range = Number.MAX_VALUE;
  8634. this.includeOnlyWithLayerMask = 0;
  8635. this.includedOnlyMeshes = new Array();
  8636. this.excludedMeshes = new Array();
  8637. this.excludeWithLayerMask = 0;
  8638. this._excludedMeshesIds = new Array();
  8639. this._includedOnlyMeshesIds = new Array();
  8640. scene.addLight(this);
  8641. }
  8642. Light.prototype.getShadowGenerator = function () {
  8643. return this._shadowGenerator;
  8644. };
  8645. Light.prototype.getAbsolutePosition = function () {
  8646. return BABYLON.Vector3.Zero();
  8647. };
  8648. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8649. };
  8650. Light.prototype._getWorldMatrix = function () {
  8651. return BABYLON.Matrix.Identity();
  8652. };
  8653. Light.prototype.canAffectMesh = function (mesh) {
  8654. if (!mesh) {
  8655. return true;
  8656. }
  8657. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8658. return false;
  8659. }
  8660. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8661. return false;
  8662. }
  8663. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8664. return false;
  8665. }
  8666. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8667. return false;
  8668. }
  8669. return true;
  8670. };
  8671. Light.prototype.getWorldMatrix = function () {
  8672. this._currentRenderId = this.getScene().getRenderId();
  8673. var worldMatrix = this._getWorldMatrix();
  8674. if (this.parent && this.parent.getWorldMatrix) {
  8675. if (!this._parentedWorldMatrix) {
  8676. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8677. }
  8678. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8679. this._markSyncedWithParent();
  8680. return this._parentedWorldMatrix;
  8681. }
  8682. return worldMatrix;
  8683. };
  8684. Light.prototype.dispose = function () {
  8685. if (this._shadowGenerator) {
  8686. this._shadowGenerator.dispose();
  8687. this._shadowGenerator = null;
  8688. }
  8689. // Remove from scene
  8690. this.getScene().removeLight(this);
  8691. };
  8692. return Light;
  8693. })(BABYLON.Node);
  8694. BABYLON.Light = Light;
  8695. })(BABYLON || (BABYLON = {}));
  8696. var BABYLON;
  8697. (function (BABYLON) {
  8698. var PointLight = (function (_super) {
  8699. __extends(PointLight, _super);
  8700. function PointLight(name, position, scene) {
  8701. _super.call(this, name, scene);
  8702. this.position = position;
  8703. }
  8704. PointLight.prototype.getAbsolutePosition = function () {
  8705. return this._transformedPosition ? this._transformedPosition : this.position;
  8706. };
  8707. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8708. if (this.parent && this.parent.getWorldMatrix) {
  8709. if (!this._transformedPosition) {
  8710. this._transformedPosition = BABYLON.Vector3.Zero();
  8711. }
  8712. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8713. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8714. return;
  8715. }
  8716. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8717. };
  8718. PointLight.prototype.getShadowGenerator = function () {
  8719. return null;
  8720. };
  8721. PointLight.prototype._getWorldMatrix = function () {
  8722. if (!this._worldMatrix) {
  8723. this._worldMatrix = BABYLON.Matrix.Identity();
  8724. }
  8725. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8726. return this._worldMatrix;
  8727. };
  8728. return PointLight;
  8729. })(BABYLON.Light);
  8730. BABYLON.PointLight = PointLight;
  8731. })(BABYLON || (BABYLON = {}));
  8732. var BABYLON;
  8733. (function (BABYLON) {
  8734. var SpotLight = (function (_super) {
  8735. __extends(SpotLight, _super);
  8736. function SpotLight(name, position, direction, angle, exponent, scene) {
  8737. _super.call(this, name, scene);
  8738. this.position = position;
  8739. this.direction = direction;
  8740. this.angle = angle;
  8741. this.exponent = exponent;
  8742. }
  8743. SpotLight.prototype.getAbsolutePosition = function () {
  8744. return this.transformedPosition ? this.transformedPosition : this.position;
  8745. };
  8746. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8747. var activeCamera = this.getScene().activeCamera;
  8748. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8749. };
  8750. SpotLight.prototype.supportsVSM = function () {
  8751. return true;
  8752. };
  8753. SpotLight.prototype.needRefreshPerFrame = function () {
  8754. return false;
  8755. };
  8756. SpotLight.prototype.setDirectionToTarget = function (target) {
  8757. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8758. return this.direction;
  8759. };
  8760. SpotLight.prototype.computeTransformedPosition = function () {
  8761. if (this.parent && this.parent.getWorldMatrix) {
  8762. if (!this.transformedPosition) {
  8763. this.transformedPosition = BABYLON.Vector3.Zero();
  8764. }
  8765. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8766. return true;
  8767. }
  8768. return false;
  8769. };
  8770. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8771. var normalizeDirection;
  8772. if (this.parent && this.parent.getWorldMatrix) {
  8773. if (!this._transformedDirection) {
  8774. this._transformedDirection = BABYLON.Vector3.Zero();
  8775. }
  8776. this.computeTransformedPosition();
  8777. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8778. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8779. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8780. }
  8781. else {
  8782. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8783. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8784. }
  8785. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8786. };
  8787. SpotLight.prototype._getWorldMatrix = function () {
  8788. if (!this._worldMatrix) {
  8789. this._worldMatrix = BABYLON.Matrix.Identity();
  8790. }
  8791. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8792. return this._worldMatrix;
  8793. };
  8794. return SpotLight;
  8795. })(BABYLON.Light);
  8796. BABYLON.SpotLight = SpotLight;
  8797. })(BABYLON || (BABYLON = {}));
  8798. var BABYLON;
  8799. (function (BABYLON) {
  8800. var HemisphericLight = (function (_super) {
  8801. __extends(HemisphericLight, _super);
  8802. function HemisphericLight(name, direction, scene) {
  8803. _super.call(this, name, scene);
  8804. this.direction = direction;
  8805. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8806. }
  8807. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8808. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8809. return this.direction;
  8810. };
  8811. HemisphericLight.prototype.getShadowGenerator = function () {
  8812. return null;
  8813. };
  8814. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8815. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8816. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8817. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8818. };
  8819. HemisphericLight.prototype._getWorldMatrix = function () {
  8820. if (!this._worldMatrix) {
  8821. this._worldMatrix = BABYLON.Matrix.Identity();
  8822. }
  8823. return this._worldMatrix;
  8824. };
  8825. return HemisphericLight;
  8826. })(BABYLON.Light);
  8827. BABYLON.HemisphericLight = HemisphericLight;
  8828. })(BABYLON || (BABYLON = {}));
  8829. var BABYLON;
  8830. (function (BABYLON) {
  8831. var DirectionalLight = (function (_super) {
  8832. __extends(DirectionalLight, _super);
  8833. function DirectionalLight(name, direction, scene) {
  8834. _super.call(this, name, scene);
  8835. this.direction = direction;
  8836. this.shadowOrthoScale = 0.5;
  8837. this.position = direction.scale(-1);
  8838. }
  8839. DirectionalLight.prototype.getAbsolutePosition = function () {
  8840. return this.transformedPosition ? this.transformedPosition : this.position;
  8841. };
  8842. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8843. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8844. return this.direction;
  8845. };
  8846. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8847. var orthoLeft = Number.MAX_VALUE;
  8848. var orthoRight = Number.MIN_VALUE;
  8849. var orthoTop = Number.MIN_VALUE;
  8850. var orthoBottom = Number.MAX_VALUE;
  8851. var tempVector3 = BABYLON.Vector3.Zero();
  8852. var activeCamera = this.getScene().activeCamera;
  8853. // Check extends
  8854. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8855. var mesh = renderList[meshIndex];
  8856. if (!mesh) {
  8857. continue;
  8858. }
  8859. var boundingInfo = mesh.getBoundingInfo();
  8860. if (!boundingInfo) {
  8861. continue;
  8862. }
  8863. var boundingBox = boundingInfo.boundingBox;
  8864. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8865. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8866. if (tempVector3.x < orthoLeft)
  8867. orthoLeft = tempVector3.x;
  8868. if (tempVector3.y < orthoBottom)
  8869. orthoBottom = tempVector3.y;
  8870. if (tempVector3.x > orthoRight)
  8871. orthoRight = tempVector3.x;
  8872. if (tempVector3.y > orthoTop)
  8873. orthoTop = tempVector3.y;
  8874. }
  8875. }
  8876. var xOffset = orthoRight - orthoLeft;
  8877. var yOffset = orthoTop - orthoBottom;
  8878. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8879. };
  8880. DirectionalLight.prototype.supportsVSM = function () {
  8881. return true;
  8882. };
  8883. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8884. return true;
  8885. };
  8886. DirectionalLight.prototype.computeTransformedPosition = function () {
  8887. if (this.parent && this.parent.getWorldMatrix) {
  8888. if (!this.transformedPosition) {
  8889. this.transformedPosition = BABYLON.Vector3.Zero();
  8890. }
  8891. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8892. return true;
  8893. }
  8894. return false;
  8895. };
  8896. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8897. if (this.parent && this.parent.getWorldMatrix) {
  8898. if (!this._transformedDirection) {
  8899. this._transformedDirection = BABYLON.Vector3.Zero();
  8900. }
  8901. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8902. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8903. return;
  8904. }
  8905. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8906. };
  8907. DirectionalLight.prototype._getWorldMatrix = function () {
  8908. if (!this._worldMatrix) {
  8909. this._worldMatrix = BABYLON.Matrix.Identity();
  8910. }
  8911. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8912. return this._worldMatrix;
  8913. };
  8914. return DirectionalLight;
  8915. })(BABYLON.Light);
  8916. BABYLON.DirectionalLight = DirectionalLight;
  8917. })(BABYLON || (BABYLON = {}));
  8918. var BABYLON;
  8919. (function (BABYLON) {
  8920. var ShadowGenerator = (function () {
  8921. function ShadowGenerator(mapSize, light) {
  8922. var _this = this;
  8923. // Members
  8924. this._filter = ShadowGenerator.FILTER_NONE;
  8925. this.blurScale = 2;
  8926. this._blurBoxOffset = 0;
  8927. this._bias = 0.00005;
  8928. this._lightDirection = BABYLON.Vector3.Zero();
  8929. this._darkness = 0;
  8930. this._transparencyShadow = false;
  8931. this._viewMatrix = BABYLON.Matrix.Zero();
  8932. this._projectionMatrix = BABYLON.Matrix.Zero();
  8933. this._transformMatrix = BABYLON.Matrix.Zero();
  8934. this._worldViewProjection = BABYLON.Matrix.Zero();
  8935. this._light = light;
  8936. this._scene = light.getScene();
  8937. this._mapSize = mapSize;
  8938. light._shadowGenerator = this;
  8939. // Render target
  8940. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8941. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8942. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8943. this._shadowMap.anisotropicFilteringLevel = 1;
  8944. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8945. this._shadowMap.renderParticles = false;
  8946. this._shadowMap.onAfterUnbind = function () {
  8947. if (!_this.useBlurVarianceShadowMap) {
  8948. return;
  8949. }
  8950. if (!_this._shadowMap2) {
  8951. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8952. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8953. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8954. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8955. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8956. _this._downSamplePostprocess.onApply = function (effect) {
  8957. effect.setTexture("textureSampler", _this._shadowMap);
  8958. };
  8959. _this.blurBoxOffset = 1;
  8960. }
  8961. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8962. };
  8963. // Custom render function
  8964. var renderSubMesh = function (subMesh) {
  8965. var mesh = subMesh.getRenderingMesh();
  8966. var scene = _this._scene;
  8967. var engine = scene.getEngine();
  8968. // Culling
  8969. engine.setState(subMesh.getMaterial().backFaceCulling);
  8970. // Managing instances
  8971. var batch = mesh._getInstancesRenderList(subMesh._id);
  8972. if (batch.mustReturn) {
  8973. return;
  8974. }
  8975. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8976. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8977. engine.enableEffect(_this._effect);
  8978. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8979. var material = subMesh.getMaterial();
  8980. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8981. // Alpha test
  8982. if (material && material.needAlphaTesting()) {
  8983. var alphaTexture = material.getAlphaTestTexture();
  8984. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8985. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8986. }
  8987. // Bones
  8988. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8989. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8990. }
  8991. // Draw
  8992. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8993. }
  8994. else {
  8995. // Need to reset refresh rate of the shadowMap
  8996. _this._shadowMap.resetRefreshCounter();
  8997. }
  8998. };
  8999. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9000. var index;
  9001. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9002. renderSubMesh(opaqueSubMeshes.data[index]);
  9003. }
  9004. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9005. renderSubMesh(alphaTestSubMeshes.data[index]);
  9006. }
  9007. if (_this._transparencyShadow) {
  9008. for (index = 0; index < transparentSubMeshes.length; index++) {
  9009. renderSubMesh(transparentSubMeshes.data[index]);
  9010. }
  9011. }
  9012. };
  9013. this._shadowMap.onClear = function (engine) {
  9014. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9015. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9016. }
  9017. else {
  9018. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9019. }
  9020. };
  9021. }
  9022. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9023. // Static
  9024. get: function () {
  9025. return ShadowGenerator._FILTER_NONE;
  9026. },
  9027. enumerable: true,
  9028. configurable: true
  9029. });
  9030. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9031. get: function () {
  9032. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9033. },
  9034. enumerable: true,
  9035. configurable: true
  9036. });
  9037. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9038. get: function () {
  9039. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9040. },
  9041. enumerable: true,
  9042. configurable: true
  9043. });
  9044. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9045. get: function () {
  9046. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9047. },
  9048. enumerable: true,
  9049. configurable: true
  9050. });
  9051. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9052. get: function () {
  9053. return this._bias;
  9054. },
  9055. set: function (bias) {
  9056. this._bias = bias;
  9057. },
  9058. enumerable: true,
  9059. configurable: true
  9060. });
  9061. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9062. get: function () {
  9063. return this._blurBoxOffset;
  9064. },
  9065. set: function (value) {
  9066. var _this = this;
  9067. if (this._blurBoxOffset === value) {
  9068. return;
  9069. }
  9070. this._blurBoxOffset = value;
  9071. if (this._boxBlurPostprocess) {
  9072. this._boxBlurPostprocess.dispose();
  9073. }
  9074. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9075. this._boxBlurPostprocess.onApply = function (effect) {
  9076. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9077. };
  9078. },
  9079. enumerable: true,
  9080. configurable: true
  9081. });
  9082. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9083. get: function () {
  9084. return this._filter;
  9085. },
  9086. set: function (value) {
  9087. if (this._filter === value) {
  9088. return;
  9089. }
  9090. this._filter = value;
  9091. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9092. this._shadowMap.anisotropicFilteringLevel = 16;
  9093. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9094. }
  9095. else {
  9096. this._shadowMap.anisotropicFilteringLevel = 1;
  9097. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9098. }
  9099. },
  9100. enumerable: true,
  9101. configurable: true
  9102. });
  9103. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9104. get: function () {
  9105. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9106. },
  9107. set: function (value) {
  9108. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9114. get: function () {
  9115. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9116. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9117. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9118. },
  9119. set: function (value) {
  9120. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9121. },
  9122. enumerable: true,
  9123. configurable: true
  9124. });
  9125. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9126. get: function () {
  9127. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9128. },
  9129. set: function (value) {
  9130. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9136. var defines = [];
  9137. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9138. defines.push("#define VSM");
  9139. }
  9140. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9141. var mesh = subMesh.getMesh();
  9142. var material = subMesh.getMaterial();
  9143. // Alpha test
  9144. if (material && material.needAlphaTesting()) {
  9145. defines.push("#define ALPHATEST");
  9146. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9147. attribs.push(BABYLON.VertexBuffer.UVKind);
  9148. defines.push("#define UV1");
  9149. }
  9150. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9151. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9152. defines.push("#define UV2");
  9153. }
  9154. }
  9155. // Bones
  9156. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9157. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9158. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9159. defines.push("#define BONES");
  9160. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9161. }
  9162. // Instances
  9163. if (useInstances) {
  9164. defines.push("#define INSTANCES");
  9165. attribs.push("world0");
  9166. attribs.push("world1");
  9167. attribs.push("world2");
  9168. attribs.push("world3");
  9169. }
  9170. // Get correct effect
  9171. var join = defines.join("\n");
  9172. if (this._cachedDefines !== join) {
  9173. this._cachedDefines = join;
  9174. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9175. }
  9176. return this._effect.isReady();
  9177. };
  9178. ShadowGenerator.prototype.getShadowMap = function () {
  9179. return this._shadowMap;
  9180. };
  9181. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9182. if (this._shadowMap2) {
  9183. return this._shadowMap2;
  9184. }
  9185. return this._shadowMap;
  9186. };
  9187. ShadowGenerator.prototype.getLight = function () {
  9188. return this._light;
  9189. };
  9190. // Methods
  9191. ShadowGenerator.prototype.getTransformMatrix = function () {
  9192. var scene = this._scene;
  9193. if (this._currentRenderID === scene.getRenderId()) {
  9194. return this._transformMatrix;
  9195. }
  9196. this._currentRenderID = scene.getRenderId();
  9197. var lightPosition = this._light.position;
  9198. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9199. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9200. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9201. }
  9202. if (this._light.computeTransformedPosition()) {
  9203. lightPosition = this._light.transformedPosition;
  9204. }
  9205. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9206. this._cachedPosition = lightPosition.clone();
  9207. this._cachedDirection = this._lightDirection.clone();
  9208. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9209. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9210. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9211. }
  9212. return this._transformMatrix;
  9213. };
  9214. ShadowGenerator.prototype.getDarkness = function () {
  9215. return this._darkness;
  9216. };
  9217. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9218. if (darkness >= 1.0)
  9219. this._darkness = 1.0;
  9220. else if (darkness <= 0.0)
  9221. this._darkness = 0.0;
  9222. else
  9223. this._darkness = darkness;
  9224. };
  9225. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9226. this._transparencyShadow = hasShadow;
  9227. };
  9228. ShadowGenerator.prototype._packHalf = function (depth) {
  9229. var scale = depth * 255.0;
  9230. var fract = scale - Math.floor(scale);
  9231. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9232. };
  9233. ShadowGenerator.prototype.dispose = function () {
  9234. this._shadowMap.dispose();
  9235. if (this._shadowMap2) {
  9236. this._shadowMap2.dispose();
  9237. }
  9238. if (this._downSamplePostprocess) {
  9239. this._downSamplePostprocess.dispose();
  9240. }
  9241. if (this._boxBlurPostprocess) {
  9242. this._boxBlurPostprocess.dispose();
  9243. }
  9244. };
  9245. ShadowGenerator._FILTER_NONE = 0;
  9246. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9247. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9248. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9249. return ShadowGenerator;
  9250. })();
  9251. BABYLON.ShadowGenerator = ShadowGenerator;
  9252. })(BABYLON || (BABYLON = {}));
  9253. var BABYLON;
  9254. (function (BABYLON) {
  9255. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9256. if (boxMin.x > sphereCenter.x + sphereRadius)
  9257. return false;
  9258. if (sphereCenter.x - sphereRadius > boxMax.x)
  9259. return false;
  9260. if (boxMin.y > sphereCenter.y + sphereRadius)
  9261. return false;
  9262. if (sphereCenter.y - sphereRadius > boxMax.y)
  9263. return false;
  9264. if (boxMin.z > sphereCenter.z + sphereRadius)
  9265. return false;
  9266. if (sphereCenter.z - sphereRadius > boxMax.z)
  9267. return false;
  9268. return true;
  9269. };
  9270. var getLowestRoot = function (a, b, c, maxR) {
  9271. var determinant = b * b - 4.0 * a * c;
  9272. var result = { root: 0, found: false };
  9273. if (determinant < 0)
  9274. return result;
  9275. var sqrtD = Math.sqrt(determinant);
  9276. var r1 = (-b - sqrtD) / (2.0 * a);
  9277. var r2 = (-b + sqrtD) / (2.0 * a);
  9278. if (r1 > r2) {
  9279. var temp = r2;
  9280. r2 = r1;
  9281. r1 = temp;
  9282. }
  9283. if (r1 > 0 && r1 < maxR) {
  9284. result.root = r1;
  9285. result.found = true;
  9286. return result;
  9287. }
  9288. if (r2 > 0 && r2 < maxR) {
  9289. result.root = r2;
  9290. result.found = true;
  9291. return result;
  9292. }
  9293. return result;
  9294. };
  9295. var Collider = (function () {
  9296. function Collider() {
  9297. this.radius = new BABYLON.Vector3(1, 1, 1);
  9298. this.retry = 0;
  9299. this.basePointWorld = BABYLON.Vector3.Zero();
  9300. this.velocityWorld = BABYLON.Vector3.Zero();
  9301. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9302. this._collisionPoint = BABYLON.Vector3.Zero();
  9303. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9304. this._tempVector = BABYLON.Vector3.Zero();
  9305. this._tempVector2 = BABYLON.Vector3.Zero();
  9306. this._tempVector3 = BABYLON.Vector3.Zero();
  9307. this._tempVector4 = BABYLON.Vector3.Zero();
  9308. this._edge = BABYLON.Vector3.Zero();
  9309. this._baseToVertex = BABYLON.Vector3.Zero();
  9310. this._destinationPoint = BABYLON.Vector3.Zero();
  9311. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9312. this._displacementVector = BABYLON.Vector3.Zero();
  9313. }
  9314. // Methods
  9315. Collider.prototype._initialize = function (source, dir, e) {
  9316. this.velocity = dir;
  9317. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9318. this.basePoint = source;
  9319. source.multiplyToRef(this.radius, this.basePointWorld);
  9320. dir.multiplyToRef(this.radius, this.velocityWorld);
  9321. this.velocityWorldLength = this.velocityWorld.length();
  9322. this.epsilon = e;
  9323. this.collisionFound = false;
  9324. };
  9325. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9326. pa.subtractToRef(point, this._tempVector);
  9327. pb.subtractToRef(point, this._tempVector2);
  9328. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9329. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9330. if (d < 0)
  9331. return false;
  9332. pc.subtractToRef(point, this._tempVector3);
  9333. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9334. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9335. if (d < 0)
  9336. return false;
  9337. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9338. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9339. return d >= 0;
  9340. };
  9341. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9342. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9343. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9344. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9345. return false;
  9346. }
  9347. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9348. return false;
  9349. return true;
  9350. };
  9351. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9352. var t0;
  9353. var embeddedInPlane = false;
  9354. //defensive programming, actually not needed.
  9355. if (!trianglePlaneArray) {
  9356. trianglePlaneArray = [];
  9357. }
  9358. if (!trianglePlaneArray[faceIndex]) {
  9359. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9360. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9361. }
  9362. var trianglePlane = trianglePlaneArray[faceIndex];
  9363. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9364. return;
  9365. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9366. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9367. if (normalDotVelocity == 0) {
  9368. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9369. return;
  9370. embeddedInPlane = true;
  9371. t0 = 0;
  9372. }
  9373. else {
  9374. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9375. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9376. if (t0 > t1) {
  9377. var temp = t1;
  9378. t1 = t0;
  9379. t0 = temp;
  9380. }
  9381. if (t0 > 1.0 || t1 < 0.0)
  9382. return;
  9383. if (t0 < 0)
  9384. t0 = 0;
  9385. if (t0 > 1.0)
  9386. t0 = 1.0;
  9387. }
  9388. this._collisionPoint.copyFromFloats(0, 0, 0);
  9389. var found = false;
  9390. var t = 1.0;
  9391. if (!embeddedInPlane) {
  9392. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9393. this.velocity.scaleToRef(t0, this._tempVector);
  9394. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9395. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9396. found = true;
  9397. t = t0;
  9398. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9399. }
  9400. }
  9401. if (!found) {
  9402. var velocitySquaredLength = this.velocity.lengthSquared();
  9403. var a = velocitySquaredLength;
  9404. this.basePoint.subtractToRef(p1, this._tempVector);
  9405. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9406. var c = this._tempVector.lengthSquared() - 1.0;
  9407. var lowestRoot = getLowestRoot(a, b, c, t);
  9408. if (lowestRoot.found) {
  9409. t = lowestRoot.root;
  9410. found = true;
  9411. this._collisionPoint.copyFrom(p1);
  9412. }
  9413. this.basePoint.subtractToRef(p2, this._tempVector);
  9414. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9415. c = this._tempVector.lengthSquared() - 1.0;
  9416. lowestRoot = getLowestRoot(a, b, c, t);
  9417. if (lowestRoot.found) {
  9418. t = lowestRoot.root;
  9419. found = true;
  9420. this._collisionPoint.copyFrom(p2);
  9421. }
  9422. this.basePoint.subtractToRef(p3, this._tempVector);
  9423. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9424. c = this._tempVector.lengthSquared() - 1.0;
  9425. lowestRoot = getLowestRoot(a, b, c, t);
  9426. if (lowestRoot.found) {
  9427. t = lowestRoot.root;
  9428. found = true;
  9429. this._collisionPoint.copyFrom(p3);
  9430. }
  9431. p2.subtractToRef(p1, this._edge);
  9432. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9433. var edgeSquaredLength = this._edge.lengthSquared();
  9434. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9435. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9436. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9437. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9438. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9439. lowestRoot = getLowestRoot(a, b, c, t);
  9440. if (lowestRoot.found) {
  9441. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9442. if (f >= 0.0 && f <= 1.0) {
  9443. t = lowestRoot.root;
  9444. found = true;
  9445. this._edge.scaleInPlace(f);
  9446. p1.addToRef(this._edge, this._collisionPoint);
  9447. }
  9448. }
  9449. p3.subtractToRef(p2, this._edge);
  9450. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9451. edgeSquaredLength = this._edge.lengthSquared();
  9452. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9453. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9454. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9455. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9456. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9457. lowestRoot = getLowestRoot(a, b, c, t);
  9458. if (lowestRoot.found) {
  9459. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9460. if (f >= 0.0 && f <= 1.0) {
  9461. t = lowestRoot.root;
  9462. found = true;
  9463. this._edge.scaleInPlace(f);
  9464. p2.addToRef(this._edge, this._collisionPoint);
  9465. }
  9466. }
  9467. p1.subtractToRef(p3, this._edge);
  9468. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9469. edgeSquaredLength = this._edge.lengthSquared();
  9470. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9471. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9472. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9473. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9474. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9475. lowestRoot = getLowestRoot(a, b, c, t);
  9476. if (lowestRoot.found) {
  9477. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9478. if (f >= 0.0 && f <= 1.0) {
  9479. t = lowestRoot.root;
  9480. found = true;
  9481. this._edge.scaleInPlace(f);
  9482. p3.addToRef(this._edge, this._collisionPoint);
  9483. }
  9484. }
  9485. }
  9486. if (found) {
  9487. var distToCollision = t * this.velocity.length();
  9488. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9489. if (!this.intersectionPoint) {
  9490. this.intersectionPoint = this._collisionPoint.clone();
  9491. }
  9492. else {
  9493. this.intersectionPoint.copyFrom(this._collisionPoint);
  9494. }
  9495. this.nearestDistance = distToCollision;
  9496. this.collisionFound = true;
  9497. }
  9498. }
  9499. };
  9500. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9501. for (var i = indexStart; i < indexEnd; i += 3) {
  9502. var p1 = pts[indices[i] - decal];
  9503. var p2 = pts[indices[i + 1] - decal];
  9504. var p3 = pts[indices[i + 2] - decal];
  9505. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9506. }
  9507. };
  9508. Collider.prototype._getResponse = function (pos, vel) {
  9509. pos.addToRef(vel, this._destinationPoint);
  9510. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9511. this.basePoint.addToRef(vel, pos);
  9512. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9513. this._slidePlaneNormal.normalize();
  9514. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9515. pos.addInPlace(this._displacementVector);
  9516. this.intersectionPoint.addInPlace(this._displacementVector);
  9517. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9518. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9519. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9520. };
  9521. return Collider;
  9522. })();
  9523. BABYLON.Collider = Collider;
  9524. })(BABYLON || (BABYLON = {}));
  9525. var BABYLON;
  9526. (function (BABYLON) {
  9527. //WebWorker code will be inserted to this variable.
  9528. BABYLON.CollisionWorker = "";
  9529. (function (WorkerTaskType) {
  9530. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9531. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9532. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9533. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9534. var WorkerTaskType = BABYLON.WorkerTaskType;
  9535. (function (WorkerReplyType) {
  9536. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9537. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9538. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9539. var WorkerReplyType = BABYLON.WorkerReplyType;
  9540. var CollisionCoordinatorWorker = (function () {
  9541. function CollisionCoordinatorWorker() {
  9542. var _this = this;
  9543. this._scaledPosition = BABYLON.Vector3.Zero();
  9544. this._scaledVelocity = BABYLON.Vector3.Zero();
  9545. this.onMeshUpdated = function (mesh) {
  9546. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9547. };
  9548. this.onGeometryUpdated = function (geometry) {
  9549. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9550. };
  9551. this._afterRender = function () {
  9552. if (!_this._init)
  9553. return;
  9554. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9555. return;
  9556. }
  9557. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9558. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9559. if (_this._runningUpdated > 4) {
  9560. return;
  9561. }
  9562. ++_this._runningUpdated;
  9563. var payload = {
  9564. updatedMeshes: _this._addUpdateMeshesList,
  9565. updatedGeometries: _this._addUpdateGeometriesList,
  9566. removedGeometries: _this._toRemoveGeometryArray,
  9567. removedMeshes: _this._toRemoveMeshesArray
  9568. };
  9569. var message = {
  9570. payload: payload,
  9571. taskType: WorkerTaskType.UPDATE
  9572. };
  9573. var serializable = [];
  9574. for (var id in payload.updatedGeometries) {
  9575. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9576. //prepare transferables
  9577. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9578. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9579. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9580. }
  9581. }
  9582. _this._worker.postMessage(message, serializable);
  9583. _this._addUpdateMeshesList = {};
  9584. _this._addUpdateGeometriesList = {};
  9585. _this._toRemoveGeometryArray = [];
  9586. _this._toRemoveMeshesArray = [];
  9587. };
  9588. this._onMessageFromWorker = function (e) {
  9589. var returnData = e.data;
  9590. if (returnData.error != WorkerReplyType.SUCCESS) {
  9591. //TODO what errors can be returned from the worker?
  9592. BABYLON.Tools.Warn("error returned from worker!");
  9593. return;
  9594. }
  9595. switch (returnData.taskType) {
  9596. case WorkerTaskType.INIT:
  9597. _this._init = true;
  9598. //Update the worked with ALL of the scene's current state
  9599. _this._scene.meshes.forEach(function (mesh) {
  9600. _this.onMeshAdded(mesh);
  9601. });
  9602. _this._scene.getGeometries().forEach(function (geometry) {
  9603. _this.onGeometryAdded(geometry);
  9604. });
  9605. break;
  9606. case WorkerTaskType.UPDATE:
  9607. _this._runningUpdated--;
  9608. break;
  9609. case WorkerTaskType.COLLIDE:
  9610. _this._runningCollisionTask = false;
  9611. var returnPayload = returnData.payload;
  9612. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9613. return;
  9614. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9615. //cleanup
  9616. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9617. break;
  9618. }
  9619. };
  9620. this._collisionsCallbackArray = [];
  9621. this._init = false;
  9622. this._runningUpdated = 0;
  9623. this._runningCollisionTask = false;
  9624. this._addUpdateMeshesList = {};
  9625. this._addUpdateGeometriesList = {};
  9626. this._toRemoveGeometryArray = [];
  9627. this._toRemoveMeshesArray = [];
  9628. }
  9629. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9630. if (!this._init)
  9631. return;
  9632. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9633. return;
  9634. position.divideToRef(collider.radius, this._scaledPosition);
  9635. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9636. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9637. var payload = {
  9638. collider: {
  9639. position: this._scaledPosition.asArray(),
  9640. velocity: this._scaledVelocity.asArray(),
  9641. radius: collider.radius.asArray()
  9642. },
  9643. collisionId: collisionIndex,
  9644. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9645. maximumRetry: maximumRetry
  9646. };
  9647. var message = {
  9648. payload: payload,
  9649. taskType: WorkerTaskType.COLLIDE
  9650. };
  9651. this._worker.postMessage(message);
  9652. };
  9653. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9654. this._scene = scene;
  9655. this._scene.registerAfterRender(this._afterRender);
  9656. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9657. this._worker = new Worker(workerUrl);
  9658. this._worker.onmessage = this._onMessageFromWorker;
  9659. var message = {
  9660. payload: {},
  9661. taskType: WorkerTaskType.INIT
  9662. };
  9663. this._worker.postMessage(message);
  9664. };
  9665. CollisionCoordinatorWorker.prototype.destroy = function () {
  9666. this._scene.unregisterAfterRender(this._afterRender);
  9667. this._worker.terminate();
  9668. };
  9669. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9670. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9671. this.onMeshUpdated(mesh);
  9672. };
  9673. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9674. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9675. };
  9676. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9677. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9678. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9679. this.onGeometryUpdated(geometry);
  9680. };
  9681. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9682. this._toRemoveGeometryArray.push(geometry.id);
  9683. };
  9684. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9685. var submeshes = [];
  9686. if (mesh.subMeshes) {
  9687. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9688. return {
  9689. position: idx,
  9690. verticesStart: sm.verticesStart,
  9691. verticesCount: sm.verticesCount,
  9692. indexStart: sm.indexStart,
  9693. indexCount: sm.indexCount,
  9694. hasMaterial: !!sm.getMaterial(),
  9695. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9696. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9697. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9698. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9699. };
  9700. });
  9701. }
  9702. var geometryId = null;
  9703. if (mesh instanceof BABYLON.Mesh) {
  9704. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9705. }
  9706. else if (mesh instanceof BABYLON.InstancedMesh) {
  9707. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9708. }
  9709. return {
  9710. uniqueId: mesh.uniqueId,
  9711. id: mesh.id,
  9712. name: mesh.name,
  9713. geometryId: geometryId,
  9714. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9715. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9716. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9717. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9718. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9719. subMeshes: submeshes,
  9720. checkCollisions: mesh.checkCollisions
  9721. };
  9722. };
  9723. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9724. return {
  9725. id: geometry.id,
  9726. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9727. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9728. indices: new Int32Array(geometry.getIndices() || []),
  9729. };
  9730. };
  9731. return CollisionCoordinatorWorker;
  9732. })();
  9733. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9734. var CollisionCoordinatorLegacy = (function () {
  9735. function CollisionCoordinatorLegacy() {
  9736. this._scaledPosition = BABYLON.Vector3.Zero();
  9737. this._scaledVelocity = BABYLON.Vector3.Zero();
  9738. this._finalPosition = BABYLON.Vector3.Zero();
  9739. }
  9740. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9741. position.divideToRef(collider.radius, this._scaledPosition);
  9742. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9743. collider.collidedMesh = null;
  9744. collider.retry = 0;
  9745. collider.initialVelocity = this._scaledVelocity;
  9746. collider.initialPosition = this._scaledPosition;
  9747. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9748. this._finalPosition.multiplyInPlace(collider.radius);
  9749. //run the callback
  9750. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9751. };
  9752. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9753. this._scene = scene;
  9754. };
  9755. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9756. //Legacy need no destruction method.
  9757. };
  9758. //No update in legacy mode
  9759. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9760. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9761. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9762. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9763. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9764. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9765. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9766. if (excludedMesh === void 0) { excludedMesh = null; }
  9767. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9768. if (collider.retry >= maximumRetry) {
  9769. finalPosition.copyFrom(position);
  9770. return;
  9771. }
  9772. collider._initialize(position, velocity, closeDistance);
  9773. // Check all meshes
  9774. for (var index = 0; index < this._scene.meshes.length; index++) {
  9775. var mesh = this._scene.meshes[index];
  9776. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9777. mesh._checkCollision(collider);
  9778. }
  9779. }
  9780. if (!collider.collisionFound) {
  9781. position.addToRef(velocity, finalPosition);
  9782. return;
  9783. }
  9784. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9785. collider._getResponse(position, velocity);
  9786. }
  9787. if (velocity.length() <= closeDistance) {
  9788. finalPosition.copyFrom(position);
  9789. return;
  9790. }
  9791. collider.retry++;
  9792. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9793. };
  9794. return CollisionCoordinatorLegacy;
  9795. })();
  9796. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9797. })(BABYLON || (BABYLON = {}));
  9798. var BABYLON;
  9799. (function (BABYLON) {
  9800. var VRCameraMetrics = (function () {
  9801. function VRCameraMetrics() {
  9802. this.compensateDistorsion = true;
  9803. }
  9804. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9805. get: function () {
  9806. return this.hResolution / (2 * this.vResolution);
  9807. },
  9808. enumerable: true,
  9809. configurable: true
  9810. });
  9811. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9812. get: function () {
  9813. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9814. },
  9815. enumerable: true,
  9816. configurable: true
  9817. });
  9818. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9819. get: function () {
  9820. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9821. var h = (4 * meters) / this.hScreenSize;
  9822. return BABYLON.Matrix.Translation(h, 0, 0);
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9828. get: function () {
  9829. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9830. var h = (4 * meters) / this.hScreenSize;
  9831. return BABYLON.Matrix.Translation(-h, 0, 0);
  9832. },
  9833. enumerable: true,
  9834. configurable: true
  9835. });
  9836. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9837. get: function () {
  9838. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9844. get: function () {
  9845. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. VRCameraMetrics.GetDefault = function () {
  9851. var result = new VRCameraMetrics();
  9852. result.hResolution = 1280;
  9853. result.vResolution = 800;
  9854. result.hScreenSize = 0.149759993;
  9855. result.vScreenSize = 0.0935999975;
  9856. result.vScreenCenter = 0.0467999987,
  9857. result.eyeToScreenDistance = 0.0410000011;
  9858. result.lensSeparationDistance = 0.0635000020;
  9859. result.interpupillaryDistance = 0.0640000030;
  9860. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9861. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9862. result.postProcessScaleFactor = 1.714605507808412;
  9863. result.lensCenterOffset = 0.151976421;
  9864. return result;
  9865. };
  9866. return VRCameraMetrics;
  9867. })();
  9868. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9869. var Camera = (function (_super) {
  9870. __extends(Camera, _super);
  9871. function Camera(name, position, scene) {
  9872. _super.call(this, name, scene);
  9873. this.position = position;
  9874. // Members
  9875. this.upVector = BABYLON.Vector3.Up();
  9876. this.orthoLeft = null;
  9877. this.orthoRight = null;
  9878. this.orthoBottom = null;
  9879. this.orthoTop = null;
  9880. this.fov = 0.8;
  9881. this.minZ = 1.0;
  9882. this.maxZ = 10000.0;
  9883. this.inertia = 0.9;
  9884. this.mode = Camera.PERSPECTIVE_CAMERA;
  9885. this.isIntermediate = false;
  9886. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9887. this.layerMask = 0x0FFFFFFF;
  9888. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9889. // Camera rig members
  9890. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9891. this._rigCameras = new Array();
  9892. // Cache
  9893. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9894. this._projectionMatrix = new BABYLON.Matrix();
  9895. this._postProcesses = new Array();
  9896. this._postProcessesTakenIndices = [];
  9897. this._activeMeshes = new BABYLON.SmartArray(256);
  9898. this._globalPosition = BABYLON.Vector3.Zero();
  9899. scene.addCamera(this);
  9900. if (!scene.activeCamera) {
  9901. scene.activeCamera = this;
  9902. }
  9903. }
  9904. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9905. get: function () {
  9906. return Camera._PERSPECTIVE_CAMERA;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9912. get: function () {
  9913. return Camera._ORTHOGRAPHIC_CAMERA;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9919. get: function () {
  9920. return Camera._FOVMODE_VERTICAL_FIXED;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9926. get: function () {
  9927. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9933. get: function () {
  9934. return Camera._RIG_MODE_NONE;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9940. get: function () {
  9941. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9947. get: function () {
  9948. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9954. get: function () {
  9955. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9961. get: function () {
  9962. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9968. get: function () {
  9969. return Camera._RIG_MODE_VR;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(Camera.prototype, "globalPosition", {
  9975. get: function () {
  9976. return this._globalPosition;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Camera.prototype.getActiveMeshes = function () {
  9982. return this._activeMeshes;
  9983. };
  9984. Camera.prototype.isActiveMesh = function (mesh) {
  9985. return (this._activeMeshes.indexOf(mesh) !== -1);
  9986. };
  9987. //Cache
  9988. Camera.prototype._initCache = function () {
  9989. _super.prototype._initCache.call(this);
  9990. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9991. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9992. this._cache.mode = undefined;
  9993. this._cache.minZ = undefined;
  9994. this._cache.maxZ = undefined;
  9995. this._cache.fov = undefined;
  9996. this._cache.aspectRatio = undefined;
  9997. this._cache.orthoLeft = undefined;
  9998. this._cache.orthoRight = undefined;
  9999. this._cache.orthoBottom = undefined;
  10000. this._cache.orthoTop = undefined;
  10001. this._cache.renderWidth = undefined;
  10002. this._cache.renderHeight = undefined;
  10003. };
  10004. Camera.prototype._updateCache = function (ignoreParentClass) {
  10005. if (!ignoreParentClass) {
  10006. _super.prototype._updateCache.call(this);
  10007. }
  10008. var engine = this.getEngine();
  10009. this._cache.position.copyFrom(this.position);
  10010. this._cache.upVector.copyFrom(this.upVector);
  10011. this._cache.mode = this.mode;
  10012. this._cache.minZ = this.minZ;
  10013. this._cache.maxZ = this.maxZ;
  10014. this._cache.fov = this.fov;
  10015. this._cache.aspectRatio = engine.getAspectRatio(this);
  10016. this._cache.orthoLeft = this.orthoLeft;
  10017. this._cache.orthoRight = this.orthoRight;
  10018. this._cache.orthoBottom = this.orthoBottom;
  10019. this._cache.orthoTop = this.orthoTop;
  10020. this._cache.renderWidth = engine.getRenderWidth();
  10021. this._cache.renderHeight = engine.getRenderHeight();
  10022. };
  10023. Camera.prototype._updateFromScene = function () {
  10024. this.updateCache();
  10025. this._update();
  10026. };
  10027. // Synchronized
  10028. Camera.prototype._isSynchronized = function () {
  10029. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10030. };
  10031. Camera.prototype._isSynchronizedViewMatrix = function () {
  10032. if (!_super.prototype._isSynchronized.call(this))
  10033. return false;
  10034. return this._cache.position.equals(this.position)
  10035. && this._cache.upVector.equals(this.upVector)
  10036. && this.isSynchronizedWithParent();
  10037. };
  10038. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10039. var check = this._cache.mode === this.mode
  10040. && this._cache.minZ === this.minZ
  10041. && this._cache.maxZ === this.maxZ;
  10042. if (!check) {
  10043. return false;
  10044. }
  10045. var engine = this.getEngine();
  10046. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10047. check = this._cache.fov === this.fov
  10048. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10049. }
  10050. else {
  10051. check = this._cache.orthoLeft === this.orthoLeft
  10052. && this._cache.orthoRight === this.orthoRight
  10053. && this._cache.orthoBottom === this.orthoBottom
  10054. && this._cache.orthoTop === this.orthoTop
  10055. && this._cache.renderWidth === engine.getRenderWidth()
  10056. && this._cache.renderHeight === engine.getRenderHeight();
  10057. }
  10058. return check;
  10059. };
  10060. // Controls
  10061. Camera.prototype.attachControl = function (element) {
  10062. };
  10063. Camera.prototype.detachControl = function (element) {
  10064. };
  10065. Camera.prototype._update = function () {
  10066. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10067. this._updateRigCameras();
  10068. }
  10069. this._checkInputs();
  10070. };
  10071. Camera.prototype._checkInputs = function () {
  10072. };
  10073. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10074. if (insertAt === void 0) { insertAt = null; }
  10075. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10076. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10077. return 0;
  10078. }
  10079. if (insertAt == null || insertAt < 0) {
  10080. this._postProcesses.push(postProcess);
  10081. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10082. return this._postProcesses.length - 1;
  10083. }
  10084. var add = 0;
  10085. if (this._postProcesses[insertAt]) {
  10086. var start = this._postProcesses.length - 1;
  10087. for (var i = start; i >= insertAt + 1; --i) {
  10088. this._postProcesses[i + 1] = this._postProcesses[i];
  10089. }
  10090. add = 1;
  10091. }
  10092. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10093. if (this._postProcessesTakenIndices[i] < insertAt) {
  10094. continue;
  10095. }
  10096. start = this._postProcessesTakenIndices.length - 1;
  10097. for (var j = start; j >= i; --j) {
  10098. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10099. }
  10100. this._postProcessesTakenIndices[i] = insertAt;
  10101. break;
  10102. }
  10103. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10104. this._postProcessesTakenIndices.push(insertAt);
  10105. }
  10106. var result = insertAt + add;
  10107. this._postProcesses[result] = postProcess;
  10108. return result;
  10109. };
  10110. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10111. if (atIndices === void 0) { atIndices = null; }
  10112. var result = [];
  10113. if (!atIndices) {
  10114. var length = this._postProcesses.length;
  10115. for (var i = 0; i < length; i++) {
  10116. if (this._postProcesses[i] !== postProcess) {
  10117. continue;
  10118. }
  10119. delete this._postProcesses[i];
  10120. var index = this._postProcessesTakenIndices.indexOf(i);
  10121. this._postProcessesTakenIndices.splice(index, 1);
  10122. }
  10123. }
  10124. else {
  10125. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10126. for (i = 0; i < atIndices.length; i++) {
  10127. var foundPostProcess = this._postProcesses[atIndices[i]];
  10128. if (foundPostProcess !== postProcess) {
  10129. result.push(i);
  10130. continue;
  10131. }
  10132. delete this._postProcesses[atIndices[i]];
  10133. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10134. this._postProcessesTakenIndices.splice(index, 1);
  10135. }
  10136. }
  10137. return result;
  10138. };
  10139. Camera.prototype.getWorldMatrix = function () {
  10140. if (!this._worldMatrix) {
  10141. this._worldMatrix = BABYLON.Matrix.Identity();
  10142. }
  10143. var viewMatrix = this.getViewMatrix();
  10144. viewMatrix.invertToRef(this._worldMatrix);
  10145. return this._worldMatrix;
  10146. };
  10147. Camera.prototype._getViewMatrix = function () {
  10148. return BABYLON.Matrix.Identity();
  10149. };
  10150. Camera.prototype.getViewMatrix = function (force) {
  10151. this._computedViewMatrix = this._computeViewMatrix(force);
  10152. if (!force && this._isSynchronizedViewMatrix()) {
  10153. return this._computedViewMatrix;
  10154. }
  10155. if (!this.parent || !this.parent.getWorldMatrix) {
  10156. this._globalPosition.copyFrom(this.position);
  10157. }
  10158. else {
  10159. if (!this._worldMatrix) {
  10160. this._worldMatrix = BABYLON.Matrix.Identity();
  10161. }
  10162. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10163. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10164. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10165. this._computedViewMatrix.invert();
  10166. this._markSyncedWithParent();
  10167. }
  10168. this._currentRenderId = this.getScene().getRenderId();
  10169. return this._computedViewMatrix;
  10170. };
  10171. Camera.prototype._computeViewMatrix = function (force) {
  10172. if (!force && this._isSynchronizedViewMatrix()) {
  10173. return this._computedViewMatrix;
  10174. }
  10175. this._computedViewMatrix = this._getViewMatrix();
  10176. this._currentRenderId = this.getScene().getRenderId();
  10177. return this._computedViewMatrix;
  10178. };
  10179. Camera.prototype.getProjectionMatrix = function (force) {
  10180. if (!force && this._isSynchronizedProjectionMatrix()) {
  10181. return this._projectionMatrix;
  10182. }
  10183. var engine = this.getEngine();
  10184. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10185. if (this.minZ <= 0) {
  10186. this.minZ = 0.1;
  10187. }
  10188. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10189. return this._projectionMatrix;
  10190. }
  10191. var halfWidth = engine.getRenderWidth() / 2.0;
  10192. var halfHeight = engine.getRenderHeight() / 2.0;
  10193. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10194. return this._projectionMatrix;
  10195. };
  10196. Camera.prototype.dispose = function () {
  10197. // Remove from scene
  10198. this.getScene().removeCamera(this);
  10199. while (this._rigCameras.length > 0) {
  10200. this._rigCameras.pop().dispose();
  10201. }
  10202. // Postprocesses
  10203. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10204. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10205. }
  10206. };
  10207. // ---- Camera rigs section ----
  10208. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10209. while (this._rigCameras.length > 0) {
  10210. this._rigCameras.pop().dispose();
  10211. }
  10212. this.cameraRigMode = mode;
  10213. this._cameraRigParams = {};
  10214. switch (this.cameraRigMode) {
  10215. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10216. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10217. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10218. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10219. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10220. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10221. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10222. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10223. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10224. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10225. break;
  10226. }
  10227. var postProcesses = new Array();
  10228. switch (this.cameraRigMode) {
  10229. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10230. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10231. this._rigCameras[0].isIntermediate = true;
  10232. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10233. postProcesses[1].onApply = function (effect) {
  10234. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10235. };
  10236. break;
  10237. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10238. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10239. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10240. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10241. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10242. var secondCamIndex = 1 - firstCamIndex;
  10243. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10244. this._rigCameras[firstCamIndex].isIntermediate = true;
  10245. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10246. break;
  10247. case Camera.RIG_MODE_VR:
  10248. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10249. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10250. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10251. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10252. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10253. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10254. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10255. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10256. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10257. if (metrics.compensateDistorsion) {
  10258. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10259. }
  10260. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10261. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10262. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10263. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10264. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10265. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10266. if (metrics.compensateDistorsion) {
  10267. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10268. }
  10269. break;
  10270. }
  10271. this._update();
  10272. };
  10273. Camera.prototype._getVRProjectionMatrix = function () {
  10274. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10275. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10276. return this._projectionMatrix;
  10277. };
  10278. Camera.prototype.setCameraRigParameter = function (name, value) {
  10279. this._cameraRigParams[name] = value;
  10280. //provisionnally:
  10281. if (name === "interaxialDistance") {
  10282. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10283. }
  10284. };
  10285. /**
  10286. * May needs to be overridden by children so sub has required properties to be copied
  10287. */
  10288. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10289. return null;
  10290. };
  10291. /**
  10292. * May needs to be overridden by children
  10293. */
  10294. Camera.prototype._updateRigCameras = function () {
  10295. for (var i = 0; i < this._rigCameras.length; i++) {
  10296. this._rigCameras[i].minZ = this.minZ;
  10297. this._rigCameras[i].maxZ = this.maxZ;
  10298. this._rigCameras[i].fov = this.fov;
  10299. }
  10300. // only update viewport when ANAGLYPH
  10301. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10302. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10303. }
  10304. };
  10305. // Statics
  10306. Camera._PERSPECTIVE_CAMERA = 0;
  10307. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10308. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10309. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10310. Camera._RIG_MODE_NONE = 0;
  10311. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10312. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10313. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10314. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10315. Camera._RIG_MODE_VR = 20;
  10316. return Camera;
  10317. })(BABYLON.Node);
  10318. BABYLON.Camera = Camera;
  10319. })(BABYLON || (BABYLON = {}));
  10320. var BABYLON;
  10321. (function (BABYLON) {
  10322. var TargetCamera = (function (_super) {
  10323. __extends(TargetCamera, _super);
  10324. function TargetCamera(name, position, scene) {
  10325. _super.call(this, name, position, scene);
  10326. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10327. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10328. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10329. this.speed = 2.0;
  10330. this.noRotationConstraint = false;
  10331. this.lockedTarget = null;
  10332. this._currentTarget = BABYLON.Vector3.Zero();
  10333. this._viewMatrix = BABYLON.Matrix.Zero();
  10334. this._camMatrix = BABYLON.Matrix.Zero();
  10335. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10336. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10337. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10338. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10339. this._lookAtTemp = BABYLON.Matrix.Zero();
  10340. this._tempMatrix = BABYLON.Matrix.Zero();
  10341. }
  10342. TargetCamera.prototype.getFrontPosition = function (distance) {
  10343. var direction = this.getTarget().subtract(this.position);
  10344. direction.normalize();
  10345. direction.scaleInPlace(distance);
  10346. return this.globalPosition.add(direction);
  10347. };
  10348. TargetCamera.prototype._getLockedTargetPosition = function () {
  10349. if (!this.lockedTarget) {
  10350. return null;
  10351. }
  10352. return this.lockedTarget.position || this.lockedTarget;
  10353. };
  10354. // Cache
  10355. TargetCamera.prototype._initCache = function () {
  10356. _super.prototype._initCache.call(this);
  10357. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10358. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10359. };
  10360. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10361. if (!ignoreParentClass) {
  10362. _super.prototype._updateCache.call(this);
  10363. }
  10364. var lockedTargetPosition = this._getLockedTargetPosition();
  10365. if (!lockedTargetPosition) {
  10366. this._cache.lockedTarget = null;
  10367. }
  10368. else {
  10369. if (!this._cache.lockedTarget) {
  10370. this._cache.lockedTarget = lockedTargetPosition.clone();
  10371. }
  10372. else {
  10373. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10374. }
  10375. }
  10376. this._cache.rotation.copyFrom(this.rotation);
  10377. };
  10378. // Synchronized
  10379. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10380. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10381. return false;
  10382. }
  10383. var lockedTargetPosition = this._getLockedTargetPosition();
  10384. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10385. && this._cache.rotation.equals(this.rotation);
  10386. };
  10387. // Methods
  10388. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10389. var engine = this.getEngine();
  10390. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10391. };
  10392. // Target
  10393. TargetCamera.prototype.setTarget = function (target) {
  10394. this.upVector.normalize();
  10395. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10396. this._camMatrix.invert();
  10397. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10398. var vDir = target.subtract(this.position);
  10399. if (vDir.x >= 0.0) {
  10400. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10401. }
  10402. else {
  10403. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10404. }
  10405. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10406. if (isNaN(this.rotation.x)) {
  10407. this.rotation.x = 0;
  10408. }
  10409. if (isNaN(this.rotation.y)) {
  10410. this.rotation.y = 0;
  10411. }
  10412. if (isNaN(this.rotation.z)) {
  10413. this.rotation.z = 0;
  10414. }
  10415. };
  10416. TargetCamera.prototype.getTarget = function () {
  10417. return this._currentTarget;
  10418. };
  10419. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10420. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10421. };
  10422. TargetCamera.prototype._updatePosition = function () {
  10423. this.position.addInPlace(this.cameraDirection);
  10424. };
  10425. TargetCamera.prototype._checkInputs = function () {
  10426. var needToMove = this._decideIfNeedsToMove();
  10427. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10428. // Move
  10429. if (needToMove) {
  10430. this._updatePosition();
  10431. }
  10432. // Rotate
  10433. if (needToRotate) {
  10434. this.rotation.x += this.cameraRotation.x;
  10435. this.rotation.y += this.cameraRotation.y;
  10436. if (!this.noRotationConstraint) {
  10437. var limit = (Math.PI / 2) * 0.95;
  10438. if (this.rotation.x > limit)
  10439. this.rotation.x = limit;
  10440. if (this.rotation.x < -limit)
  10441. this.rotation.x = -limit;
  10442. }
  10443. }
  10444. // Inertia
  10445. if (needToMove) {
  10446. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10447. this.cameraDirection.x = 0;
  10448. }
  10449. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10450. this.cameraDirection.y = 0;
  10451. }
  10452. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10453. this.cameraDirection.z = 0;
  10454. }
  10455. this.cameraDirection.scaleInPlace(this.inertia);
  10456. }
  10457. if (needToRotate) {
  10458. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10459. this.cameraRotation.x = 0;
  10460. }
  10461. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10462. this.cameraRotation.y = 0;
  10463. }
  10464. this.cameraRotation.scaleInPlace(this.inertia);
  10465. }
  10466. _super.prototype._checkInputs.call(this);
  10467. };
  10468. TargetCamera.prototype._getViewMatrix = function () {
  10469. if (!this.lockedTarget) {
  10470. // Compute
  10471. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10472. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10473. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10474. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10475. this._lookAtTemp.invert();
  10476. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10477. }
  10478. else {
  10479. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10480. }
  10481. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10482. // Computing target and final matrix
  10483. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10484. }
  10485. else {
  10486. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10487. }
  10488. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10489. return this._viewMatrix;
  10490. };
  10491. TargetCamera.prototype._getVRViewMatrix = function () {
  10492. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10493. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10494. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10495. // Computing target and final matrix
  10496. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10497. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10498. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10499. return this._viewMatrix;
  10500. };
  10501. /**
  10502. * @override
  10503. * Override Camera.createRigCamera
  10504. */
  10505. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10506. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10507. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10508. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10509. rigCamera._cameraRigParams = {};
  10510. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10511. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10512. }
  10513. return rigCamera;
  10514. }
  10515. return null;
  10516. };
  10517. /**
  10518. * @override
  10519. * Override Camera._updateRigCameras
  10520. */
  10521. TargetCamera.prototype._updateRigCameras = function () {
  10522. switch (this.cameraRigMode) {
  10523. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10524. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10525. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10526. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10527. case BABYLON.Camera.RIG_MODE_VR:
  10528. var camLeft = this._rigCameras[0];
  10529. var camRight = this._rigCameras[1];
  10530. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10531. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10532. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10533. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10534. camLeft.position.copyFrom(this.position);
  10535. camRight.position.copyFrom(this.position);
  10536. }
  10537. else {
  10538. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10539. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10540. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10541. camLeft.setTarget(this.getTarget());
  10542. camRight.setTarget(this.getTarget());
  10543. }
  10544. break;
  10545. }
  10546. _super.prototype._updateRigCameras.call(this);
  10547. };
  10548. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10549. if (!this._rigCamTransformMatrix) {
  10550. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10551. }
  10552. var target = this.getTarget();
  10553. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10554. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10555. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10556. };
  10557. return TargetCamera;
  10558. })(BABYLON.Camera);
  10559. BABYLON.TargetCamera = TargetCamera;
  10560. })(BABYLON || (BABYLON = {}));
  10561. var BABYLON;
  10562. (function (BABYLON) {
  10563. var FreeCamera = (function (_super) {
  10564. __extends(FreeCamera, _super);
  10565. function FreeCamera(name, position, scene) {
  10566. var _this = this;
  10567. _super.call(this, name, position, scene);
  10568. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10569. this.keysUp = [38];
  10570. this.keysDown = [40];
  10571. this.keysLeft = [37];
  10572. this.keysRight = [39];
  10573. this.checkCollisions = false;
  10574. this.applyGravity = false;
  10575. this.angularSensibility = 2000.0;
  10576. this._keys = [];
  10577. this._collider = new BABYLON.Collider();
  10578. this._needMoveForGravity = false;
  10579. this._oldPosition = BABYLON.Vector3.Zero();
  10580. this._diffPosition = BABYLON.Vector3.Zero();
  10581. this._newPosition = BABYLON.Vector3.Zero();
  10582. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10583. if (collidedMesh === void 0) { collidedMesh = null; }
  10584. //TODO move this to the collision coordinator!
  10585. if (_this.getScene().workerCollisions)
  10586. newPosition.multiplyInPlace(_this._collider.radius);
  10587. var updatePosition = function (newPos) {
  10588. _this._newPosition.copyFrom(newPos);
  10589. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10590. var oldPosition = _this.position.clone();
  10591. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10592. _this.position.addInPlace(_this._diffPosition);
  10593. if (_this.onCollide && collidedMesh) {
  10594. _this.onCollide(collidedMesh);
  10595. }
  10596. }
  10597. };
  10598. updatePosition(newPosition);
  10599. };
  10600. }
  10601. // Controls
  10602. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10603. var _this = this;
  10604. var previousPosition;
  10605. var engine = this.getEngine();
  10606. if (this._attachedElement) {
  10607. return;
  10608. }
  10609. this._attachedElement = element;
  10610. if (this._onMouseDown === undefined) {
  10611. this._onMouseDown = function (evt) {
  10612. previousPosition = {
  10613. x: evt.clientX,
  10614. y: evt.clientY
  10615. };
  10616. if (!noPreventDefault) {
  10617. evt.preventDefault();
  10618. }
  10619. };
  10620. this._onMouseUp = function (evt) {
  10621. previousPosition = null;
  10622. if (!noPreventDefault) {
  10623. evt.preventDefault();
  10624. }
  10625. };
  10626. this._onMouseOut = function (evt) {
  10627. previousPosition = null;
  10628. _this._keys = [];
  10629. if (!noPreventDefault) {
  10630. evt.preventDefault();
  10631. }
  10632. };
  10633. this._onMouseMove = function (evt) {
  10634. if (!previousPosition && !engine.isPointerLock) {
  10635. return;
  10636. }
  10637. var offsetX;
  10638. var offsetY;
  10639. if (!engine.isPointerLock) {
  10640. offsetX = evt.clientX - previousPosition.x;
  10641. offsetY = evt.clientY - previousPosition.y;
  10642. }
  10643. else {
  10644. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10645. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10646. }
  10647. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10648. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10649. previousPosition = {
  10650. x: evt.clientX,
  10651. y: evt.clientY
  10652. };
  10653. if (!noPreventDefault) {
  10654. evt.preventDefault();
  10655. }
  10656. };
  10657. this._onKeyDown = function (evt) {
  10658. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10659. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10660. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10661. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10662. var index = _this._keys.indexOf(evt.keyCode);
  10663. if (index === -1) {
  10664. _this._keys.push(evt.keyCode);
  10665. }
  10666. if (!noPreventDefault) {
  10667. evt.preventDefault();
  10668. }
  10669. }
  10670. };
  10671. this._onKeyUp = function (evt) {
  10672. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10673. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10674. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10675. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10676. var index = _this._keys.indexOf(evt.keyCode);
  10677. if (index >= 0) {
  10678. _this._keys.splice(index, 1);
  10679. }
  10680. if (!noPreventDefault) {
  10681. evt.preventDefault();
  10682. }
  10683. }
  10684. };
  10685. this._onLostFocus = function () {
  10686. _this._keys = [];
  10687. };
  10688. this._reset = function () {
  10689. _this._keys = [];
  10690. previousPosition = null;
  10691. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10692. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10693. };
  10694. }
  10695. element.addEventListener("mousedown", this._onMouseDown, false);
  10696. element.addEventListener("mouseup", this._onMouseUp, false);
  10697. element.addEventListener("mouseout", this._onMouseOut, false);
  10698. element.addEventListener("mousemove", this._onMouseMove, false);
  10699. BABYLON.Tools.RegisterTopRootEvents([
  10700. { name: "keydown", handler: this._onKeyDown },
  10701. { name: "keyup", handler: this._onKeyUp },
  10702. { name: "blur", handler: this._onLostFocus }
  10703. ]);
  10704. };
  10705. FreeCamera.prototype.detachControl = function (element) {
  10706. if (this._attachedElement != element) {
  10707. return;
  10708. }
  10709. element.removeEventListener("mousedown", this._onMouseDown);
  10710. element.removeEventListener("mouseup", this._onMouseUp);
  10711. element.removeEventListener("mouseout", this._onMouseOut);
  10712. element.removeEventListener("mousemove", this._onMouseMove);
  10713. BABYLON.Tools.UnregisterTopRootEvents([
  10714. { name: "keydown", handler: this._onKeyDown },
  10715. { name: "keyup", handler: this._onKeyUp },
  10716. { name: "blur", handler: this._onLostFocus }
  10717. ]);
  10718. this._attachedElement = null;
  10719. if (this._reset) {
  10720. this._reset();
  10721. }
  10722. };
  10723. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10724. var globalPosition;
  10725. if (this.parent) {
  10726. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10727. }
  10728. else {
  10729. globalPosition = this.position;
  10730. }
  10731. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10732. this._collider.radius = this.ellipsoid;
  10733. //add gravity to the velocity to prevent the dual-collision checking
  10734. if (this.applyGravity) {
  10735. velocity.addInPlace(this.getScene().gravity);
  10736. }
  10737. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10738. };
  10739. FreeCamera.prototype._checkInputs = function () {
  10740. if (!this._localDirection) {
  10741. this._localDirection = BABYLON.Vector3.Zero();
  10742. this._transformedDirection = BABYLON.Vector3.Zero();
  10743. }
  10744. // Keyboard
  10745. for (var index = 0; index < this._keys.length; index++) {
  10746. var keyCode = this._keys[index];
  10747. var speed = this._computeLocalCameraSpeed();
  10748. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10749. this._localDirection.copyFromFloats(-speed, 0, 0);
  10750. }
  10751. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10752. this._localDirection.copyFromFloats(0, 0, speed);
  10753. }
  10754. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10755. this._localDirection.copyFromFloats(speed, 0, 0);
  10756. }
  10757. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10758. this._localDirection.copyFromFloats(0, 0, -speed);
  10759. }
  10760. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10761. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10762. this.cameraDirection.addInPlace(this._transformedDirection);
  10763. }
  10764. _super.prototype._checkInputs.call(this);
  10765. };
  10766. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10767. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10768. };
  10769. FreeCamera.prototype._updatePosition = function () {
  10770. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10771. this._collideWithWorld(this.cameraDirection);
  10772. }
  10773. else {
  10774. this.position.addInPlace(this.cameraDirection);
  10775. }
  10776. };
  10777. return FreeCamera;
  10778. })(BABYLON.TargetCamera);
  10779. BABYLON.FreeCamera = FreeCamera;
  10780. })(BABYLON || (BABYLON = {}));
  10781. var BABYLON;
  10782. (function (BABYLON) {
  10783. var FollowCamera = (function (_super) {
  10784. __extends(FollowCamera, _super);
  10785. function FollowCamera(name, position, scene) {
  10786. _super.call(this, name, position, scene);
  10787. this.radius = 12;
  10788. this.rotationOffset = 0;
  10789. this.heightOffset = 4;
  10790. this.cameraAcceleration = 0.05;
  10791. this.maxCameraSpeed = 20;
  10792. }
  10793. FollowCamera.prototype.getRadians = function (degrees) {
  10794. return degrees * Math.PI / 180;
  10795. };
  10796. FollowCamera.prototype.follow = function (cameraTarget) {
  10797. if (!cameraTarget)
  10798. return;
  10799. var yRotation;
  10800. if (cameraTarget.rotationQuaternion) {
  10801. var rotMatrix = new BABYLON.Matrix();
  10802. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10803. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10804. }
  10805. else {
  10806. yRotation = cameraTarget.rotation.y;
  10807. }
  10808. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10809. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10810. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10811. var dx = targetX - this.position.x;
  10812. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10813. var dz = (targetZ) - this.position.z;
  10814. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10815. var vy = dy * this.cameraAcceleration;
  10816. var vz = dz * this.cameraAcceleration * 2;
  10817. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10818. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10819. }
  10820. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10821. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10822. }
  10823. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10824. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10825. }
  10826. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10827. this.setTarget(cameraTarget.position);
  10828. };
  10829. FollowCamera.prototype._checkInputs = function () {
  10830. _super.prototype._checkInputs.call(this);
  10831. this.follow(this.target);
  10832. };
  10833. return FollowCamera;
  10834. })(BABYLON.TargetCamera);
  10835. BABYLON.FollowCamera = FollowCamera;
  10836. var ArcFollowCamera = (function (_super) {
  10837. __extends(ArcFollowCamera, _super);
  10838. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10839. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10840. this.alpha = alpha;
  10841. this.beta = beta;
  10842. this.radius = radius;
  10843. this.target = target;
  10844. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10845. this.follow();
  10846. }
  10847. ArcFollowCamera.prototype.follow = function () {
  10848. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10849. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10850. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10851. this.position = this.target.position.add(this._cartesianCoordinates);
  10852. this.setTarget(this.target.position);
  10853. };
  10854. ArcFollowCamera.prototype._checkInputs = function () {
  10855. _super.prototype._checkInputs.call(this);
  10856. this.follow();
  10857. };
  10858. return ArcFollowCamera;
  10859. })(BABYLON.TargetCamera);
  10860. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10861. })(BABYLON || (BABYLON = {}));
  10862. var BABYLON;
  10863. (function (BABYLON) {
  10864. // We're mainly based on the logic defined into the FreeCamera code
  10865. var TouchCamera = (function (_super) {
  10866. __extends(TouchCamera, _super);
  10867. function TouchCamera(name, position, scene) {
  10868. _super.call(this, name, position, scene);
  10869. this._offsetX = null;
  10870. this._offsetY = null;
  10871. this._pointerCount = 0;
  10872. this._pointerPressed = [];
  10873. this.angularSensibility = 200000.0;
  10874. this.moveSensibility = 500.0;
  10875. }
  10876. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10877. var _this = this;
  10878. var previousPosition;
  10879. if (this._attachedCanvas) {
  10880. return;
  10881. }
  10882. this._attachedCanvas = canvas;
  10883. if (this._onPointerDown === undefined) {
  10884. this._onPointerDown = function (evt) {
  10885. if (!noPreventDefault) {
  10886. evt.preventDefault();
  10887. }
  10888. _this._pointerPressed.push(evt.pointerId);
  10889. if (_this._pointerPressed.length !== 1) {
  10890. return;
  10891. }
  10892. previousPosition = {
  10893. x: evt.clientX,
  10894. y: evt.clientY
  10895. };
  10896. };
  10897. this._onPointerUp = function (evt) {
  10898. if (!noPreventDefault) {
  10899. evt.preventDefault();
  10900. }
  10901. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10902. if (index === -1) {
  10903. return;
  10904. }
  10905. _this._pointerPressed.splice(index, 1);
  10906. if (index != 0) {
  10907. return;
  10908. }
  10909. previousPosition = null;
  10910. _this._offsetX = null;
  10911. _this._offsetY = null;
  10912. };
  10913. this._onPointerMove = function (evt) {
  10914. if (!noPreventDefault) {
  10915. evt.preventDefault();
  10916. }
  10917. if (!previousPosition) {
  10918. return;
  10919. }
  10920. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10921. if (index != 0) {
  10922. return;
  10923. }
  10924. _this._offsetX = evt.clientX - previousPosition.x;
  10925. _this._offsetY = -(evt.clientY - previousPosition.y);
  10926. };
  10927. this._onLostFocus = function () {
  10928. _this._offsetX = null;
  10929. _this._offsetY = null;
  10930. };
  10931. }
  10932. canvas.addEventListener("pointerdown", this._onPointerDown);
  10933. canvas.addEventListener("pointerup", this._onPointerUp);
  10934. canvas.addEventListener("pointerout", this._onPointerUp);
  10935. canvas.addEventListener("pointermove", this._onPointerMove);
  10936. BABYLON.Tools.RegisterTopRootEvents([
  10937. { name: "blur", handler: this._onLostFocus }
  10938. ]);
  10939. };
  10940. TouchCamera.prototype.detachControl = function (canvas) {
  10941. if (this._attachedCanvas != canvas) {
  10942. return;
  10943. }
  10944. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10945. canvas.removeEventListener("pointerup", this._onPointerUp);
  10946. canvas.removeEventListener("pointerout", this._onPointerUp);
  10947. canvas.removeEventListener("pointermove", this._onPointerMove);
  10948. BABYLON.Tools.UnregisterTopRootEvents([
  10949. { name: "blur", handler: this._onLostFocus }
  10950. ]);
  10951. this._attachedCanvas = null;
  10952. };
  10953. TouchCamera.prototype._checkInputs = function () {
  10954. if (this._offsetX) {
  10955. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10956. if (this._pointerPressed.length > 1) {
  10957. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10958. }
  10959. else {
  10960. var speed = this._computeLocalCameraSpeed();
  10961. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10962. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10963. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10964. }
  10965. }
  10966. _super.prototype._checkInputs.call(this);
  10967. };
  10968. return TouchCamera;
  10969. })(BABYLON.FreeCamera);
  10970. BABYLON.TouchCamera = TouchCamera;
  10971. })(BABYLON || (BABYLON = {}));
  10972. var BABYLON;
  10973. (function (BABYLON) {
  10974. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10975. var ArcRotateCamera = (function (_super) {
  10976. __extends(ArcRotateCamera, _super);
  10977. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10978. var _this = this;
  10979. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10980. this.alpha = alpha;
  10981. this.beta = beta;
  10982. this.radius = radius;
  10983. this.target = target;
  10984. this.inertialAlphaOffset = 0;
  10985. this.inertialBetaOffset = 0;
  10986. this.inertialRadiusOffset = 0;
  10987. this.lowerAlphaLimit = null;
  10988. this.upperAlphaLimit = null;
  10989. this.lowerBetaLimit = 0.01;
  10990. this.upperBetaLimit = Math.PI;
  10991. this.lowerRadiusLimit = null;
  10992. this.upperRadiusLimit = null;
  10993. this.angularSensibilityX = 1000.0;
  10994. this.angularSensibilityY = 1000.0;
  10995. this.wheelPrecision = 3.0;
  10996. this.pinchPrecision = 2.0;
  10997. this.panningSensibility = 50.0;
  10998. this.inertialPanningX = 0;
  10999. this.inertialPanningY = 0;
  11000. this.keysUp = [38];
  11001. this.keysDown = [40];
  11002. this.keysLeft = [37];
  11003. this.keysRight = [39];
  11004. this.zoomOnFactor = 1;
  11005. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11006. this.pinchInwards = true;
  11007. this.allowUpsideDown = true;
  11008. this._keys = [];
  11009. this._viewMatrix = new BABYLON.Matrix();
  11010. this._isRightClick = false;
  11011. this._isCtrlPushed = false;
  11012. this.checkCollisions = false;
  11013. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11014. this._collider = new BABYLON.Collider();
  11015. this._previousPosition = BABYLON.Vector3.Zero();
  11016. this._collisionVelocity = BABYLON.Vector3.Zero();
  11017. this._newPosition = BABYLON.Vector3.Zero();
  11018. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11019. if (collidedMesh === void 0) { collidedMesh = null; }
  11020. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11021. newPosition.multiplyInPlace(_this._collider.radius);
  11022. }
  11023. if (!collidedMesh) {
  11024. _this._previousPosition.copyFrom(_this.position);
  11025. }
  11026. else {
  11027. _this.setPosition(_this.position);
  11028. if (_this.onCollide) {
  11029. _this.onCollide(collidedMesh);
  11030. }
  11031. }
  11032. // Recompute because of constraints
  11033. var cosa = Math.cos(_this.alpha);
  11034. var sina = Math.sin(_this.alpha);
  11035. var cosb = Math.cos(_this.beta);
  11036. var sinb = Math.sin(_this.beta);
  11037. var target = _this._getTargetPosition();
  11038. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11039. _this.position.copyFrom(_this._newPosition);
  11040. var up = _this.upVector;
  11041. if (_this.allowUpsideDown && _this.beta < 0) {
  11042. var up = up.clone();
  11043. up = up.negate();
  11044. }
  11045. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11046. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11047. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11048. _this._collisionTriggered = false;
  11049. };
  11050. if (!this.target) {
  11051. this.target = BABYLON.Vector3.Zero();
  11052. }
  11053. this.getViewMatrix();
  11054. }
  11055. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11056. //deprecated angularSensibility support
  11057. get: function () {
  11058. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11059. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11060. },
  11061. //deprecated angularSensibility support
  11062. set: function (value) {
  11063. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11064. this.angularSensibilityX = value;
  11065. this.angularSensibilityY = value;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. ArcRotateCamera.prototype._getTargetPosition = function () {
  11071. return this.target.position || this.target;
  11072. };
  11073. // Cache
  11074. ArcRotateCamera.prototype._initCache = function () {
  11075. _super.prototype._initCache.call(this);
  11076. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11077. this._cache.alpha = undefined;
  11078. this._cache.beta = undefined;
  11079. this._cache.radius = undefined;
  11080. this._cache.targetScreenOffset = undefined;
  11081. };
  11082. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11083. if (!ignoreParentClass) {
  11084. _super.prototype._updateCache.call(this);
  11085. }
  11086. this._cache.target.copyFrom(this._getTargetPosition());
  11087. this._cache.alpha = this.alpha;
  11088. this._cache.beta = this.beta;
  11089. this._cache.radius = this.radius;
  11090. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11091. };
  11092. // Synchronized
  11093. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11094. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11095. return false;
  11096. return this._cache.target.equals(this._getTargetPosition())
  11097. && this._cache.alpha === this.alpha
  11098. && this._cache.beta === this.beta
  11099. && this._cache.radius === this.radius
  11100. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11101. };
  11102. // Methods
  11103. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11104. var _this = this;
  11105. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11106. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11107. var previousPinchDistance = 0;
  11108. var pointers = new BABYLON.SmartCollection();
  11109. if (this._attachedElement) {
  11110. return;
  11111. }
  11112. this._attachedElement = element;
  11113. var engine = this.getEngine();
  11114. if (this._onPointerDown === undefined) {
  11115. this._onPointerDown = function (evt) {
  11116. // Manage panning with right click
  11117. _this._isRightClick = evt.button === 2 ? true : false;
  11118. // manage pointers
  11119. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11120. cacheSoloPointer = pointers.item(evt.pointerId);
  11121. if (!noPreventDefault) {
  11122. evt.preventDefault();
  11123. }
  11124. };
  11125. this._onPointerUp = function (evt) {
  11126. cacheSoloPointer = null;
  11127. previousPinchDistance = 0;
  11128. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11129. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11130. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11131. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11132. pointers.empty();
  11133. if (!noPreventDefault) {
  11134. evt.preventDefault();
  11135. }
  11136. };
  11137. this._onContextMenu = function (evt) {
  11138. evt.preventDefault();
  11139. };
  11140. this._onPointerMove = function (evt) {
  11141. if (!noPreventDefault) {
  11142. evt.preventDefault();
  11143. }
  11144. switch (pointers.count) {
  11145. case 1:
  11146. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11147. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11148. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11149. }
  11150. else {
  11151. var offsetX = evt.clientX - cacheSoloPointer.x;
  11152. var offsetY = evt.clientY - cacheSoloPointer.y;
  11153. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11154. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11155. }
  11156. cacheSoloPointer.x = evt.clientX;
  11157. cacheSoloPointer.y = evt.clientY;
  11158. break;
  11159. case 2:
  11160. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11161. pointers.item(evt.pointerId).x = evt.clientX;
  11162. pointers.item(evt.pointerId).y = evt.clientY;
  11163. var direction = _this.pinchInwards ? 1 : -1;
  11164. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11165. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11166. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11167. if (previousPinchDistance === 0) {
  11168. previousPinchDistance = pinchSquaredDistance;
  11169. return;
  11170. }
  11171. if (pinchSquaredDistance !== previousPinchDistance) {
  11172. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11173. previousPinchDistance = pinchSquaredDistance;
  11174. }
  11175. break;
  11176. default:
  11177. if (pointers.item(evt.pointerId)) {
  11178. pointers.item(evt.pointerId).x = evt.clientX;
  11179. pointers.item(evt.pointerId).y = evt.clientY;
  11180. }
  11181. }
  11182. };
  11183. this._onMouseMove = function (evt) {
  11184. if (!engine.isPointerLock) {
  11185. return;
  11186. }
  11187. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11188. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11189. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11190. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11191. if (!noPreventDefault) {
  11192. evt.preventDefault();
  11193. }
  11194. };
  11195. this._wheel = function (event) {
  11196. var delta = 0;
  11197. if (event.wheelDelta) {
  11198. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11199. }
  11200. else if (event.detail) {
  11201. delta = -event.detail / _this.wheelPrecision;
  11202. }
  11203. if (delta)
  11204. _this.inertialRadiusOffset += delta;
  11205. if (event.preventDefault) {
  11206. if (!noPreventDefault) {
  11207. event.preventDefault();
  11208. }
  11209. }
  11210. };
  11211. this._onKeyDown = function (evt) {
  11212. _this._isCtrlPushed = evt.ctrlKey;
  11213. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11214. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11215. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11216. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11217. var index = _this._keys.indexOf(evt.keyCode);
  11218. if (index === -1) {
  11219. _this._keys.push(evt.keyCode);
  11220. }
  11221. if (evt.preventDefault) {
  11222. if (!noPreventDefault) {
  11223. evt.preventDefault();
  11224. }
  11225. }
  11226. }
  11227. };
  11228. this._onKeyUp = function (evt) {
  11229. _this._isCtrlPushed = evt.ctrlKey;
  11230. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11231. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11232. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11233. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11234. var index = _this._keys.indexOf(evt.keyCode);
  11235. if (index >= 0) {
  11236. _this._keys.splice(index, 1);
  11237. }
  11238. if (evt.preventDefault) {
  11239. if (!noPreventDefault) {
  11240. evt.preventDefault();
  11241. }
  11242. }
  11243. }
  11244. };
  11245. this._onLostFocus = function () {
  11246. _this._keys = [];
  11247. pointers.empty();
  11248. previousPinchDistance = 0;
  11249. cacheSoloPointer = null;
  11250. };
  11251. this._onGestureStart = function (e) {
  11252. if (window.MSGesture === undefined) {
  11253. return;
  11254. }
  11255. if (!_this._MSGestureHandler) {
  11256. _this._MSGestureHandler = new MSGesture();
  11257. _this._MSGestureHandler.target = element;
  11258. }
  11259. _this._MSGestureHandler.addPointer(e.pointerId);
  11260. };
  11261. this._onGesture = function (e) {
  11262. _this.radius *= e.scale;
  11263. if (e.preventDefault) {
  11264. if (!noPreventDefault) {
  11265. e.stopPropagation();
  11266. e.preventDefault();
  11267. }
  11268. }
  11269. };
  11270. this._reset = function () {
  11271. _this._keys = [];
  11272. _this.inertialAlphaOffset = 0;
  11273. _this.inertialBetaOffset = 0;
  11274. _this.inertialRadiusOffset = 0;
  11275. pointers.empty();
  11276. previousPinchDistance = 0;
  11277. cacheSoloPointer = null;
  11278. };
  11279. }
  11280. if (!useCtrlForPanning) {
  11281. element.addEventListener("contextmenu", this._onContextMenu, false);
  11282. }
  11283. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11284. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11285. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11286. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11287. element.addEventListener("mousemove", this._onMouseMove, false);
  11288. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11289. element.addEventListener("MSGestureChange", this._onGesture, false);
  11290. element.addEventListener('mousewheel', this._wheel, false);
  11291. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11292. BABYLON.Tools.RegisterTopRootEvents([
  11293. { name: "keydown", handler: this._onKeyDown },
  11294. { name: "keyup", handler: this._onKeyUp },
  11295. { name: "blur", handler: this._onLostFocus }
  11296. ]);
  11297. };
  11298. ArcRotateCamera.prototype.detachControl = function (element) {
  11299. if (this._attachedElement !== element) {
  11300. return;
  11301. }
  11302. element.removeEventListener("contextmenu", this._onContextMenu);
  11303. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11304. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11305. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11306. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11307. element.removeEventListener("mousemove", this._onMouseMove);
  11308. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11309. element.removeEventListener("MSGestureChange", this._onGesture);
  11310. element.removeEventListener('mousewheel', this._wheel);
  11311. element.removeEventListener('DOMMouseScroll', this._wheel);
  11312. BABYLON.Tools.UnregisterTopRootEvents([
  11313. { name: "keydown", handler: this._onKeyDown },
  11314. { name: "keyup", handler: this._onKeyUp },
  11315. { name: "blur", handler: this._onLostFocus }
  11316. ]);
  11317. this._MSGestureHandler = null;
  11318. this._attachedElement = null;
  11319. if (this._reset) {
  11320. this._reset();
  11321. }
  11322. };
  11323. ArcRotateCamera.prototype._checkInputs = function () {
  11324. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11325. if (this._collisionTriggered) {
  11326. return;
  11327. }
  11328. // Keyboard
  11329. for (var index = 0; index < this._keys.length; index++) {
  11330. var keyCode = this._keys[index];
  11331. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11332. this.inertialAlphaOffset -= 0.01;
  11333. }
  11334. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11335. this.inertialBetaOffset -= 0.01;
  11336. }
  11337. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11338. this.inertialAlphaOffset += 0.01;
  11339. }
  11340. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11341. this.inertialBetaOffset += 0.01;
  11342. }
  11343. }
  11344. // Inertia
  11345. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11346. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11347. this.beta += this.inertialBetaOffset;
  11348. this.radius -= this.inertialRadiusOffset;
  11349. this.inertialAlphaOffset *= this.inertia;
  11350. this.inertialBetaOffset *= this.inertia;
  11351. this.inertialRadiusOffset *= this.inertia;
  11352. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11353. this.inertialAlphaOffset = 0;
  11354. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11355. this.inertialBetaOffset = 0;
  11356. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11357. this.inertialRadiusOffset = 0;
  11358. }
  11359. // Panning inertia
  11360. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11361. if (!this._localDirection) {
  11362. this._localDirection = BABYLON.Vector3.Zero();
  11363. this._transformedDirection = BABYLON.Vector3.Zero();
  11364. }
  11365. this.inertialPanningX *= this.inertia;
  11366. this.inertialPanningY *= this.inertia;
  11367. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11368. this.inertialPanningX = 0;
  11369. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11370. this.inertialPanningY = 0;
  11371. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11372. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11373. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11374. this.target.addInPlace(this._transformedDirection);
  11375. }
  11376. // Limits
  11377. this._checkLimits();
  11378. _super.prototype._checkInputs.call(this);
  11379. };
  11380. ArcRotateCamera.prototype._checkLimits = function () {
  11381. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11382. if (this.allowUpsideDown && this.beta > Math.PI) {
  11383. this.beta = this.beta - (2 * Math.PI);
  11384. }
  11385. }
  11386. else {
  11387. if (this.beta < this.lowerBetaLimit) {
  11388. this.beta = this.lowerBetaLimit;
  11389. }
  11390. }
  11391. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11392. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11393. this.beta = this.beta + (2 * Math.PI);
  11394. }
  11395. }
  11396. else {
  11397. if (this.beta > this.upperBetaLimit) {
  11398. this.beta = this.upperBetaLimit;
  11399. }
  11400. }
  11401. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11402. this.alpha = this.lowerAlphaLimit;
  11403. }
  11404. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11405. this.alpha = this.upperAlphaLimit;
  11406. }
  11407. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11408. this.radius = this.lowerRadiusLimit;
  11409. }
  11410. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11411. this.radius = this.upperRadiusLimit;
  11412. }
  11413. };
  11414. ArcRotateCamera.prototype.setPosition = function (position) {
  11415. var radiusv3 = position.subtract(this._getTargetPosition());
  11416. this.radius = radiusv3.length();
  11417. // Alpha
  11418. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11419. if (radiusv3.z < 0) {
  11420. this.alpha = 2 * Math.PI - this.alpha;
  11421. }
  11422. // Beta
  11423. this.beta = Math.acos(radiusv3.y / this.radius);
  11424. this._checkLimits();
  11425. };
  11426. ArcRotateCamera.prototype._getViewMatrix = function () {
  11427. // Compute
  11428. var cosa = Math.cos(this.alpha);
  11429. var sina = Math.sin(this.alpha);
  11430. var cosb = Math.cos(this.beta);
  11431. var sinb = Math.sin(this.beta);
  11432. var target = this._getTargetPosition();
  11433. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11434. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11435. this._collider.radius = this.collisionRadius;
  11436. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11437. this._collisionTriggered = true;
  11438. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11439. }
  11440. else {
  11441. this.position.copyFrom(this._newPosition);
  11442. var up = this.upVector;
  11443. if (this.allowUpsideDown && this.beta < 0) {
  11444. var up = up.clone();
  11445. up = up.negate();
  11446. }
  11447. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11448. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11449. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11450. }
  11451. return this._viewMatrix;
  11452. };
  11453. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11454. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11455. meshes = meshes || this.getScene().meshes;
  11456. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11457. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11458. this.radius = distance * this.zoomOnFactor;
  11459. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11460. };
  11461. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11462. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11463. var meshesOrMinMaxVector;
  11464. var distance;
  11465. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11466. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11467. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11468. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11469. }
  11470. else {
  11471. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11472. distance = meshesOrMinMaxVectorAndDistance.distance;
  11473. }
  11474. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11475. if (!doNotUpdateMaxZ) {
  11476. this.maxZ = distance * 2;
  11477. }
  11478. };
  11479. /**
  11480. * @override
  11481. * Override Camera.createRigCamera
  11482. */
  11483. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11484. switch (this.cameraRigMode) {
  11485. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11486. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11487. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11488. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11489. case BABYLON.Camera.RIG_MODE_VR:
  11490. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11491. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11492. }
  11493. };
  11494. /**
  11495. * @override
  11496. * Override Camera._updateRigCameras
  11497. */
  11498. ArcRotateCamera.prototype._updateRigCameras = function () {
  11499. switch (this.cameraRigMode) {
  11500. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11501. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11503. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11504. case BABYLON.Camera.RIG_MODE_VR:
  11505. var camLeft = this._rigCameras[0];
  11506. var camRight = this._rigCameras[1];
  11507. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11508. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11509. camLeft.beta = camRight.beta = this.beta;
  11510. camLeft.radius = camRight.radius = this.radius;
  11511. break;
  11512. }
  11513. _super.prototype._updateRigCameras.call(this);
  11514. };
  11515. return ArcRotateCamera;
  11516. })(BABYLON.TargetCamera);
  11517. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11518. })(BABYLON || (BABYLON = {}));
  11519. var BABYLON;
  11520. (function (BABYLON) {
  11521. // We're mainly based on the logic defined into the FreeCamera code
  11522. var DeviceOrientationCamera = (function (_super) {
  11523. __extends(DeviceOrientationCamera, _super);
  11524. function DeviceOrientationCamera(name, position, scene) {
  11525. var _this = this;
  11526. _super.call(this, name, position, scene);
  11527. this._offsetX = null;
  11528. this._offsetY = null;
  11529. this._orientationGamma = 0;
  11530. this._orientationBeta = 0;
  11531. this._initialOrientationGamma = 0;
  11532. this._initialOrientationBeta = 0;
  11533. this.angularSensibility = 10000.0;
  11534. this.moveSensibility = 50.0;
  11535. window.addEventListener("resize", function () {
  11536. _this._initialOrientationGamma = null;
  11537. }, false);
  11538. }
  11539. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11540. var _this = this;
  11541. if (this._attachedCanvas) {
  11542. return;
  11543. }
  11544. this._attachedCanvas = canvas;
  11545. if (!this._orientationChanged) {
  11546. this._orientationChanged = function (evt) {
  11547. if (!_this._initialOrientationGamma) {
  11548. _this._initialOrientationGamma = evt.gamma;
  11549. _this._initialOrientationBeta = evt.beta;
  11550. }
  11551. _this._orientationGamma = evt.gamma;
  11552. _this._orientationBeta = evt.beta;
  11553. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11554. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11555. };
  11556. }
  11557. window.addEventListener("deviceorientation", this._orientationChanged);
  11558. };
  11559. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11560. if (this._attachedCanvas != canvas) {
  11561. return;
  11562. }
  11563. window.removeEventListener("deviceorientation", this._orientationChanged);
  11564. this._attachedCanvas = null;
  11565. this._orientationGamma = 0;
  11566. this._orientationBeta = 0;
  11567. this._initialOrientationGamma = 0;
  11568. this._initialOrientationBeta = 0;
  11569. };
  11570. DeviceOrientationCamera.prototype._checkInputs = function () {
  11571. if (!this._offsetX) {
  11572. return;
  11573. }
  11574. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11575. var speed = this._computeLocalCameraSpeed();
  11576. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11577. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11578. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11579. _super.prototype._checkInputs.call(this);
  11580. };
  11581. return DeviceOrientationCamera;
  11582. })(BABYLON.FreeCamera);
  11583. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11584. })(BABYLON || (BABYLON = {}));
  11585. var BABYLON;
  11586. (function (BABYLON) {
  11587. var Gamepads = (function () {
  11588. function Gamepads(ongamedpadconnected) {
  11589. var _this = this;
  11590. this.babylonGamepads = [];
  11591. this.oneGamepadConnected = false;
  11592. this.isMonitoring = false;
  11593. this.gamepadEventSupported = 'GamepadEvent' in window;
  11594. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11595. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11596. 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=";
  11597. this._callbackGamepadConnected = ongamedpadconnected;
  11598. if (this.gamepadSupportAvailable) {
  11599. // Checking if the gamepad connected event is supported (like in Firefox)
  11600. if (this.gamepadEventSupported) {
  11601. window.addEventListener('gamepadconnected', function (evt) {
  11602. _this._onGamepadConnected(evt);
  11603. }, false);
  11604. window.addEventListener('gamepaddisconnected', function (evt) {
  11605. _this._onGamepadDisconnected(evt);
  11606. }, false);
  11607. }
  11608. else {
  11609. this._startMonitoringGamepads();
  11610. }
  11611. if (!this.oneGamepadConnected) {
  11612. this._insertGamepadDOMInstructions();
  11613. }
  11614. }
  11615. else {
  11616. this._insertGamepadDOMNotSupported();
  11617. }
  11618. }
  11619. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11620. Gamepads.gamepadDOMInfo = document.createElement("div");
  11621. var buttonAImage = document.createElement("img");
  11622. buttonAImage.src = this.buttonADataURL;
  11623. var spanMessage = document.createElement("span");
  11624. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11625. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11626. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11627. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11628. Gamepads.gamepadDOMInfo.style.width = "100%";
  11629. Gamepads.gamepadDOMInfo.style.height = "48px";
  11630. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11631. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11632. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11633. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11634. buttonAImage.style.position = "relative";
  11635. buttonAImage.style.bottom = "8px";
  11636. spanMessage.style.position = "relative";
  11637. spanMessage.style.fontSize = "32px";
  11638. spanMessage.style.bottom = "32px";
  11639. spanMessage.style.color = "green";
  11640. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11641. };
  11642. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11643. Gamepads.gamepadDOMInfo = document.createElement("div");
  11644. var spanMessage = document.createElement("span");
  11645. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11646. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11647. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11648. Gamepads.gamepadDOMInfo.style.width = "100%";
  11649. Gamepads.gamepadDOMInfo.style.height = "40px";
  11650. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11651. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11652. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11653. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11654. spanMessage.style.position = "relative";
  11655. spanMessage.style.fontSize = "32px";
  11656. spanMessage.style.color = "red";
  11657. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11658. };
  11659. Gamepads.prototype.dispose = function () {
  11660. if (Gamepads.gamepadDOMInfo) {
  11661. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11662. }
  11663. };
  11664. Gamepads.prototype._onGamepadConnected = function (evt) {
  11665. var newGamepad = this._addNewGamepad(evt.gamepad);
  11666. if (this._callbackGamepadConnected)
  11667. this._callbackGamepadConnected(newGamepad);
  11668. this._startMonitoringGamepads();
  11669. };
  11670. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11671. if (!this.oneGamepadConnected) {
  11672. this.oneGamepadConnected = true;
  11673. if (Gamepads.gamepadDOMInfo) {
  11674. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11675. Gamepads.gamepadDOMInfo = null;
  11676. }
  11677. }
  11678. var newGamepad;
  11679. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11680. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11681. }
  11682. else {
  11683. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11684. }
  11685. this.babylonGamepads.push(newGamepad);
  11686. return newGamepad;
  11687. };
  11688. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11689. // Remove the gamepad from the list of gamepads to monitor.
  11690. for (var i in this.babylonGamepads) {
  11691. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11692. this.babylonGamepads.splice(i, 1);
  11693. break;
  11694. }
  11695. }
  11696. // If no gamepads are left, stop the polling loop.
  11697. if (this.babylonGamepads.length == 0) {
  11698. this._stopMonitoringGamepads();
  11699. }
  11700. };
  11701. Gamepads.prototype._startMonitoringGamepads = function () {
  11702. if (!this.isMonitoring) {
  11703. this.isMonitoring = true;
  11704. this._checkGamepadsStatus();
  11705. }
  11706. };
  11707. Gamepads.prototype._stopMonitoringGamepads = function () {
  11708. this.isMonitoring = false;
  11709. };
  11710. Gamepads.prototype._checkGamepadsStatus = function () {
  11711. var _this = this;
  11712. // updating gamepad objects
  11713. this._updateGamepadObjects();
  11714. for (var i in this.babylonGamepads) {
  11715. this.babylonGamepads[i].update();
  11716. }
  11717. if (this.isMonitoring) {
  11718. if (window.requestAnimationFrame) {
  11719. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11720. }
  11721. else if (window.mozRequestAnimationFrame) {
  11722. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11723. }
  11724. else if (window.webkitRequestAnimationFrame) {
  11725. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11726. }
  11727. }
  11728. };
  11729. // This function is called only on Chrome, which does not yet support
  11730. // connection/disconnection events, but requires you to monitor
  11731. // an array for changes.
  11732. Gamepads.prototype._updateGamepadObjects = function () {
  11733. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11734. for (var i = 0; i < gamepads.length; i++) {
  11735. if (gamepads[i]) {
  11736. if (!(gamepads[i].index in this.babylonGamepads)) {
  11737. var newGamepad = this._addNewGamepad(gamepads[i]);
  11738. if (this._callbackGamepadConnected) {
  11739. this._callbackGamepadConnected(newGamepad);
  11740. }
  11741. }
  11742. else {
  11743. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11744. }
  11745. }
  11746. }
  11747. };
  11748. return Gamepads;
  11749. })();
  11750. BABYLON.Gamepads = Gamepads;
  11751. var StickValues = (function () {
  11752. function StickValues(x, y) {
  11753. this.x = x;
  11754. this.y = y;
  11755. }
  11756. return StickValues;
  11757. })();
  11758. BABYLON.StickValues = StickValues;
  11759. var Gamepad = (function () {
  11760. function Gamepad(id, index, browserGamepad) {
  11761. this.id = id;
  11762. this.index = index;
  11763. this.browserGamepad = browserGamepad;
  11764. if (this.browserGamepad.axes.length >= 2) {
  11765. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11766. }
  11767. if (this.browserGamepad.axes.length >= 4) {
  11768. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11769. }
  11770. }
  11771. Gamepad.prototype.onleftstickchanged = function (callback) {
  11772. this._onleftstickchanged = callback;
  11773. };
  11774. Gamepad.prototype.onrightstickchanged = function (callback) {
  11775. this._onrightstickchanged = callback;
  11776. };
  11777. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11778. get: function () {
  11779. return this._leftStick;
  11780. },
  11781. set: function (newValues) {
  11782. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11783. this._onleftstickchanged(newValues);
  11784. }
  11785. this._leftStick = newValues;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11791. get: function () {
  11792. return this._rightStick;
  11793. },
  11794. set: function (newValues) {
  11795. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11796. this._onrightstickchanged(newValues);
  11797. }
  11798. this._rightStick = newValues;
  11799. },
  11800. enumerable: true,
  11801. configurable: true
  11802. });
  11803. Gamepad.prototype.update = function () {
  11804. if (this._leftStick) {
  11805. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11806. }
  11807. if (this._rightStick) {
  11808. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11809. }
  11810. };
  11811. return Gamepad;
  11812. })();
  11813. BABYLON.Gamepad = Gamepad;
  11814. var GenericPad = (function (_super) {
  11815. __extends(GenericPad, _super);
  11816. function GenericPad(id, index, gamepad) {
  11817. _super.call(this, id, index, gamepad);
  11818. this.id = id;
  11819. this.index = index;
  11820. this.gamepad = gamepad;
  11821. this._buttons = new Array(gamepad.buttons.length);
  11822. }
  11823. GenericPad.prototype.onbuttondown = function (callback) {
  11824. this._onbuttondown = callback;
  11825. };
  11826. GenericPad.prototype.onbuttonup = function (callback) {
  11827. this._onbuttonup = callback;
  11828. };
  11829. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11830. if (newValue !== currentValue) {
  11831. if (this._onbuttondown && newValue === 1) {
  11832. this._onbuttondown(buttonIndex);
  11833. }
  11834. if (this._onbuttonup && newValue === 0) {
  11835. this._onbuttonup(buttonIndex);
  11836. }
  11837. }
  11838. return newValue;
  11839. };
  11840. GenericPad.prototype.update = function () {
  11841. _super.prototype.update.call(this);
  11842. for (var index = 0; index < this._buttons.length; index++) {
  11843. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11844. }
  11845. };
  11846. return GenericPad;
  11847. })(Gamepad);
  11848. BABYLON.GenericPad = GenericPad;
  11849. (function (Xbox360Button) {
  11850. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11851. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11852. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11853. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11854. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11855. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11856. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11857. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11858. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11859. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11860. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11861. var Xbox360Button = BABYLON.Xbox360Button;
  11862. (function (Xbox360Dpad) {
  11863. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11864. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11865. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11866. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11867. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11868. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11869. var Xbox360Pad = (function (_super) {
  11870. __extends(Xbox360Pad, _super);
  11871. function Xbox360Pad() {
  11872. _super.apply(this, arguments);
  11873. this._leftTrigger = 0;
  11874. this._rightTrigger = 0;
  11875. this._buttonA = 0;
  11876. this._buttonB = 0;
  11877. this._buttonX = 0;
  11878. this._buttonY = 0;
  11879. this._buttonBack = 0;
  11880. this._buttonStart = 0;
  11881. this._buttonLB = 0;
  11882. this._buttonRB = 0;
  11883. this._buttonLeftStick = 0;
  11884. this._buttonRightStick = 0;
  11885. this._dPadUp = 0;
  11886. this._dPadDown = 0;
  11887. this._dPadLeft = 0;
  11888. this._dPadRight = 0;
  11889. }
  11890. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11891. this._onlefttriggerchanged = callback;
  11892. };
  11893. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11894. this._onrighttriggerchanged = callback;
  11895. };
  11896. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11897. get: function () {
  11898. return this._leftTrigger;
  11899. },
  11900. set: function (newValue) {
  11901. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11902. this._onlefttriggerchanged(newValue);
  11903. }
  11904. this._leftTrigger = newValue;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11910. get: function () {
  11911. return this._rightTrigger;
  11912. },
  11913. set: function (newValue) {
  11914. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11915. this._onrighttriggerchanged(newValue);
  11916. }
  11917. this._rightTrigger = newValue;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11923. this._onbuttondown = callback;
  11924. };
  11925. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11926. this._onbuttonup = callback;
  11927. };
  11928. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11929. this._ondpaddown = callback;
  11930. };
  11931. Xbox360Pad.prototype.ondpadup = function (callback) {
  11932. this._ondpadup = callback;
  11933. };
  11934. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11935. if (newValue !== currentValue) {
  11936. if (this._onbuttondown && newValue === 1) {
  11937. this._onbuttondown(buttonType);
  11938. }
  11939. if (this._onbuttonup && newValue === 0) {
  11940. this._onbuttonup(buttonType);
  11941. }
  11942. }
  11943. return newValue;
  11944. };
  11945. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11946. if (newValue !== currentValue) {
  11947. if (this._ondpaddown && newValue === 1) {
  11948. this._ondpaddown(buttonType);
  11949. }
  11950. if (this._ondpadup && newValue === 0) {
  11951. this._ondpadup(buttonType);
  11952. }
  11953. }
  11954. return newValue;
  11955. };
  11956. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11957. get: function () {
  11958. return this._buttonA;
  11959. },
  11960. set: function (value) {
  11961. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11962. },
  11963. enumerable: true,
  11964. configurable: true
  11965. });
  11966. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11967. get: function () {
  11968. return this._buttonB;
  11969. },
  11970. set: function (value) {
  11971. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11977. get: function () {
  11978. return this._buttonX;
  11979. },
  11980. set: function (value) {
  11981. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11987. get: function () {
  11988. return this._buttonY;
  11989. },
  11990. set: function (value) {
  11991. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11997. get: function () {
  11998. return this._buttonStart;
  11999. },
  12000. set: function (value) {
  12001. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  12002. },
  12003. enumerable: true,
  12004. configurable: true
  12005. });
  12006. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12007. get: function () {
  12008. return this._buttonBack;
  12009. },
  12010. set: function (value) {
  12011. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12017. get: function () {
  12018. return this._buttonLB;
  12019. },
  12020. set: function (value) {
  12021. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12022. },
  12023. enumerable: true,
  12024. configurable: true
  12025. });
  12026. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12027. get: function () {
  12028. return this._buttonRB;
  12029. },
  12030. set: function (value) {
  12031. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12037. get: function () {
  12038. return this._buttonLeftStick;
  12039. },
  12040. set: function (value) {
  12041. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12047. get: function () {
  12048. return this._buttonRightStick;
  12049. },
  12050. set: function (value) {
  12051. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12057. get: function () {
  12058. return this._dPadUp;
  12059. },
  12060. set: function (value) {
  12061. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12067. get: function () {
  12068. return this._dPadDown;
  12069. },
  12070. set: function (value) {
  12071. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12077. get: function () {
  12078. return this._dPadLeft;
  12079. },
  12080. set: function (value) {
  12081. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12087. get: function () {
  12088. return this._dPadRight;
  12089. },
  12090. set: function (value) {
  12091. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Xbox360Pad.prototype.update = function () {
  12097. _super.prototype.update.call(this);
  12098. this.buttonA = this.browserGamepad.buttons[0].value;
  12099. this.buttonB = this.browserGamepad.buttons[1].value;
  12100. this.buttonX = this.browserGamepad.buttons[2].value;
  12101. this.buttonY = this.browserGamepad.buttons[3].value;
  12102. this.buttonLB = this.browserGamepad.buttons[4].value;
  12103. this.buttonRB = this.browserGamepad.buttons[5].value;
  12104. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12105. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12106. this.buttonBack = this.browserGamepad.buttons[8].value;
  12107. this.buttonStart = this.browserGamepad.buttons[9].value;
  12108. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12109. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12110. this.dPadUp = this.browserGamepad.buttons[12].value;
  12111. this.dPadDown = this.browserGamepad.buttons[13].value;
  12112. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12113. this.dPadRight = this.browserGamepad.buttons[15].value;
  12114. };
  12115. return Xbox360Pad;
  12116. })(Gamepad);
  12117. BABYLON.Xbox360Pad = Xbox360Pad;
  12118. })(BABYLON || (BABYLON = {}));
  12119. var BABYLON;
  12120. (function (BABYLON) {
  12121. // We're mainly based on the logic defined into the FreeCamera code
  12122. var GamepadCamera = (function (_super) {
  12123. __extends(GamepadCamera, _super);
  12124. function GamepadCamera(name, position, scene) {
  12125. var _this = this;
  12126. _super.call(this, name, position, scene);
  12127. this.angularSensibility = 200;
  12128. this.moveSensibility = 75;
  12129. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12130. }
  12131. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12132. // Only the first gamepad can control the camera
  12133. if (gamepad.index === 0) {
  12134. this._gamepad = gamepad;
  12135. }
  12136. };
  12137. GamepadCamera.prototype._checkInputs = function () {
  12138. if (this._gamepad) {
  12139. var LSValues = this._gamepad.leftStick;
  12140. var normalizedLX = LSValues.x / this.moveSensibility;
  12141. var normalizedLY = LSValues.y / this.moveSensibility;
  12142. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12143. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12144. var RSValues = this._gamepad.rightStick;
  12145. var normalizedRX = RSValues.x / this.angularSensibility;
  12146. var normalizedRY = RSValues.y / this.angularSensibility;
  12147. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12148. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12149. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12150. var speed = this._computeLocalCameraSpeed() * 50.0;
  12151. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12152. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12153. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12154. }
  12155. _super.prototype._checkInputs.call(this);
  12156. };
  12157. GamepadCamera.prototype.dispose = function () {
  12158. this._gamepads.dispose();
  12159. _super.prototype.dispose.call(this);
  12160. };
  12161. return GamepadCamera;
  12162. })(BABYLON.FreeCamera);
  12163. BABYLON.GamepadCamera = GamepadCamera;
  12164. })(BABYLON || (BABYLON = {}));
  12165. var BABYLON;
  12166. (function (BABYLON) {
  12167. var RenderingManager = (function () {
  12168. function RenderingManager(scene) {
  12169. this._renderingGroups = new Array();
  12170. this._scene = scene;
  12171. }
  12172. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12173. if (this._scene._activeParticleSystems.length === 0) {
  12174. return;
  12175. }
  12176. // Particles
  12177. var beforeParticlesDate = BABYLON.Tools.Now;
  12178. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12179. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12180. if (particleSystem.renderingGroupId !== index) {
  12181. continue;
  12182. }
  12183. this._clearDepthBuffer();
  12184. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12185. this._scene._activeParticles += particleSystem.render();
  12186. }
  12187. }
  12188. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12189. };
  12190. RenderingManager.prototype._renderSprites = function (index) {
  12191. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12192. return;
  12193. }
  12194. // Sprites
  12195. var beforeSpritessDate = BABYLON.Tools.Now;
  12196. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12197. var spriteManager = this._scene.spriteManagers[id];
  12198. if (spriteManager.renderingGroupId === index) {
  12199. this._clearDepthBuffer();
  12200. spriteManager.render();
  12201. }
  12202. }
  12203. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12204. };
  12205. RenderingManager.prototype._clearDepthBuffer = function () {
  12206. if (this._depthBufferAlreadyCleaned) {
  12207. return;
  12208. }
  12209. this._scene.getEngine().clear(0, false, true);
  12210. this._depthBufferAlreadyCleaned = true;
  12211. };
  12212. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12213. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12214. this._depthBufferAlreadyCleaned = false;
  12215. var renderingGroup = this._renderingGroups[index];
  12216. var needToStepBack = false;
  12217. if (renderingGroup) {
  12218. this._clearDepthBuffer();
  12219. if (!renderingGroup.render(customRenderFunction)) {
  12220. this._renderingGroups.splice(index, 1);
  12221. needToStepBack = true;
  12222. }
  12223. }
  12224. if (renderSprites) {
  12225. this._renderSprites(index);
  12226. }
  12227. if (renderParticles) {
  12228. this._renderParticles(index, activeMeshes);
  12229. }
  12230. if (needToStepBack) {
  12231. index--;
  12232. }
  12233. }
  12234. };
  12235. RenderingManager.prototype.reset = function () {
  12236. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12237. if (renderingGroup) {
  12238. renderingGroup.prepare();
  12239. }
  12240. });
  12241. };
  12242. RenderingManager.prototype.dispatch = function (subMesh) {
  12243. var mesh = subMesh.getMesh();
  12244. var renderingGroupId = mesh.renderingGroupId || 0;
  12245. if (!this._renderingGroups[renderingGroupId]) {
  12246. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12247. }
  12248. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12249. };
  12250. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12251. return RenderingManager;
  12252. })();
  12253. BABYLON.RenderingManager = RenderingManager;
  12254. })(BABYLON || (BABYLON = {}));
  12255. var BABYLON;
  12256. (function (BABYLON) {
  12257. var RenderingGroup = (function () {
  12258. function RenderingGroup(index, scene) {
  12259. this.index = index;
  12260. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12261. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12262. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12263. this._scene = scene;
  12264. }
  12265. RenderingGroup.prototype.render = function (customRenderFunction) {
  12266. if (customRenderFunction) {
  12267. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12268. return true;
  12269. }
  12270. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12271. return false;
  12272. }
  12273. var engine = this._scene.getEngine();
  12274. // Opaque
  12275. var subIndex;
  12276. var submesh;
  12277. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12278. submesh = this._opaqueSubMeshes.data[subIndex];
  12279. submesh.render(false);
  12280. }
  12281. // Alpha test
  12282. engine.setAlphaTesting(true);
  12283. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12284. submesh = this._alphaTestSubMeshes.data[subIndex];
  12285. submesh.render(false);
  12286. }
  12287. engine.setAlphaTesting(false);
  12288. // Transparent
  12289. if (this._transparentSubMeshes.length) {
  12290. // Sorting
  12291. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12292. submesh = this._transparentSubMeshes.data[subIndex];
  12293. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12294. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12295. }
  12296. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12297. sortedArray.sort(function (a, b) {
  12298. // Alpha index first
  12299. if (a._alphaIndex > b._alphaIndex) {
  12300. return 1;
  12301. }
  12302. if (a._alphaIndex < b._alphaIndex) {
  12303. return -1;
  12304. }
  12305. // Then distance to camera
  12306. if (a._distanceToCamera < b._distanceToCamera) {
  12307. return 1;
  12308. }
  12309. if (a._distanceToCamera > b._distanceToCamera) {
  12310. return -1;
  12311. }
  12312. return 0;
  12313. });
  12314. // Rendering
  12315. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12316. submesh = sortedArray[subIndex];
  12317. submesh.render(true);
  12318. }
  12319. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12320. }
  12321. return true;
  12322. };
  12323. RenderingGroup.prototype.prepare = function () {
  12324. this._opaqueSubMeshes.reset();
  12325. this._transparentSubMeshes.reset();
  12326. this._alphaTestSubMeshes.reset();
  12327. };
  12328. RenderingGroup.prototype.dispatch = function (subMesh) {
  12329. var material = subMesh.getMaterial();
  12330. var mesh = subMesh.getMesh();
  12331. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12332. this._transparentSubMeshes.push(subMesh);
  12333. }
  12334. else if (material.needAlphaTesting()) {
  12335. this._alphaTestSubMeshes.push(subMesh);
  12336. }
  12337. else {
  12338. this._opaqueSubMeshes.push(subMesh); // Opaque
  12339. }
  12340. };
  12341. return RenderingGroup;
  12342. })();
  12343. BABYLON.RenderingGroup = RenderingGroup;
  12344. })(BABYLON || (BABYLON = {}));
  12345. var BABYLON;
  12346. (function (BABYLON) {
  12347. /**
  12348. * Represents a scene to be rendered by the engine.
  12349. * @see http://doc.babylonjs.com/page.php?p=21911
  12350. */
  12351. var Scene = (function () {
  12352. /**
  12353. * @constructor
  12354. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12355. */
  12356. function Scene(engine) {
  12357. // Members
  12358. this.autoClear = true;
  12359. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12360. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12361. this.forceWireframe = false;
  12362. this.forcePointsCloud = false;
  12363. this.forceShowBoundingBoxes = false;
  12364. this.animationsEnabled = true;
  12365. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  12366. // Fog
  12367. /**
  12368. * is fog enabled on this scene.
  12369. * @type {boolean}
  12370. */
  12371. this.fogEnabled = true;
  12372. this.fogMode = Scene.FOGMODE_NONE;
  12373. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12374. this.fogDensity = 0.1;
  12375. this.fogStart = 0;
  12376. this.fogEnd = 1000.0;
  12377. // Lights
  12378. /**
  12379. * is shadow enabled on this scene.
  12380. * @type {boolean}
  12381. */
  12382. this.shadowsEnabled = true;
  12383. /**
  12384. * is light enabled on this scene.
  12385. * @type {boolean}
  12386. */
  12387. this.lightsEnabled = true;
  12388. /**
  12389. * All of the lights added to this scene.
  12390. * @see BABYLON.Light
  12391. * @type {BABYLON.Light[]}
  12392. */
  12393. this.lights = new Array();
  12394. // Cameras
  12395. /**
  12396. * All of the cameras added to this scene.
  12397. * @see BABYLON.Camera
  12398. * @type {BABYLON.Camera[]}
  12399. */
  12400. this.cameras = new Array();
  12401. this.activeCameras = new Array();
  12402. // Meshes
  12403. /**
  12404. * All of the (abstract) meshes added to this scene.
  12405. * @see BABYLON.AbstractMesh
  12406. * @type {BABYLON.AbstractMesh[]}
  12407. */
  12408. this.meshes = new Array();
  12409. // Geometries
  12410. this._geometries = new Array();
  12411. this.materials = new Array();
  12412. this.multiMaterials = new Array();
  12413. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12414. // Textures
  12415. this.texturesEnabled = true;
  12416. this.textures = new Array();
  12417. // Particles
  12418. this.particlesEnabled = true;
  12419. this.particleSystems = new Array();
  12420. // Sprites
  12421. this.spritesEnabled = true;
  12422. this.spriteManagers = new Array();
  12423. // Layers
  12424. this.layers = new Array();
  12425. // Skeletons
  12426. this.skeletonsEnabled = true;
  12427. this.skeletons = new Array();
  12428. // Lens flares
  12429. this.lensFlaresEnabled = true;
  12430. this.lensFlareSystems = new Array();
  12431. // Collisions
  12432. this.collisionsEnabled = true;
  12433. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12434. // Postprocesses
  12435. this.postProcessesEnabled = true;
  12436. // Customs render targets
  12437. this.renderTargetsEnabled = true;
  12438. this.dumpNextRenderTargets = false;
  12439. this.customRenderTargets = new Array();
  12440. // Imported meshes
  12441. this.importedMeshesFiles = new Array();
  12442. this._actionManagers = new Array();
  12443. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12444. // Procedural textures
  12445. this.proceduralTexturesEnabled = true;
  12446. this._proceduralTextures = new Array();
  12447. this.soundTracks = new Array();
  12448. this._audioEnabled = true;
  12449. this._headphone = false;
  12450. this._totalVertices = 0;
  12451. this._activeIndices = 0;
  12452. this._activeParticles = 0;
  12453. this._lastFrameDuration = 0;
  12454. this._evaluateActiveMeshesDuration = 0;
  12455. this._renderTargetsDuration = 0;
  12456. this._particlesDuration = 0;
  12457. this._renderDuration = 0;
  12458. this._spritesDuration = 0;
  12459. this._animationRatio = 0;
  12460. this._renderId = 0;
  12461. this._executeWhenReadyTimeoutId = -1;
  12462. this._toBeDisposed = new BABYLON.SmartArray(256);
  12463. this._onReadyCallbacks = new Array();
  12464. this._pendingData = []; //ANY
  12465. this._onBeforeRenderCallbacks = new Array();
  12466. this._onAfterRenderCallbacks = new Array();
  12467. this._activeMeshes = new BABYLON.SmartArray(256);
  12468. this._processedMaterials = new BABYLON.SmartArray(256);
  12469. this._renderTargets = new BABYLON.SmartArray(256);
  12470. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12471. this._activeSkeletons = new BABYLON.SmartArray(32);
  12472. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12473. this._activeBones = 0;
  12474. this._activeAnimatables = new Array();
  12475. this._transformMatrix = BABYLON.Matrix.Zero();
  12476. this._edgesRenderers = new BABYLON.SmartArray(16);
  12477. this._uniqueIdCounter = 0;
  12478. this._engine = engine;
  12479. engine.scenes.push(this);
  12480. this._renderingManager = new BABYLON.RenderingManager(this);
  12481. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12482. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12483. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12484. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12485. this.attachControl();
  12486. this._debugLayer = new BABYLON.DebugLayer(this);
  12487. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12488. //simplification queue
  12489. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12490. //collision coordinator initialization. For now legacy per default.
  12491. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12492. }
  12493. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12494. get: function () {
  12495. return Scene._FOGMODE_NONE;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12501. get: function () {
  12502. return Scene._FOGMODE_EXP;
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12508. get: function () {
  12509. return Scene._FOGMODE_EXP2;
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12515. get: function () {
  12516. return Scene._FOGMODE_LINEAR;
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(Scene.prototype, "debugLayer", {
  12522. // Properties
  12523. get: function () {
  12524. return this._debugLayer;
  12525. },
  12526. enumerable: true,
  12527. configurable: true
  12528. });
  12529. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12530. get: function () {
  12531. return this._workerCollisions;
  12532. },
  12533. set: function (enabled) {
  12534. enabled = (enabled && !!Worker);
  12535. this._workerCollisions = enabled;
  12536. if (this.collisionCoordinator) {
  12537. this.collisionCoordinator.destroy();
  12538. }
  12539. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12540. this.collisionCoordinator.init(this);
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12546. get: function () {
  12547. return this._selectionOctree;
  12548. },
  12549. enumerable: true,
  12550. configurable: true
  12551. });
  12552. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12553. /**
  12554. * The mesh that is currently under the pointer.
  12555. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12556. */
  12557. get: function () {
  12558. return this._meshUnderPointer;
  12559. },
  12560. enumerable: true,
  12561. configurable: true
  12562. });
  12563. Object.defineProperty(Scene.prototype, "pointerX", {
  12564. /**
  12565. * Current on-screen X position of the pointer
  12566. * @return {number} X position of the pointer
  12567. */
  12568. get: function () {
  12569. return this._pointerX;
  12570. },
  12571. enumerable: true,
  12572. configurable: true
  12573. });
  12574. Object.defineProperty(Scene.prototype, "pointerY", {
  12575. /**
  12576. * Current on-screen Y position of the pointer
  12577. * @return {number} Y position of the pointer
  12578. */
  12579. get: function () {
  12580. return this._pointerY;
  12581. },
  12582. enumerable: true,
  12583. configurable: true
  12584. });
  12585. Scene.prototype.getCachedMaterial = function () {
  12586. return this._cachedMaterial;
  12587. };
  12588. Scene.prototype.getBoundingBoxRenderer = function () {
  12589. return this._boundingBoxRenderer;
  12590. };
  12591. Scene.prototype.getOutlineRenderer = function () {
  12592. return this._outlineRenderer;
  12593. };
  12594. Scene.prototype.getEngine = function () {
  12595. return this._engine;
  12596. };
  12597. Scene.prototype.getTotalVertices = function () {
  12598. return this._totalVertices;
  12599. };
  12600. Scene.prototype.getActiveIndices = function () {
  12601. return this._activeIndices;
  12602. };
  12603. Scene.prototype.getActiveParticles = function () {
  12604. return this._activeParticles;
  12605. };
  12606. Scene.prototype.getActiveBones = function () {
  12607. return this._activeBones;
  12608. };
  12609. // Stats
  12610. Scene.prototype.getLastFrameDuration = function () {
  12611. return this._lastFrameDuration;
  12612. };
  12613. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12614. return this._evaluateActiveMeshesDuration;
  12615. };
  12616. Scene.prototype.getActiveMeshes = function () {
  12617. return this._activeMeshes;
  12618. };
  12619. Scene.prototype.getRenderTargetsDuration = function () {
  12620. return this._renderTargetsDuration;
  12621. };
  12622. Scene.prototype.getRenderDuration = function () {
  12623. return this._renderDuration;
  12624. };
  12625. Scene.prototype.getParticlesDuration = function () {
  12626. return this._particlesDuration;
  12627. };
  12628. Scene.prototype.getSpritesDuration = function () {
  12629. return this._spritesDuration;
  12630. };
  12631. Scene.prototype.getAnimationRatio = function () {
  12632. return this._animationRatio;
  12633. };
  12634. Scene.prototype.getRenderId = function () {
  12635. return this._renderId;
  12636. };
  12637. Scene.prototype.incrementRenderId = function () {
  12638. this._renderId++;
  12639. };
  12640. Scene.prototype._updatePointerPosition = function (evt) {
  12641. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12642. this._pointerX = evt.clientX - canvasRect.left;
  12643. this._pointerY = evt.clientY - canvasRect.top;
  12644. if (this.cameraToUseForPointers) {
  12645. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12646. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12647. }
  12648. };
  12649. // Pointers handling
  12650. Scene.prototype.attachControl = function () {
  12651. var _this = this;
  12652. this._onPointerMove = function (evt) {
  12653. var canvas = _this._engine.getRenderingCanvas();
  12654. _this._updatePointerPosition(evt);
  12655. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12656. if (pickResult.hit) {
  12657. _this._meshUnderPointer = pickResult.pickedMesh;
  12658. _this.setPointerOverMesh(pickResult.pickedMesh);
  12659. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12660. canvas.style.cursor = "pointer";
  12661. }
  12662. else {
  12663. canvas.style.cursor = "";
  12664. }
  12665. }
  12666. else {
  12667. _this.setPointerOverMesh(null);
  12668. canvas.style.cursor = "";
  12669. _this._meshUnderPointer = null;
  12670. }
  12671. };
  12672. this._onPointerDown = function (evt) {
  12673. var predicate = null;
  12674. if (!_this.onPointerDown) {
  12675. predicate = function (mesh) {
  12676. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12677. };
  12678. }
  12679. _this._updatePointerPosition(evt);
  12680. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12681. if (pickResult.hit) {
  12682. if (pickResult.pickedMesh.actionManager) {
  12683. switch (evt.button) {
  12684. case 0:
  12685. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12686. break;
  12687. case 1:
  12688. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12689. break;
  12690. case 2:
  12691. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12692. break;
  12693. }
  12694. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12695. }
  12696. }
  12697. if (_this.onPointerDown) {
  12698. _this.onPointerDown(evt, pickResult);
  12699. }
  12700. };
  12701. this._onPointerUp = function (evt) {
  12702. var predicate = null;
  12703. if (!_this.onPointerUp) {
  12704. predicate = function (mesh) {
  12705. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12706. };
  12707. }
  12708. _this._updatePointerPosition(evt);
  12709. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12710. if (pickResult.hit) {
  12711. if (pickResult.pickedMesh.actionManager) {
  12712. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12713. }
  12714. }
  12715. if (_this.onPointerUp) {
  12716. _this.onPointerUp(evt, pickResult);
  12717. }
  12718. };
  12719. this._onKeyDown = function (evt) {
  12720. if (_this.actionManager) {
  12721. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12722. }
  12723. };
  12724. this._onKeyUp = function (evt) {
  12725. if (_this.actionManager) {
  12726. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12727. }
  12728. };
  12729. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12730. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12731. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12732. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12733. // Wheel
  12734. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12735. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12736. BABYLON.Tools.RegisterTopRootEvents([
  12737. { name: "keydown", handler: this._onKeyDown },
  12738. { name: "keyup", handler: this._onKeyUp }
  12739. ]);
  12740. };
  12741. Scene.prototype.detachControl = function () {
  12742. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12743. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12744. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12745. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12746. // Wheel
  12747. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12748. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12749. BABYLON.Tools.UnregisterTopRootEvents([
  12750. { name: "keydown", handler: this._onKeyDown },
  12751. { name: "keyup", handler: this._onKeyUp }
  12752. ]);
  12753. };
  12754. // Ready
  12755. Scene.prototype.isReady = function () {
  12756. if (this._pendingData.length > 0) {
  12757. return false;
  12758. }
  12759. var index;
  12760. for (index = 0; index < this._geometries.length; index++) {
  12761. var geometry = this._geometries[index];
  12762. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12763. return false;
  12764. }
  12765. }
  12766. for (index = 0; index < this.meshes.length; index++) {
  12767. var mesh = this.meshes[index];
  12768. if (!mesh.isReady()) {
  12769. return false;
  12770. }
  12771. var mat = mesh.material;
  12772. if (mat) {
  12773. if (!mat.isReady(mesh)) {
  12774. return false;
  12775. }
  12776. }
  12777. }
  12778. return true;
  12779. };
  12780. Scene.prototype.resetCachedMaterial = function () {
  12781. this._cachedMaterial = null;
  12782. };
  12783. Scene.prototype.registerBeforeRender = function (func) {
  12784. this._onBeforeRenderCallbacks.push(func);
  12785. };
  12786. Scene.prototype.unregisterBeforeRender = function (func) {
  12787. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12788. if (index > -1) {
  12789. this._onBeforeRenderCallbacks.splice(index, 1);
  12790. }
  12791. };
  12792. Scene.prototype.registerAfterRender = function (func) {
  12793. this._onAfterRenderCallbacks.push(func);
  12794. };
  12795. Scene.prototype.unregisterAfterRender = function (func) {
  12796. var index = this._onAfterRenderCallbacks.indexOf(func);
  12797. if (index > -1) {
  12798. this._onAfterRenderCallbacks.splice(index, 1);
  12799. }
  12800. };
  12801. Scene.prototype._addPendingData = function (data) {
  12802. this._pendingData.push(data);
  12803. };
  12804. Scene.prototype._removePendingData = function (data) {
  12805. var index = this._pendingData.indexOf(data);
  12806. if (index !== -1) {
  12807. this._pendingData.splice(index, 1);
  12808. }
  12809. };
  12810. Scene.prototype.getWaitingItemsCount = function () {
  12811. return this._pendingData.length;
  12812. };
  12813. /**
  12814. * Registers a function to be executed when the scene is ready.
  12815. * @param {Function} func - the function to be executed.
  12816. */
  12817. Scene.prototype.executeWhenReady = function (func) {
  12818. var _this = this;
  12819. this._onReadyCallbacks.push(func);
  12820. if (this._executeWhenReadyTimeoutId !== -1) {
  12821. return;
  12822. }
  12823. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12824. _this._checkIsReady();
  12825. }, 150);
  12826. };
  12827. Scene.prototype._checkIsReady = function () {
  12828. var _this = this;
  12829. if (this.isReady()) {
  12830. this._onReadyCallbacks.forEach(function (func) {
  12831. func();
  12832. });
  12833. this._onReadyCallbacks = [];
  12834. this._executeWhenReadyTimeoutId = -1;
  12835. return;
  12836. }
  12837. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12838. _this._checkIsReady();
  12839. }, 150);
  12840. };
  12841. // Animations
  12842. /**
  12843. * Will start the animation sequence of a given target
  12844. * @param target - the target
  12845. * @param {number} from - from which frame should animation start
  12846. * @param {number} to - till which frame should animation run.
  12847. * @param {boolean} [loop] - should the animation loop
  12848. * @param {number} [speedRatio] - the speed in which to run the animation
  12849. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12850. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12851. * @return {BABYLON.Animatable} the animatable object created for this animation
  12852. * @see BABYLON.Animatable
  12853. * @see http://doc.babylonjs.com/page.php?p=22081
  12854. */
  12855. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12856. if (speedRatio === undefined) {
  12857. speedRatio = 1.0;
  12858. }
  12859. this.stopAnimation(target);
  12860. if (!animatable) {
  12861. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12862. }
  12863. // Local animations
  12864. if (target.animations) {
  12865. animatable.appendAnimations(target, target.animations);
  12866. }
  12867. // Children animations
  12868. if (target.getAnimatables) {
  12869. var animatables = target.getAnimatables();
  12870. for (var index = 0; index < animatables.length; index++) {
  12871. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12872. }
  12873. }
  12874. return animatable;
  12875. };
  12876. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12877. if (speedRatio === undefined) {
  12878. speedRatio = 1.0;
  12879. }
  12880. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12881. return animatable;
  12882. };
  12883. Scene.prototype.getAnimatableByTarget = function (target) {
  12884. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12885. if (this._activeAnimatables[index].target === target) {
  12886. return this._activeAnimatables[index];
  12887. }
  12888. }
  12889. return null;
  12890. };
  12891. /**
  12892. * Will stop the animation of the given target
  12893. * @param target - the target
  12894. * @see beginAnimation
  12895. */
  12896. Scene.prototype.stopAnimation = function (target) {
  12897. var animatable = this.getAnimatableByTarget(target);
  12898. if (animatable) {
  12899. animatable.stop();
  12900. }
  12901. };
  12902. Scene.prototype._animate = function () {
  12903. if (!this.animationsEnabled) {
  12904. return;
  12905. }
  12906. if (!this._animationStartDate) {
  12907. this._animationStartDate = BABYLON.Tools.Now;
  12908. }
  12909. // Getting time
  12910. var now = BABYLON.Tools.Now;
  12911. var delay = now - this._animationStartDate;
  12912. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12913. this._activeAnimatables[index]._animate(delay);
  12914. }
  12915. };
  12916. // Matrix
  12917. Scene.prototype.getViewMatrix = function () {
  12918. return this._viewMatrix;
  12919. };
  12920. Scene.prototype.getProjectionMatrix = function () {
  12921. return this._projectionMatrix;
  12922. };
  12923. Scene.prototype.getTransformMatrix = function () {
  12924. return this._transformMatrix;
  12925. };
  12926. Scene.prototype.setTransformMatrix = function (view, projection) {
  12927. this._viewMatrix = view;
  12928. this._projectionMatrix = projection;
  12929. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12930. };
  12931. // Methods
  12932. Scene.prototype.addMesh = function (newMesh) {
  12933. newMesh.uniqueId = this._uniqueIdCounter++;
  12934. var position = this.meshes.push(newMesh);
  12935. //notify the collision coordinator
  12936. this.collisionCoordinator.onMeshAdded(newMesh);
  12937. if (this.onNewMeshAdded) {
  12938. this.onNewMeshAdded(newMesh, position, this);
  12939. }
  12940. };
  12941. Scene.prototype.removeMesh = function (toRemove) {
  12942. var index = this.meshes.indexOf(toRemove);
  12943. if (index !== -1) {
  12944. // Remove from the scene if mesh found
  12945. this.meshes.splice(index, 1);
  12946. }
  12947. //notify the collision coordinator
  12948. this.collisionCoordinator.onMeshRemoved(toRemove);
  12949. if (this.onMeshRemoved) {
  12950. this.onMeshRemoved(toRemove);
  12951. }
  12952. return index;
  12953. };
  12954. Scene.prototype.removeLight = function (toRemove) {
  12955. var index = this.lights.indexOf(toRemove);
  12956. if (index !== -1) {
  12957. // Remove from the scene if mesh found
  12958. this.lights.splice(index, 1);
  12959. }
  12960. if (this.onLightRemoved) {
  12961. this.onLightRemoved(toRemove);
  12962. }
  12963. return index;
  12964. };
  12965. Scene.prototype.removeCamera = function (toRemove) {
  12966. var index = this.cameras.indexOf(toRemove);
  12967. if (index !== -1) {
  12968. // Remove from the scene if mesh found
  12969. this.cameras.splice(index, 1);
  12970. }
  12971. // Remove from activeCameras
  12972. var index2 = this.activeCameras.indexOf(toRemove);
  12973. if (index2 !== -1) {
  12974. // Remove from the scene if mesh found
  12975. this.activeCameras.splice(index2, 1);
  12976. }
  12977. // Reset the activeCamera
  12978. if (this.activeCamera === toRemove) {
  12979. if (this.cameras.length > 0) {
  12980. this.activeCamera = this.cameras[0];
  12981. }
  12982. else {
  12983. this.activeCamera = null;
  12984. }
  12985. }
  12986. if (this.onCameraRemoved) {
  12987. this.onCameraRemoved(toRemove);
  12988. }
  12989. return index;
  12990. };
  12991. Scene.prototype.addLight = function (newLight) {
  12992. newLight.uniqueId = this._uniqueIdCounter++;
  12993. var position = this.lights.push(newLight);
  12994. if (this.onNewLightAdded) {
  12995. this.onNewLightAdded(newLight, position, this);
  12996. }
  12997. };
  12998. Scene.prototype.addCamera = function (newCamera) {
  12999. newCamera.uniqueId = this._uniqueIdCounter++;
  13000. var position = this.cameras.push(newCamera);
  13001. if (this.onNewCameraAdded) {
  13002. this.onNewCameraAdded(newCamera, position, this);
  13003. }
  13004. };
  13005. /**
  13006. * sets the active camera of the scene using its ID
  13007. * @param {string} id - the camera's ID
  13008. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13009. * @see activeCamera
  13010. */
  13011. Scene.prototype.setActiveCameraByID = function (id) {
  13012. var camera = this.getCameraByID(id);
  13013. if (camera) {
  13014. this.activeCamera = camera;
  13015. return camera;
  13016. }
  13017. return null;
  13018. };
  13019. /**
  13020. * sets the active camera of the scene using its name
  13021. * @param {string} name - the camera's name
  13022. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13023. * @see activeCamera
  13024. */
  13025. Scene.prototype.setActiveCameraByName = function (name) {
  13026. var camera = this.getCameraByName(name);
  13027. if (camera) {
  13028. this.activeCamera = camera;
  13029. return camera;
  13030. }
  13031. return null;
  13032. };
  13033. /**
  13034. * get a material using its id
  13035. * @param {string} the material's ID
  13036. * @return {BABYLON.Material|null} the material or null if none found.
  13037. */
  13038. Scene.prototype.getMaterialByID = function (id) {
  13039. for (var index = 0; index < this.materials.length; index++) {
  13040. if (this.materials[index].id === id) {
  13041. return this.materials[index];
  13042. }
  13043. }
  13044. return null;
  13045. };
  13046. /**
  13047. * get a material using its name
  13048. * @param {string} the material's name
  13049. * @return {BABYLON.Material|null} the material or null if none found.
  13050. */
  13051. Scene.prototype.getMaterialByName = function (name) {
  13052. for (var index = 0; index < this.materials.length; index++) {
  13053. if (this.materials[index].name === name) {
  13054. return this.materials[index];
  13055. }
  13056. }
  13057. return null;
  13058. };
  13059. Scene.prototype.getLensFlareSystemByName = function (name) {
  13060. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13061. if (this.lensFlareSystems[index].name === name) {
  13062. return this.lensFlareSystems[index];
  13063. }
  13064. }
  13065. return null;
  13066. };
  13067. Scene.prototype.getCameraByID = function (id) {
  13068. for (var index = 0; index < this.cameras.length; index++) {
  13069. if (this.cameras[index].id === id) {
  13070. return this.cameras[index];
  13071. }
  13072. }
  13073. return null;
  13074. };
  13075. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13076. for (var index = 0; index < this.cameras.length; index++) {
  13077. if (this.cameras[index].uniqueId === uniqueId) {
  13078. return this.cameras[index];
  13079. }
  13080. }
  13081. return null;
  13082. };
  13083. /**
  13084. * get a camera using its name
  13085. * @param {string} the camera's name
  13086. * @return {BABYLON.Camera|null} the camera or null if none found.
  13087. */
  13088. Scene.prototype.getCameraByName = function (name) {
  13089. for (var index = 0; index < this.cameras.length; index++) {
  13090. if (this.cameras[index].name === name) {
  13091. return this.cameras[index];
  13092. }
  13093. }
  13094. return null;
  13095. };
  13096. /**
  13097. * get a light node using its name
  13098. * @param {string} the light's name
  13099. * @return {BABYLON.Light|null} the light or null if none found.
  13100. */
  13101. Scene.prototype.getLightByName = function (name) {
  13102. for (var index = 0; index < this.lights.length; index++) {
  13103. if (this.lights[index].name === name) {
  13104. return this.lights[index];
  13105. }
  13106. }
  13107. return null;
  13108. };
  13109. /**
  13110. * get a light node using its ID
  13111. * @param {string} the light's id
  13112. * @return {BABYLON.Light|null} the light or null if none found.
  13113. */
  13114. Scene.prototype.getLightByID = function (id) {
  13115. for (var index = 0; index < this.lights.length; index++) {
  13116. if (this.lights[index].id === id) {
  13117. return this.lights[index];
  13118. }
  13119. }
  13120. return null;
  13121. };
  13122. /**
  13123. * get a light node using its scene-generated unique ID
  13124. * @param {number} the light's unique id
  13125. * @return {BABYLON.Light|null} the light or null if none found.
  13126. */
  13127. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13128. for (var index = 0; index < this.lights.length; index++) {
  13129. if (this.lights[index].uniqueId === uniqueId) {
  13130. return this.lights[index];
  13131. }
  13132. }
  13133. return null;
  13134. };
  13135. /**
  13136. * get a geometry using its ID
  13137. * @param {string} the geometry's id
  13138. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13139. */
  13140. Scene.prototype.getGeometryByID = function (id) {
  13141. for (var index = 0; index < this._geometries.length; index++) {
  13142. if (this._geometries[index].id === id) {
  13143. return this._geometries[index];
  13144. }
  13145. }
  13146. return null;
  13147. };
  13148. /**
  13149. * add a new geometry to this scene.
  13150. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13151. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13152. * @return {boolean} was the geometry added or not
  13153. */
  13154. Scene.prototype.pushGeometry = function (geometry, force) {
  13155. if (!force && this.getGeometryByID(geometry.id)) {
  13156. return false;
  13157. }
  13158. this._geometries.push(geometry);
  13159. //notify the collision coordinator
  13160. this.collisionCoordinator.onGeometryAdded(geometry);
  13161. if (this.onGeometryAdded) {
  13162. this.onGeometryAdded(geometry);
  13163. }
  13164. return true;
  13165. };
  13166. /**
  13167. * Removes an existing geometry
  13168. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13169. * @return {boolean} was the geometry removed or not
  13170. */
  13171. Scene.prototype.removeGeometry = function (geometry) {
  13172. var index = this._geometries.indexOf(geometry);
  13173. if (index > -1) {
  13174. this._geometries.splice(index, 1);
  13175. //notify the collision coordinator
  13176. this.collisionCoordinator.onGeometryDeleted(geometry);
  13177. if (this.onGeometryRemoved) {
  13178. this.onGeometryRemoved(geometry);
  13179. }
  13180. return true;
  13181. }
  13182. return false;
  13183. };
  13184. Scene.prototype.getGeometries = function () {
  13185. return this._geometries;
  13186. };
  13187. /**
  13188. * Get the first added mesh found of a given ID
  13189. * @param {string} id - the id to search for
  13190. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13191. */
  13192. Scene.prototype.getMeshByID = function (id) {
  13193. for (var index = 0; index < this.meshes.length; index++) {
  13194. if (this.meshes[index].id === id) {
  13195. return this.meshes[index];
  13196. }
  13197. }
  13198. return null;
  13199. };
  13200. /**
  13201. * Get a mesh with its auto-generated unique id
  13202. * @param {number} uniqueId - the unique id to search for
  13203. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13204. */
  13205. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13206. for (var index = 0; index < this.meshes.length; index++) {
  13207. if (this.meshes[index].uniqueId === uniqueId) {
  13208. return this.meshes[index];
  13209. }
  13210. }
  13211. return null;
  13212. };
  13213. /**
  13214. * Get a the last added mesh found of a given ID
  13215. * @param {string} id - the id to search for
  13216. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13217. */
  13218. Scene.prototype.getLastMeshByID = function (id) {
  13219. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13220. if (this.meshes[index].id === id) {
  13221. return this.meshes[index];
  13222. }
  13223. }
  13224. return null;
  13225. };
  13226. /**
  13227. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13228. * @param {string} id - the id to search for
  13229. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13230. */
  13231. Scene.prototype.getLastEntryByID = function (id) {
  13232. var index;
  13233. for (index = this.meshes.length - 1; index >= 0; index--) {
  13234. if (this.meshes[index].id === id) {
  13235. return this.meshes[index];
  13236. }
  13237. }
  13238. for (index = this.cameras.length - 1; index >= 0; index--) {
  13239. if (this.cameras[index].id === id) {
  13240. return this.cameras[index];
  13241. }
  13242. }
  13243. for (index = this.lights.length - 1; index >= 0; index--) {
  13244. if (this.lights[index].id === id) {
  13245. return this.lights[index];
  13246. }
  13247. }
  13248. return null;
  13249. };
  13250. Scene.prototype.getNodeByID = function (id) {
  13251. var mesh = this.getMeshByID(id);
  13252. if (mesh) {
  13253. return mesh;
  13254. }
  13255. var light = this.getLightByID(id);
  13256. if (light) {
  13257. return light;
  13258. }
  13259. return this.getCameraByID(id);
  13260. };
  13261. Scene.prototype.getNodeByName = function (name) {
  13262. var mesh = this.getMeshByName(name);
  13263. if (mesh) {
  13264. return mesh;
  13265. }
  13266. var light = this.getLightByName(name);
  13267. if (light) {
  13268. return light;
  13269. }
  13270. return this.getCameraByName(name);
  13271. };
  13272. Scene.prototype.getMeshByName = function (name) {
  13273. for (var index = 0; index < this.meshes.length; index++) {
  13274. if (this.meshes[index].name === name) {
  13275. return this.meshes[index];
  13276. }
  13277. }
  13278. return null;
  13279. };
  13280. Scene.prototype.getSoundByName = function (name) {
  13281. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13282. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13283. return this.mainSoundTrack.soundCollection[index];
  13284. }
  13285. }
  13286. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13287. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13288. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13289. return this.soundTracks[sdIndex].soundCollection[index];
  13290. }
  13291. }
  13292. }
  13293. return null;
  13294. };
  13295. Scene.prototype.getLastSkeletonByID = function (id) {
  13296. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13297. if (this.skeletons[index].id === id) {
  13298. return this.skeletons[index];
  13299. }
  13300. }
  13301. return null;
  13302. };
  13303. Scene.prototype.getSkeletonById = function (id) {
  13304. for (var index = 0; index < this.skeletons.length; index++) {
  13305. if (this.skeletons[index].id === id) {
  13306. return this.skeletons[index];
  13307. }
  13308. }
  13309. return null;
  13310. };
  13311. Scene.prototype.getSkeletonByName = function (name) {
  13312. for (var index = 0; index < this.skeletons.length; index++) {
  13313. if (this.skeletons[index].name === name) {
  13314. return this.skeletons[index];
  13315. }
  13316. }
  13317. return null;
  13318. };
  13319. Scene.prototype.isActiveMesh = function (mesh) {
  13320. return (this._activeMeshes.indexOf(mesh) !== -1);
  13321. };
  13322. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13323. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13324. var material = subMesh.getMaterial();
  13325. if (mesh.showSubMeshesBoundingBox) {
  13326. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13327. }
  13328. if (material) {
  13329. // Render targets
  13330. if (material.getRenderTargetTextures) {
  13331. if (this._processedMaterials.indexOf(material) === -1) {
  13332. this._processedMaterials.push(material);
  13333. this._renderTargets.concat(material.getRenderTargetTextures());
  13334. }
  13335. }
  13336. // Dispatch
  13337. this._activeIndices += subMesh.indexCount;
  13338. this._renderingManager.dispatch(subMesh);
  13339. }
  13340. }
  13341. };
  13342. Scene.prototype._evaluateActiveMeshes = function () {
  13343. this.activeCamera._activeMeshes.reset();
  13344. this._activeMeshes.reset();
  13345. this._renderingManager.reset();
  13346. this._processedMaterials.reset();
  13347. this._activeParticleSystems.reset();
  13348. this._activeSkeletons.reset();
  13349. this._softwareSkinnedMeshes.reset();
  13350. this._boundingBoxRenderer.reset();
  13351. this._edgesRenderers.reset();
  13352. if (!this._frustumPlanes) {
  13353. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13354. }
  13355. else {
  13356. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13357. }
  13358. // Meshes
  13359. var meshes;
  13360. var len;
  13361. if (this._selectionOctree) {
  13362. var selection = this._selectionOctree.select(this._frustumPlanes);
  13363. meshes = selection.data;
  13364. len = selection.length;
  13365. }
  13366. else {
  13367. len = this.meshes.length;
  13368. meshes = this.meshes;
  13369. }
  13370. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13371. var mesh = meshes[meshIndex];
  13372. if (mesh.isBlocked) {
  13373. continue;
  13374. }
  13375. this._totalVertices += mesh.getTotalVertices();
  13376. if (!mesh.isReady() || !mesh.isEnabled()) {
  13377. continue;
  13378. }
  13379. mesh.computeWorldMatrix();
  13380. // Intersections
  13381. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13382. this._meshesForIntersections.pushNoDuplicate(mesh);
  13383. }
  13384. // Switch to current LOD
  13385. var meshLOD = mesh.getLOD(this.activeCamera);
  13386. if (!meshLOD) {
  13387. continue;
  13388. }
  13389. mesh._preActivate();
  13390. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13391. this._activeMeshes.push(mesh);
  13392. this.activeCamera._activeMeshes.push(mesh);
  13393. mesh._activate(this._renderId);
  13394. this._activeMesh(meshLOD);
  13395. }
  13396. }
  13397. // Particle systems
  13398. var beforeParticlesDate = BABYLON.Tools.Now;
  13399. if (this.particlesEnabled) {
  13400. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13401. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13402. var particleSystem = this.particleSystems[particleIndex];
  13403. if (!particleSystem.isStarted()) {
  13404. continue;
  13405. }
  13406. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13407. this._activeParticleSystems.push(particleSystem);
  13408. particleSystem.animate();
  13409. }
  13410. }
  13411. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13412. }
  13413. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13414. };
  13415. Scene.prototype._activeMesh = function (mesh) {
  13416. if (mesh.skeleton && this.skeletonsEnabled) {
  13417. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13418. if (!mesh.computeBonesUsingShaders) {
  13419. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13420. }
  13421. }
  13422. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13423. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13424. }
  13425. if (mesh._edgesRenderer) {
  13426. this._edgesRenderers.push(mesh._edgesRenderer);
  13427. }
  13428. if (mesh && mesh.subMeshes) {
  13429. // Submeshes Octrees
  13430. var len;
  13431. var subMeshes;
  13432. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13433. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13434. len = intersections.length;
  13435. subMeshes = intersections.data;
  13436. }
  13437. else {
  13438. subMeshes = mesh.subMeshes;
  13439. len = subMeshes.length;
  13440. }
  13441. for (var subIndex = 0; subIndex < len; subIndex++) {
  13442. var subMesh = subMeshes[subIndex];
  13443. this._evaluateSubMesh(subMesh, mesh);
  13444. }
  13445. }
  13446. };
  13447. Scene.prototype.updateTransformMatrix = function (force) {
  13448. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13449. };
  13450. Scene.prototype._renderForCamera = function (camera) {
  13451. var engine = this._engine;
  13452. this.activeCamera = camera;
  13453. if (!this.activeCamera)
  13454. throw new Error("Active camera not set");
  13455. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13456. // Viewport
  13457. engine.setViewport(this.activeCamera.viewport);
  13458. // Camera
  13459. this.resetCachedMaterial();
  13460. this._renderId++;
  13461. this.updateTransformMatrix();
  13462. if (this.beforeCameraRender) {
  13463. this.beforeCameraRender(this.activeCamera);
  13464. }
  13465. // Meshes
  13466. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13467. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13468. this._evaluateActiveMeshes();
  13469. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13470. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13471. // Skeletons
  13472. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13473. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13474. skeleton.prepare();
  13475. }
  13476. // Software skinning
  13477. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13478. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13479. mesh.applySkeleton(mesh.skeleton);
  13480. }
  13481. // Render targets
  13482. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13483. if (this.renderTargetsEnabled) {
  13484. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13485. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13486. var renderTarget = this._renderTargets.data[renderIndex];
  13487. if (renderTarget._shouldRender()) {
  13488. this._renderId++;
  13489. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13490. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13491. }
  13492. }
  13493. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13494. this._renderId++;
  13495. }
  13496. if (this._renderTargets.length > 0) {
  13497. engine.restoreDefaultFramebuffer();
  13498. }
  13499. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13500. // Prepare Frame
  13501. this.postProcessManager._prepareFrame();
  13502. var beforeRenderDate = BABYLON.Tools.Now;
  13503. // Backgrounds
  13504. var layerIndex;
  13505. if (this.layers.length) {
  13506. engine.setDepthBuffer(false);
  13507. var layer;
  13508. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13509. layer = this.layers[layerIndex];
  13510. if (layer.isBackground) {
  13511. layer.render();
  13512. }
  13513. }
  13514. engine.setDepthBuffer(true);
  13515. }
  13516. // Render
  13517. BABYLON.Tools.StartPerformanceCounter("Main render");
  13518. this._renderingManager.render(null, null, true, true);
  13519. BABYLON.Tools.EndPerformanceCounter("Main render");
  13520. // Bounding boxes
  13521. this._boundingBoxRenderer.render();
  13522. // Edges
  13523. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13524. this._edgesRenderers.data[edgesRendererIndex].render();
  13525. }
  13526. // Lens flares
  13527. if (this.lensFlaresEnabled) {
  13528. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13529. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13530. this.lensFlareSystems[lensFlareSystemIndex].render();
  13531. }
  13532. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13533. }
  13534. // Foregrounds
  13535. if (this.layers.length) {
  13536. engine.setDepthBuffer(false);
  13537. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13538. layer = this.layers[layerIndex];
  13539. if (!layer.isBackground) {
  13540. layer.render();
  13541. }
  13542. }
  13543. engine.setDepthBuffer(true);
  13544. }
  13545. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13546. // Finalize frame
  13547. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13548. // Update camera
  13549. this.activeCamera._updateFromScene();
  13550. // Reset some special arrays
  13551. this._renderTargets.reset();
  13552. if (this.afterCameraRender) {
  13553. this.afterCameraRender(this.activeCamera);
  13554. }
  13555. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13556. };
  13557. Scene.prototype._processSubCameras = function (camera) {
  13558. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13559. this._renderForCamera(camera);
  13560. return;
  13561. }
  13562. // rig cameras
  13563. for (var index = 0; index < camera._rigCameras.length; index++) {
  13564. this._renderForCamera(camera._rigCameras[index]);
  13565. }
  13566. this.activeCamera = camera;
  13567. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13568. // Update camera
  13569. this.activeCamera._updateFromScene();
  13570. };
  13571. Scene.prototype._checkIntersections = function () {
  13572. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13573. var sourceMesh = this._meshesForIntersections.data[index];
  13574. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13575. var action = sourceMesh.actionManager.actions[actionIndex];
  13576. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13577. var parameters = action.getTriggerParameter();
  13578. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13579. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13580. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13581. if (areIntersecting && currentIntersectionInProgress === -1) {
  13582. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13583. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13584. sourceMesh._intersectionsInProgress.push(otherMesh);
  13585. }
  13586. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13587. sourceMesh._intersectionsInProgress.push(otherMesh);
  13588. }
  13589. }
  13590. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13591. //They intersected, and now they don't.
  13592. //is this trigger an exit trigger? execute an event.
  13593. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13594. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13595. }
  13596. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13597. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13598. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13599. }
  13600. }
  13601. }
  13602. }
  13603. }
  13604. };
  13605. Scene.prototype.render = function () {
  13606. var startDate = BABYLON.Tools.Now;
  13607. this._particlesDuration = 0;
  13608. this._spritesDuration = 0;
  13609. this._activeParticles = 0;
  13610. this._renderDuration = 0;
  13611. this._renderTargetsDuration = 0;
  13612. this._evaluateActiveMeshesDuration = 0;
  13613. this._totalVertices = 0;
  13614. this._activeIndices = 0;
  13615. this._activeBones = 0;
  13616. this.getEngine().resetDrawCalls();
  13617. this._meshesForIntersections.reset();
  13618. this.resetCachedMaterial();
  13619. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13620. // Actions
  13621. if (this.actionManager) {
  13622. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13623. }
  13624. //Simplification Queue
  13625. if (!this.simplificationQueue.running) {
  13626. this.simplificationQueue.executeNext();
  13627. }
  13628. // Before render
  13629. if (this.beforeRender) {
  13630. this.beforeRender();
  13631. }
  13632. var callbackIndex;
  13633. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13634. this._onBeforeRenderCallbacks[callbackIndex]();
  13635. }
  13636. // Animations
  13637. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13638. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13639. this._animate();
  13640. // Physics
  13641. if (this._physicsEngine) {
  13642. BABYLON.Tools.StartPerformanceCounter("Physics");
  13643. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13644. BABYLON.Tools.EndPerformanceCounter("Physics");
  13645. }
  13646. // Customs render targets
  13647. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13648. var engine = this.getEngine();
  13649. var currentActiveCamera = this.activeCamera;
  13650. if (this.renderTargetsEnabled) {
  13651. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13652. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13653. var renderTarget = this.customRenderTargets[customIndex];
  13654. if (renderTarget._shouldRender()) {
  13655. this._renderId++;
  13656. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13657. if (!this.activeCamera)
  13658. throw new Error("Active camera not set");
  13659. // Viewport
  13660. engine.setViewport(this.activeCamera.viewport);
  13661. // Camera
  13662. this.updateTransformMatrix();
  13663. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13664. }
  13665. }
  13666. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13667. this._renderId++;
  13668. }
  13669. if (this.customRenderTargets.length > 0) {
  13670. engine.restoreDefaultFramebuffer();
  13671. }
  13672. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13673. this.activeCamera = currentActiveCamera;
  13674. // Procedural textures
  13675. if (this.proceduralTexturesEnabled) {
  13676. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13677. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13678. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13679. if (proceduralTexture._shouldRender()) {
  13680. proceduralTexture.render();
  13681. }
  13682. }
  13683. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13684. }
  13685. // Clear
  13686. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13687. // Shadows
  13688. if (this.shadowsEnabled) {
  13689. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13690. var light = this.lights[lightIndex];
  13691. var shadowGenerator = light.getShadowGenerator();
  13692. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13693. this._renderTargets.push(shadowGenerator.getShadowMap());
  13694. }
  13695. }
  13696. }
  13697. // Depth renderer
  13698. if (this._depthRenderer) {
  13699. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13700. }
  13701. // RenderPipeline
  13702. this.postProcessRenderPipelineManager.update();
  13703. // Multi-cameras?
  13704. if (this.activeCameras.length > 0) {
  13705. var currentRenderId = this._renderId;
  13706. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13707. this._renderId = currentRenderId;
  13708. this._processSubCameras(this.activeCameras[cameraIndex]);
  13709. }
  13710. }
  13711. else {
  13712. if (!this.activeCamera) {
  13713. throw new Error("No camera defined");
  13714. }
  13715. this._processSubCameras(this.activeCamera);
  13716. }
  13717. // Intersection checks
  13718. this._checkIntersections();
  13719. // Update the audio listener attached to the camera
  13720. this._updateAudioParameters();
  13721. // After render
  13722. if (this.afterRender) {
  13723. this.afterRender();
  13724. }
  13725. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13726. this._onAfterRenderCallbacks[callbackIndex]();
  13727. }
  13728. // Cleaning
  13729. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13730. this._toBeDisposed.data[index].dispose();
  13731. this._toBeDisposed[index] = null;
  13732. }
  13733. this._toBeDisposed.reset();
  13734. if (this.dumpNextRenderTargets) {
  13735. this.dumpNextRenderTargets = false;
  13736. }
  13737. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13738. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13739. };
  13740. Scene.prototype._updateAudioParameters = function () {
  13741. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13742. return;
  13743. }
  13744. var listeningCamera;
  13745. var audioEngine = BABYLON.Engine.audioEngine;
  13746. if (this.activeCameras.length > 0) {
  13747. listeningCamera = this.activeCameras[0];
  13748. }
  13749. else {
  13750. listeningCamera = this.activeCamera;
  13751. }
  13752. if (listeningCamera && audioEngine.canUseWebAudio) {
  13753. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13754. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13755. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13756. cameraDirection.normalize();
  13757. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13758. var i;
  13759. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13760. var sound = this.mainSoundTrack.soundCollection[i];
  13761. if (sound.useCustomAttenuation) {
  13762. sound.updateDistanceFromListener();
  13763. }
  13764. }
  13765. for (i = 0; i < this.soundTracks.length; i++) {
  13766. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13767. sound = this.soundTracks[i].soundCollection[j];
  13768. if (sound.useCustomAttenuation) {
  13769. sound.updateDistanceFromListener();
  13770. }
  13771. }
  13772. }
  13773. }
  13774. };
  13775. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13776. // Audio
  13777. get: function () {
  13778. return this._audioEnabled;
  13779. },
  13780. set: function (value) {
  13781. this._audioEnabled = value;
  13782. if (this._audioEnabled) {
  13783. this._enableAudio();
  13784. }
  13785. else {
  13786. this._disableAudio();
  13787. }
  13788. },
  13789. enumerable: true,
  13790. configurable: true
  13791. });
  13792. Scene.prototype._disableAudio = function () {
  13793. var i;
  13794. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13795. this.mainSoundTrack.soundCollection[i].pause();
  13796. }
  13797. for (i = 0; i < this.soundTracks.length; i++) {
  13798. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13799. this.soundTracks[i].soundCollection[j].pause();
  13800. }
  13801. }
  13802. };
  13803. Scene.prototype._enableAudio = function () {
  13804. var i;
  13805. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13806. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13807. this.mainSoundTrack.soundCollection[i].play();
  13808. }
  13809. }
  13810. for (i = 0; i < this.soundTracks.length; i++) {
  13811. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13812. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13813. this.soundTracks[i].soundCollection[j].play();
  13814. }
  13815. }
  13816. }
  13817. };
  13818. Object.defineProperty(Scene.prototype, "headphone", {
  13819. get: function () {
  13820. return this._headphone;
  13821. },
  13822. set: function (value) {
  13823. this._headphone = value;
  13824. if (this._headphone) {
  13825. this._switchAudioModeForHeadphones();
  13826. }
  13827. else {
  13828. this._switchAudioModeForNormalSpeakers();
  13829. }
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. Scene.prototype._switchAudioModeForHeadphones = function () {
  13835. this.mainSoundTrack.switchPanningModelToHRTF();
  13836. for (var i = 0; i < this.soundTracks.length; i++) {
  13837. this.soundTracks[i].switchPanningModelToHRTF();
  13838. }
  13839. };
  13840. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13841. this.mainSoundTrack.switchPanningModelToEqualPower();
  13842. for (var i = 0; i < this.soundTracks.length; i++) {
  13843. this.soundTracks[i].switchPanningModelToEqualPower();
  13844. }
  13845. };
  13846. Scene.prototype.enableDepthRenderer = function () {
  13847. if (this._depthRenderer) {
  13848. return this._depthRenderer;
  13849. }
  13850. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13851. return this._depthRenderer;
  13852. };
  13853. Scene.prototype.disableDepthRenderer = function () {
  13854. if (!this._depthRenderer) {
  13855. return;
  13856. }
  13857. this._depthRenderer.dispose();
  13858. this._depthRenderer = null;
  13859. };
  13860. Scene.prototype.dispose = function () {
  13861. this.beforeRender = null;
  13862. this.afterRender = null;
  13863. this.skeletons = [];
  13864. this._boundingBoxRenderer.dispose();
  13865. if (this._depthRenderer) {
  13866. this._depthRenderer.dispose();
  13867. }
  13868. // Debug layer
  13869. this.debugLayer.hide();
  13870. // Events
  13871. if (this.onDispose) {
  13872. this.onDispose();
  13873. }
  13874. this._onBeforeRenderCallbacks = [];
  13875. this._onAfterRenderCallbacks = [];
  13876. this.detachControl();
  13877. // Release sounds & sounds tracks
  13878. this.disposeSounds();
  13879. // Detach cameras
  13880. var canvas = this._engine.getRenderingCanvas();
  13881. var index;
  13882. for (index = 0; index < this.cameras.length; index++) {
  13883. this.cameras[index].detachControl(canvas);
  13884. }
  13885. // Release lights
  13886. while (this.lights.length) {
  13887. this.lights[0].dispose();
  13888. }
  13889. // Release meshes
  13890. while (this.meshes.length) {
  13891. this.meshes[0].dispose(true);
  13892. }
  13893. // Release cameras
  13894. while (this.cameras.length) {
  13895. this.cameras[0].dispose();
  13896. }
  13897. // Release materials
  13898. while (this.materials.length) {
  13899. this.materials[0].dispose();
  13900. }
  13901. // Release particles
  13902. while (this.particleSystems.length) {
  13903. this.particleSystems[0].dispose();
  13904. }
  13905. // Release sprites
  13906. while (this.spriteManagers.length) {
  13907. this.spriteManagers[0].dispose();
  13908. }
  13909. // Release layers
  13910. while (this.layers.length) {
  13911. this.layers[0].dispose();
  13912. }
  13913. // Release textures
  13914. while (this.textures.length) {
  13915. this.textures[0].dispose();
  13916. }
  13917. // Post-processes
  13918. this.postProcessManager.dispose();
  13919. // Physics
  13920. if (this._physicsEngine) {
  13921. this.disablePhysicsEngine();
  13922. }
  13923. // Remove from engine
  13924. index = this._engine.scenes.indexOf(this);
  13925. if (index > -1) {
  13926. this._engine.scenes.splice(index, 1);
  13927. }
  13928. this._engine.wipeCaches();
  13929. };
  13930. // Release sounds & sounds tracks
  13931. Scene.prototype.disposeSounds = function () {
  13932. this.mainSoundTrack.dispose();
  13933. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13934. this.soundTracks[scIndex].dispose();
  13935. }
  13936. };
  13937. // Octrees
  13938. Scene.prototype.getWorldExtends = function () {
  13939. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13940. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13941. for (var index = 0; index < this.meshes.length; index++) {
  13942. var mesh = this.meshes[index];
  13943. mesh.computeWorldMatrix(true);
  13944. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13945. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13946. BABYLON.Tools.CheckExtends(minBox, min, max);
  13947. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13948. }
  13949. return {
  13950. min: min,
  13951. max: max
  13952. };
  13953. };
  13954. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13955. if (maxCapacity === void 0) { maxCapacity = 64; }
  13956. if (maxDepth === void 0) { maxDepth = 2; }
  13957. if (!this._selectionOctree) {
  13958. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13959. }
  13960. var worldExtends = this.getWorldExtends();
  13961. // Update octree
  13962. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13963. return this._selectionOctree;
  13964. };
  13965. // Picking
  13966. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13967. var engine = this._engine;
  13968. if (!camera) {
  13969. if (!this.activeCamera)
  13970. throw new Error("Active camera not set");
  13971. camera = this.activeCamera;
  13972. }
  13973. var cameraViewport = camera.viewport;
  13974. var viewport = cameraViewport.toGlobal(engine);
  13975. // Moving coordinates to local viewport world
  13976. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13977. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13978. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13979. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13980. };
  13981. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13982. var pickingInfo = null;
  13983. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13984. var mesh = this.meshes[meshIndex];
  13985. if (predicate) {
  13986. if (!predicate(mesh)) {
  13987. continue;
  13988. }
  13989. }
  13990. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13991. continue;
  13992. }
  13993. var world = mesh.getWorldMatrix();
  13994. var ray = rayFunction(world);
  13995. var result = mesh.intersects(ray, fastCheck);
  13996. if (!result || !result.hit)
  13997. continue;
  13998. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13999. continue;
  14000. pickingInfo = result;
  14001. if (fastCheck) {
  14002. break;
  14003. }
  14004. }
  14005. return pickingInfo || new BABYLON.PickingInfo();
  14006. };
  14007. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14008. var _this = this;
  14009. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14010. /// <param name="x">X position on screen</param>
  14011. /// <param name="y">Y position on screen</param>
  14012. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  14013. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14014. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14015. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14016. };
  14017. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14018. var _this = this;
  14019. return this._internalPick(function (world) {
  14020. if (!_this._pickWithRayInverseMatrix) {
  14021. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14022. }
  14023. world.invertToRef(_this._pickWithRayInverseMatrix);
  14024. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14025. }, predicate, fastCheck);
  14026. };
  14027. Scene.prototype.setPointerOverMesh = function (mesh) {
  14028. if (this._pointerOverMesh === mesh) {
  14029. return;
  14030. }
  14031. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14032. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14033. }
  14034. this._pointerOverMesh = mesh;
  14035. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14036. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14037. }
  14038. };
  14039. Scene.prototype.getPointerOverMesh = function () {
  14040. return this._pointerOverMesh;
  14041. };
  14042. // Physics
  14043. Scene.prototype.getPhysicsEngine = function () {
  14044. return this._physicsEngine;
  14045. };
  14046. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14047. if (this._physicsEngine) {
  14048. return true;
  14049. }
  14050. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14051. if (!this._physicsEngine.isSupported()) {
  14052. this._physicsEngine = null;
  14053. return false;
  14054. }
  14055. this._physicsEngine._initialize(gravity);
  14056. return true;
  14057. };
  14058. Scene.prototype.disablePhysicsEngine = function () {
  14059. if (!this._physicsEngine) {
  14060. return;
  14061. }
  14062. this._physicsEngine.dispose();
  14063. this._physicsEngine = undefined;
  14064. };
  14065. Scene.prototype.isPhysicsEnabled = function () {
  14066. return this._physicsEngine !== undefined;
  14067. };
  14068. Scene.prototype.setGravity = function (gravity) {
  14069. if (!this._physicsEngine) {
  14070. return;
  14071. }
  14072. this._physicsEngine._setGravity(gravity);
  14073. };
  14074. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14075. if (parts.parts) {
  14076. options = parts;
  14077. parts = parts.parts;
  14078. }
  14079. if (!this._physicsEngine) {
  14080. return null;
  14081. }
  14082. for (var index = 0; index < parts.length; index++) {
  14083. var mesh = parts[index].mesh;
  14084. mesh._physicImpostor = parts[index].impostor;
  14085. mesh._physicsMass = options.mass / parts.length;
  14086. mesh._physicsFriction = options.friction;
  14087. mesh._physicRestitution = options.restitution;
  14088. }
  14089. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14090. };
  14091. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14092. for (var index = 0; index < compound.parts.length; index++) {
  14093. var mesh = compound.parts[index].mesh;
  14094. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14095. this._physicsEngine._unregisterMesh(mesh);
  14096. }
  14097. };
  14098. // Misc.
  14099. Scene.prototype.createDefaultCameraOrLight = function () {
  14100. // Light
  14101. if (this.lights.length === 0) {
  14102. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14103. }
  14104. // Camera
  14105. if (!this.activeCamera) {
  14106. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14107. // Compute position
  14108. var worldExtends = this.getWorldExtends();
  14109. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14110. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14111. camera.setTarget(worldCenter);
  14112. this.activeCamera = camera;
  14113. }
  14114. };
  14115. // Tags
  14116. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14117. if (tagsQuery === undefined) {
  14118. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14119. return list;
  14120. }
  14121. var listByTags = [];
  14122. forEach = forEach || (function (item) { return; });
  14123. for (var i in list) {
  14124. var item = list[i];
  14125. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14126. listByTags.push(item);
  14127. forEach(item);
  14128. }
  14129. }
  14130. return listByTags;
  14131. };
  14132. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14133. return this._getByTags(this.meshes, tagsQuery, forEach);
  14134. };
  14135. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14136. return this._getByTags(this.cameras, tagsQuery, forEach);
  14137. };
  14138. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14139. return this._getByTags(this.lights, tagsQuery, forEach);
  14140. };
  14141. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14142. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14143. };
  14144. // Statics
  14145. Scene._FOGMODE_NONE = 0;
  14146. Scene._FOGMODE_EXP = 1;
  14147. Scene._FOGMODE_EXP2 = 2;
  14148. Scene._FOGMODE_LINEAR = 3;
  14149. Scene.MinDeltaTime = 1.0;
  14150. Scene.MaxDeltaTime = 1000.0;
  14151. return Scene;
  14152. })();
  14153. BABYLON.Scene = Scene;
  14154. })(BABYLON || (BABYLON = {}));
  14155. var BABYLON;
  14156. (function (BABYLON) {
  14157. var VertexBuffer = (function () {
  14158. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14159. if (engine instanceof BABYLON.Mesh) {
  14160. this._engine = engine.getScene().getEngine();
  14161. }
  14162. else {
  14163. this._engine = engine;
  14164. }
  14165. this._updatable = updatable;
  14166. this._data = data;
  14167. if (!postponeInternalCreation) {
  14168. this.create();
  14169. }
  14170. this._kind = kind;
  14171. if (stride) {
  14172. this._strideSize = stride;
  14173. return;
  14174. }
  14175. // Deduce stride from kind
  14176. switch (kind) {
  14177. case VertexBuffer.PositionKind:
  14178. this._strideSize = 3;
  14179. break;
  14180. case VertexBuffer.NormalKind:
  14181. this._strideSize = 3;
  14182. break;
  14183. case VertexBuffer.UVKind:
  14184. case VertexBuffer.UV2Kind:
  14185. case VertexBuffer.UV3Kind:
  14186. case VertexBuffer.UV4Kind:
  14187. case VertexBuffer.UV5Kind:
  14188. case VertexBuffer.UV6Kind:
  14189. this._strideSize = 2;
  14190. break;
  14191. case VertexBuffer.ColorKind:
  14192. this._strideSize = 4;
  14193. break;
  14194. case VertexBuffer.MatricesIndicesKind:
  14195. this._strideSize = 4;
  14196. break;
  14197. case VertexBuffer.MatricesWeightsKind:
  14198. this._strideSize = 4;
  14199. break;
  14200. }
  14201. }
  14202. // Properties
  14203. VertexBuffer.prototype.isUpdatable = function () {
  14204. return this._updatable;
  14205. };
  14206. VertexBuffer.prototype.getData = function () {
  14207. return this._data;
  14208. };
  14209. VertexBuffer.prototype.getBuffer = function () {
  14210. return this._buffer;
  14211. };
  14212. VertexBuffer.prototype.getStrideSize = function () {
  14213. return this._strideSize;
  14214. };
  14215. // Methods
  14216. VertexBuffer.prototype.create = function (data) {
  14217. if (!data && this._buffer) {
  14218. return; // nothing to do
  14219. }
  14220. data = data || this._data;
  14221. if (!this._buffer) {
  14222. if (this._updatable) {
  14223. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14224. }
  14225. else {
  14226. this._buffer = this._engine.createVertexBuffer(data);
  14227. }
  14228. }
  14229. if (this._updatable) {
  14230. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14231. this._data = data;
  14232. }
  14233. };
  14234. VertexBuffer.prototype.update = function (data) {
  14235. this.create(data);
  14236. };
  14237. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14238. if (!this._buffer) {
  14239. return;
  14240. }
  14241. if (this._updatable) {
  14242. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14243. this._data = null;
  14244. }
  14245. };
  14246. VertexBuffer.prototype.dispose = function () {
  14247. if (!this._buffer) {
  14248. return;
  14249. }
  14250. if (this._engine._releaseBuffer(this._buffer)) {
  14251. this._buffer = null;
  14252. }
  14253. };
  14254. Object.defineProperty(VertexBuffer, "PositionKind", {
  14255. get: function () {
  14256. return VertexBuffer._PositionKind;
  14257. },
  14258. enumerable: true,
  14259. configurable: true
  14260. });
  14261. Object.defineProperty(VertexBuffer, "NormalKind", {
  14262. get: function () {
  14263. return VertexBuffer._NormalKind;
  14264. },
  14265. enumerable: true,
  14266. configurable: true
  14267. });
  14268. Object.defineProperty(VertexBuffer, "UVKind", {
  14269. get: function () {
  14270. return VertexBuffer._UVKind;
  14271. },
  14272. enumerable: true,
  14273. configurable: true
  14274. });
  14275. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14276. get: function () {
  14277. return VertexBuffer._UV2Kind;
  14278. },
  14279. enumerable: true,
  14280. configurable: true
  14281. });
  14282. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14283. get: function () {
  14284. return VertexBuffer._UV3Kind;
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14290. get: function () {
  14291. return VertexBuffer._UV4Kind;
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14297. get: function () {
  14298. return VertexBuffer._UV5Kind;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14304. get: function () {
  14305. return VertexBuffer._UV6Kind;
  14306. },
  14307. enumerable: true,
  14308. configurable: true
  14309. });
  14310. Object.defineProperty(VertexBuffer, "ColorKind", {
  14311. get: function () {
  14312. return VertexBuffer._ColorKind;
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14318. get: function () {
  14319. return VertexBuffer._MatricesIndicesKind;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14325. get: function () {
  14326. return VertexBuffer._MatricesWeightsKind;
  14327. },
  14328. enumerable: true,
  14329. configurable: true
  14330. });
  14331. // Enums
  14332. VertexBuffer._PositionKind = "position";
  14333. VertexBuffer._NormalKind = "normal";
  14334. VertexBuffer._UVKind = "uv";
  14335. VertexBuffer._UV2Kind = "uv2";
  14336. VertexBuffer._UV3Kind = "uv3";
  14337. VertexBuffer._UV4Kind = "uv4";
  14338. VertexBuffer._UV5Kind = "uv5";
  14339. VertexBuffer._UV6Kind = "uv6";
  14340. VertexBuffer._ColorKind = "color";
  14341. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14342. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14343. return VertexBuffer;
  14344. })();
  14345. BABYLON.VertexBuffer = VertexBuffer;
  14346. })(BABYLON || (BABYLON = {}));
  14347. var BABYLON;
  14348. (function (BABYLON) {
  14349. /**
  14350. * Creates an instance based on a source mesh.
  14351. */
  14352. var InstancedMesh = (function (_super) {
  14353. __extends(InstancedMesh, _super);
  14354. function InstancedMesh(name, source) {
  14355. _super.call(this, name, source.getScene());
  14356. source.instances.push(this);
  14357. this._sourceMesh = source;
  14358. this.position.copyFrom(source.position);
  14359. this.rotation.copyFrom(source.rotation);
  14360. this.scaling.copyFrom(source.scaling);
  14361. if (source.rotationQuaternion) {
  14362. this.rotationQuaternion = source.rotationQuaternion.clone();
  14363. }
  14364. this.infiniteDistance = source.infiniteDistance;
  14365. this.setPivotMatrix(source.getPivotMatrix());
  14366. this.refreshBoundingInfo();
  14367. this._syncSubMeshes();
  14368. }
  14369. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14370. // Methods
  14371. get: function () {
  14372. return this._sourceMesh.receiveShadows;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(InstancedMesh.prototype, "material", {
  14378. get: function () {
  14379. return this._sourceMesh.material;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14385. get: function () {
  14386. return this._sourceMesh.visibility;
  14387. },
  14388. enumerable: true,
  14389. configurable: true
  14390. });
  14391. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14392. get: function () {
  14393. return this._sourceMesh.skeleton;
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. InstancedMesh.prototype.getTotalVertices = function () {
  14399. return this._sourceMesh.getTotalVertices();
  14400. };
  14401. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14402. get: function () {
  14403. return this._sourceMesh;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. InstancedMesh.prototype.getVerticesData = function (kind) {
  14409. return this._sourceMesh.getVerticesData(kind);
  14410. };
  14411. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14412. return this._sourceMesh.isVerticesDataPresent(kind);
  14413. };
  14414. InstancedMesh.prototype.getIndices = function () {
  14415. return this._sourceMesh.getIndices();
  14416. };
  14417. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14418. get: function () {
  14419. return this._sourceMesh._positions;
  14420. },
  14421. enumerable: true,
  14422. configurable: true
  14423. });
  14424. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14425. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14426. if (data) {
  14427. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14428. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14429. }
  14430. this._updateBoundingInfo();
  14431. };
  14432. InstancedMesh.prototype._preActivate = function () {
  14433. if (this._currentLOD) {
  14434. this._currentLOD._preActivate();
  14435. }
  14436. };
  14437. InstancedMesh.prototype._activate = function (renderId) {
  14438. if (this._currentLOD) {
  14439. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14440. }
  14441. };
  14442. InstancedMesh.prototype.getLOD = function (camera) {
  14443. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14444. if (this._currentLOD === this.sourceMesh) {
  14445. return this;
  14446. }
  14447. return this._currentLOD;
  14448. };
  14449. InstancedMesh.prototype._syncSubMeshes = function () {
  14450. this.releaseSubMeshes();
  14451. if (this._sourceMesh.subMeshes) {
  14452. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14453. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14454. }
  14455. }
  14456. };
  14457. InstancedMesh.prototype._generatePointsArray = function () {
  14458. return this._sourceMesh._generatePointsArray();
  14459. };
  14460. // Clone
  14461. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14462. var result = this._sourceMesh.createInstance(name);
  14463. // Deep copy
  14464. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14465. // Bounding info
  14466. this.refreshBoundingInfo();
  14467. // Parent
  14468. if (newParent) {
  14469. result.parent = newParent;
  14470. }
  14471. if (!doNotCloneChildren) {
  14472. // Children
  14473. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14474. var mesh = this.getScene().meshes[index];
  14475. if (mesh.parent === this) {
  14476. mesh.clone(mesh.name, result);
  14477. }
  14478. }
  14479. }
  14480. result.computeWorldMatrix(true);
  14481. return result;
  14482. };
  14483. // Dispoe
  14484. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14485. // Remove from mesh
  14486. var index = this._sourceMesh.instances.indexOf(this);
  14487. this._sourceMesh.instances.splice(index, 1);
  14488. _super.prototype.dispose.call(this, doNotRecurse);
  14489. };
  14490. return InstancedMesh;
  14491. })(BABYLON.AbstractMesh);
  14492. BABYLON.InstancedMesh = InstancedMesh;
  14493. })(BABYLON || (BABYLON = {}));
  14494. var BABYLON;
  14495. (function (BABYLON) {
  14496. var _InstancesBatch = (function () {
  14497. function _InstancesBatch() {
  14498. this.mustReturn = false;
  14499. this.visibleInstances = new Array();
  14500. this.renderSelf = new Array();
  14501. }
  14502. return _InstancesBatch;
  14503. })();
  14504. BABYLON._InstancesBatch = _InstancesBatch;
  14505. var Mesh = (function (_super) {
  14506. __extends(Mesh, _super);
  14507. /**
  14508. * @constructor
  14509. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14510. * @param {Scene} scene - The scene to add this mesh to.
  14511. * @param {Node} parent - The parent of this mesh, if it has one
  14512. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14513. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14514. * When false, achieved by calling a clone(), also passing False.
  14515. * This will make creation of children, recursive.
  14516. */
  14517. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14518. if (parent === void 0) { parent = null; }
  14519. _super.call(this, name, scene);
  14520. // Members
  14521. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14522. this.instances = new Array();
  14523. this._LODLevels = new Array();
  14524. this._onBeforeRenderCallbacks = new Array();
  14525. this._onAfterRenderCallbacks = new Array();
  14526. this._visibleInstances = {};
  14527. this._renderIdForInstances = new Array();
  14528. this._batchCache = new _InstancesBatch();
  14529. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14530. this._sideOrientation = Mesh._DEFAULTSIDE;
  14531. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14532. if (source) {
  14533. // Geometry
  14534. if (source._geometry) {
  14535. source._geometry.applyToMesh(this);
  14536. }
  14537. // Deep copy
  14538. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14539. this.id = name + "." + source.id;
  14540. // Material
  14541. this.material = source.material;
  14542. if (!doNotCloneChildren) {
  14543. // Children
  14544. for (var index = 0; index < scene.meshes.length; index++) {
  14545. var mesh = scene.meshes[index];
  14546. if (mesh.parent === source) {
  14547. // doNotCloneChildren is always going to be False
  14548. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14549. }
  14550. }
  14551. }
  14552. // Particles
  14553. for (index = 0; index < scene.particleSystems.length; index++) {
  14554. var system = scene.particleSystems[index];
  14555. if (system.emitter === source) {
  14556. system.clone(system.name, this);
  14557. }
  14558. }
  14559. this.computeWorldMatrix(true);
  14560. }
  14561. // Parent
  14562. if (parent !== null) {
  14563. this.parent = parent;
  14564. }
  14565. }
  14566. Object.defineProperty(Mesh, "FRONTSIDE", {
  14567. get: function () {
  14568. return Mesh._FRONTSIDE;
  14569. },
  14570. enumerable: true,
  14571. configurable: true
  14572. });
  14573. Object.defineProperty(Mesh, "BACKSIDE", {
  14574. get: function () {
  14575. return Mesh._BACKSIDE;
  14576. },
  14577. enumerable: true,
  14578. configurable: true
  14579. });
  14580. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14581. get: function () {
  14582. return Mesh._DOUBLESIDE;
  14583. },
  14584. enumerable: true,
  14585. configurable: true
  14586. });
  14587. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14588. get: function () {
  14589. return Mesh._DEFAULTSIDE;
  14590. },
  14591. enumerable: true,
  14592. configurable: true
  14593. });
  14594. Object.defineProperty(Mesh, "NO_CAP", {
  14595. get: function () {
  14596. return Mesh._NO_CAP;
  14597. },
  14598. enumerable: true,
  14599. configurable: true
  14600. });
  14601. Object.defineProperty(Mesh, "CAP_START", {
  14602. get: function () {
  14603. return Mesh._CAP_START;
  14604. },
  14605. enumerable: true,
  14606. configurable: true
  14607. });
  14608. Object.defineProperty(Mesh, "CAP_END", {
  14609. get: function () {
  14610. return Mesh._CAP_END;
  14611. },
  14612. enumerable: true,
  14613. configurable: true
  14614. });
  14615. Object.defineProperty(Mesh, "CAP_ALL", {
  14616. get: function () {
  14617. return Mesh._CAP_ALL;
  14618. },
  14619. enumerable: true,
  14620. configurable: true
  14621. });
  14622. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14623. // Methods
  14624. get: function () {
  14625. return this._LODLevels.length > 0;
  14626. },
  14627. enumerable: true,
  14628. configurable: true
  14629. });
  14630. Mesh.prototype._sortLODLevels = function () {
  14631. this._LODLevels.sort(function (a, b) {
  14632. if (a.distance < b.distance) {
  14633. return 1;
  14634. }
  14635. if (a.distance > b.distance) {
  14636. return -1;
  14637. }
  14638. return 0;
  14639. });
  14640. };
  14641. /**
  14642. * Add a mesh as LOD level triggered at the given distance.
  14643. * @param {number} distance - the distance from the center of the object to show this level
  14644. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14645. * @return {BABYLON.Mesh} this mesh (for chaining)
  14646. */
  14647. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14648. if (mesh && mesh._masterMesh) {
  14649. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14650. return this;
  14651. }
  14652. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14653. this._LODLevels.push(level);
  14654. if (mesh) {
  14655. mesh._masterMesh = this;
  14656. }
  14657. this._sortLODLevels();
  14658. return this;
  14659. };
  14660. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14661. for (var index = 0; index < this._LODLevels.length; index++) {
  14662. var level = this._LODLevels[index];
  14663. if (level.distance === distance) {
  14664. return level.mesh;
  14665. }
  14666. }
  14667. return null;
  14668. };
  14669. /**
  14670. * Remove a mesh from the LOD array
  14671. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14672. * @return {BABYLON.Mesh} this mesh (for chaining)
  14673. */
  14674. Mesh.prototype.removeLODLevel = function (mesh) {
  14675. for (var index = 0; index < this._LODLevels.length; index++) {
  14676. if (this._LODLevels[index].mesh === mesh) {
  14677. this._LODLevels.splice(index, 1);
  14678. if (mesh) {
  14679. mesh._masterMesh = null;
  14680. }
  14681. }
  14682. }
  14683. this._sortLODLevels();
  14684. return this;
  14685. };
  14686. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14687. if (!this._LODLevels || this._LODLevels.length === 0) {
  14688. return this;
  14689. }
  14690. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14691. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14692. if (this.onLODLevelSelection) {
  14693. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14694. }
  14695. return this;
  14696. }
  14697. for (var index = 0; index < this._LODLevels.length; index++) {
  14698. var level = this._LODLevels[index];
  14699. if (level.distance < distanceToCamera) {
  14700. if (level.mesh) {
  14701. level.mesh._preActivate();
  14702. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14703. }
  14704. if (this.onLODLevelSelection) {
  14705. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14706. }
  14707. return level.mesh;
  14708. }
  14709. }
  14710. if (this.onLODLevelSelection) {
  14711. this.onLODLevelSelection(distanceToCamera, this, this);
  14712. }
  14713. return this;
  14714. };
  14715. Object.defineProperty(Mesh.prototype, "geometry", {
  14716. get: function () {
  14717. return this._geometry;
  14718. },
  14719. enumerable: true,
  14720. configurable: true
  14721. });
  14722. Mesh.prototype.getTotalVertices = function () {
  14723. if (!this._geometry) {
  14724. return 0;
  14725. }
  14726. return this._geometry.getTotalVertices();
  14727. };
  14728. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14729. if (!this._geometry) {
  14730. return null;
  14731. }
  14732. return this._geometry.getVerticesData(kind, copyWhenShared);
  14733. };
  14734. Mesh.prototype.getVertexBuffer = function (kind) {
  14735. if (!this._geometry) {
  14736. return undefined;
  14737. }
  14738. return this._geometry.getVertexBuffer(kind);
  14739. };
  14740. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14741. if (!this._geometry) {
  14742. if (this._delayInfo) {
  14743. return this._delayInfo.indexOf(kind) !== -1;
  14744. }
  14745. return false;
  14746. }
  14747. return this._geometry.isVerticesDataPresent(kind);
  14748. };
  14749. Mesh.prototype.getVerticesDataKinds = function () {
  14750. if (!this._geometry) {
  14751. var result = [];
  14752. if (this._delayInfo) {
  14753. for (var kind in this._delayInfo) {
  14754. result.push(kind);
  14755. }
  14756. }
  14757. return result;
  14758. }
  14759. return this._geometry.getVerticesDataKinds();
  14760. };
  14761. Mesh.prototype.getTotalIndices = function () {
  14762. if (!this._geometry) {
  14763. return 0;
  14764. }
  14765. return this._geometry.getTotalIndices();
  14766. };
  14767. Mesh.prototype.getIndices = function (copyWhenShared) {
  14768. if (!this._geometry) {
  14769. return [];
  14770. }
  14771. return this._geometry.getIndices(copyWhenShared);
  14772. };
  14773. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14774. get: function () {
  14775. return this._masterMesh !== null && this._masterMesh !== undefined;
  14776. },
  14777. enumerable: true,
  14778. configurable: true
  14779. });
  14780. Mesh.prototype.isReady = function () {
  14781. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14782. return false;
  14783. }
  14784. return _super.prototype.isReady.call(this);
  14785. };
  14786. Mesh.prototype.isDisposed = function () {
  14787. return this._isDisposed;
  14788. };
  14789. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14790. get: function () {
  14791. return this._sideOrientation;
  14792. },
  14793. set: function (sideO) {
  14794. this._sideOrientation = sideO;
  14795. },
  14796. enumerable: true,
  14797. configurable: true
  14798. });
  14799. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14800. get: function () {
  14801. return this._areNormalsFrozen;
  14802. },
  14803. enumerable: true,
  14804. configurable: true
  14805. });
  14806. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14807. Mesh.prototype.freezeNormals = function () {
  14808. this._areNormalsFrozen = true;
  14809. };
  14810. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14811. Mesh.prototype.unfreezeNormals = function () {
  14812. this._areNormalsFrozen = false;
  14813. };
  14814. // Methods
  14815. Mesh.prototype._preActivate = function () {
  14816. var sceneRenderId = this.getScene().getRenderId();
  14817. if (this._preActivateId === sceneRenderId) {
  14818. return;
  14819. }
  14820. this._preActivateId = sceneRenderId;
  14821. this._visibleInstances = null;
  14822. };
  14823. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14824. if (!this._visibleInstances) {
  14825. this._visibleInstances = {};
  14826. this._visibleInstances.defaultRenderId = renderId;
  14827. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14828. }
  14829. if (!this._visibleInstances[renderId]) {
  14830. this._visibleInstances[renderId] = new Array();
  14831. }
  14832. this._visibleInstances[renderId].push(instance);
  14833. };
  14834. Mesh.prototype.refreshBoundingInfo = function () {
  14835. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14836. if (data) {
  14837. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14838. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14839. }
  14840. if (this.subMeshes) {
  14841. for (var index = 0; index < this.subMeshes.length; index++) {
  14842. this.subMeshes[index].refreshBoundingInfo();
  14843. }
  14844. }
  14845. this._updateBoundingInfo();
  14846. };
  14847. Mesh.prototype._createGlobalSubMesh = function () {
  14848. var totalVertices = this.getTotalVertices();
  14849. if (!totalVertices || !this.getIndices()) {
  14850. return null;
  14851. }
  14852. this.releaseSubMeshes();
  14853. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14854. };
  14855. Mesh.prototype.subdivide = function (count) {
  14856. if (count < 1) {
  14857. return;
  14858. }
  14859. var totalIndices = this.getTotalIndices();
  14860. var subdivisionSize = (totalIndices / count) | 0;
  14861. var offset = 0;
  14862. // Ensure that subdivisionSize is a multiple of 3
  14863. while (subdivisionSize % 3 !== 0) {
  14864. subdivisionSize++;
  14865. }
  14866. this.releaseSubMeshes();
  14867. for (var index = 0; index < count; index++) {
  14868. if (offset >= totalIndices) {
  14869. break;
  14870. }
  14871. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14872. offset += subdivisionSize;
  14873. }
  14874. this.synchronizeInstances();
  14875. };
  14876. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14877. if (kind instanceof Array) {
  14878. var temp = data;
  14879. data = kind;
  14880. kind = temp;
  14881. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14882. }
  14883. if (!this._geometry) {
  14884. var vertexData = new BABYLON.VertexData();
  14885. vertexData.set(data, kind);
  14886. var scene = this.getScene();
  14887. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14888. }
  14889. else {
  14890. this._geometry.setVerticesData(kind, data, updatable, stride);
  14891. }
  14892. };
  14893. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14894. if (!this._geometry) {
  14895. return;
  14896. }
  14897. if (!makeItUnique) {
  14898. this._geometry.updateVerticesData(kind, data, updateExtends);
  14899. }
  14900. else {
  14901. this.makeGeometryUnique();
  14902. this.updateVerticesData(kind, data, updateExtends, false);
  14903. }
  14904. };
  14905. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14906. if (!this._geometry) {
  14907. return;
  14908. }
  14909. if (!makeItUnique) {
  14910. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14911. }
  14912. else {
  14913. this.makeGeometryUnique();
  14914. this.updateVerticesDataDirectly(kind, data, offset, false);
  14915. }
  14916. };
  14917. // Mesh positions update function :
  14918. // updates the mesh positions according to the positionFunction returned values.
  14919. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14920. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14921. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14922. if (computeNormals === void 0) { computeNormals = true; }
  14923. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14924. positionFunction(positions);
  14925. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14926. if (computeNormals) {
  14927. var indices = this.getIndices();
  14928. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14929. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14930. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14931. }
  14932. };
  14933. Mesh.prototype.makeGeometryUnique = function () {
  14934. if (!this._geometry) {
  14935. return;
  14936. }
  14937. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14938. geometry.applyToMesh(this);
  14939. };
  14940. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14941. if (!this._geometry) {
  14942. var vertexData = new BABYLON.VertexData();
  14943. vertexData.indices = indices;
  14944. var scene = this.getScene();
  14945. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14946. }
  14947. else {
  14948. this._geometry.setIndices(indices, totalVertices);
  14949. }
  14950. };
  14951. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14952. var engine = this.getScene().getEngine();
  14953. // Wireframe
  14954. var indexToBind;
  14955. switch (fillMode) {
  14956. case BABYLON.Material.PointFillMode:
  14957. indexToBind = null;
  14958. break;
  14959. case BABYLON.Material.WireFrameFillMode:
  14960. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14961. break;
  14962. default:
  14963. case BABYLON.Material.TriangleFillMode:
  14964. indexToBind = this._geometry.getIndexBuffer();
  14965. break;
  14966. }
  14967. // VBOs
  14968. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14969. };
  14970. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14971. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14972. return;
  14973. }
  14974. var engine = this.getScene().getEngine();
  14975. // Draw order
  14976. switch (fillMode) {
  14977. case BABYLON.Material.PointFillMode:
  14978. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14979. break;
  14980. case BABYLON.Material.WireFrameFillMode:
  14981. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14982. break;
  14983. default:
  14984. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14985. }
  14986. };
  14987. Mesh.prototype.registerBeforeRender = function (func) {
  14988. this._onBeforeRenderCallbacks.push(func);
  14989. };
  14990. Mesh.prototype.unregisterBeforeRender = function (func) {
  14991. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14992. if (index > -1) {
  14993. this._onBeforeRenderCallbacks.splice(index, 1);
  14994. }
  14995. };
  14996. Mesh.prototype.registerAfterRender = function (func) {
  14997. this._onAfterRenderCallbacks.push(func);
  14998. };
  14999. Mesh.prototype.unregisterAfterRender = function (func) {
  15000. var index = this._onAfterRenderCallbacks.indexOf(func);
  15001. if (index > -1) {
  15002. this._onAfterRenderCallbacks.splice(index, 1);
  15003. }
  15004. };
  15005. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15006. var scene = this.getScene();
  15007. this._batchCache.mustReturn = false;
  15008. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15009. this._batchCache.visibleInstances[subMeshId] = null;
  15010. if (this._visibleInstances) {
  15011. var currentRenderId = scene.getRenderId();
  15012. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15013. var selfRenderId = this._renderId;
  15014. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15015. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15016. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15017. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15018. }
  15019. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15020. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15021. this._batchCache.mustReturn = true;
  15022. return this._batchCache;
  15023. }
  15024. if (currentRenderId !== selfRenderId) {
  15025. this._batchCache.renderSelf[subMeshId] = false;
  15026. }
  15027. }
  15028. this._renderIdForInstances[subMeshId] = currentRenderId;
  15029. }
  15030. return this._batchCache;
  15031. };
  15032. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15033. var visibleInstances = batch.visibleInstances[subMesh._id];
  15034. var matricesCount = visibleInstances.length + 1;
  15035. var bufferSize = matricesCount * 16 * 4;
  15036. while (this._instancesBufferSize < bufferSize) {
  15037. this._instancesBufferSize *= 2;
  15038. }
  15039. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15040. if (this._worldMatricesInstancesBuffer) {
  15041. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15042. }
  15043. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15044. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15045. }
  15046. var offset = 0;
  15047. var instancesCount = 0;
  15048. var world = this.getWorldMatrix();
  15049. if (batch.renderSelf[subMesh._id]) {
  15050. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15051. offset += 16;
  15052. instancesCount++;
  15053. }
  15054. if (visibleInstances) {
  15055. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15056. var instance = visibleInstances[instanceIndex];
  15057. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15058. offset += 16;
  15059. instancesCount++;
  15060. }
  15061. }
  15062. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15063. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15064. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15065. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15066. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15067. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15068. this._draw(subMesh, fillMode, instancesCount);
  15069. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15070. };
  15071. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15072. var scene = this.getScene();
  15073. var engine = scene.getEngine();
  15074. if (hardwareInstancedRendering) {
  15075. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15076. }
  15077. else {
  15078. if (batch.renderSelf[subMesh._id]) {
  15079. // Draw
  15080. if (onBeforeDraw) {
  15081. onBeforeDraw(false, this.getWorldMatrix());
  15082. }
  15083. this._draw(subMesh, fillMode);
  15084. }
  15085. if (batch.visibleInstances[subMesh._id]) {
  15086. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15087. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15088. // World
  15089. var world = instance.getWorldMatrix();
  15090. if (onBeforeDraw) {
  15091. onBeforeDraw(true, world);
  15092. }
  15093. // Draw
  15094. this._draw(subMesh, fillMode);
  15095. }
  15096. }
  15097. }
  15098. };
  15099. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15100. var scene = this.getScene();
  15101. // Managing instances
  15102. var batch = this._getInstancesRenderList(subMesh._id);
  15103. if (batch.mustReturn) {
  15104. return;
  15105. }
  15106. // Checking geometry state
  15107. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15108. return;
  15109. }
  15110. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15111. this._onBeforeRenderCallbacks[callbackIndex](this);
  15112. }
  15113. var engine = scene.getEngine();
  15114. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15115. // Material
  15116. var effectiveMaterial = subMesh.getMaterial();
  15117. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15118. return;
  15119. }
  15120. // Outline - step 1
  15121. var savedDepthWrite = engine.getDepthWrite();
  15122. if (this.renderOutline) {
  15123. engine.setDepthWrite(false);
  15124. scene.getOutlineRenderer().render(subMesh, batch);
  15125. engine.setDepthWrite(savedDepthWrite);
  15126. }
  15127. effectiveMaterial._preBind();
  15128. var effect = effectiveMaterial.getEffect();
  15129. // Bind
  15130. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15131. this._bind(subMesh, effect, fillMode);
  15132. var world = this.getWorldMatrix();
  15133. effectiveMaterial.bind(world, this);
  15134. // Alpha mode
  15135. if (enableAlphaMode) {
  15136. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15137. }
  15138. // Draw
  15139. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15140. if (isInstance) {
  15141. effectiveMaterial.bindOnlyWorldMatrix(world);
  15142. }
  15143. });
  15144. // Unbind
  15145. effectiveMaterial.unbind();
  15146. // Outline - step 2
  15147. if (this.renderOutline && savedDepthWrite) {
  15148. engine.setDepthWrite(true);
  15149. engine.setColorWrite(false);
  15150. scene.getOutlineRenderer().render(subMesh, batch);
  15151. engine.setColorWrite(true);
  15152. }
  15153. // Overlay
  15154. if (this.renderOverlay) {
  15155. var currentMode = engine.getAlphaMode();
  15156. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15157. scene.getOutlineRenderer().render(subMesh, batch, true);
  15158. engine.setAlphaMode(currentMode);
  15159. }
  15160. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15161. this._onAfterRenderCallbacks[callbackIndex](this);
  15162. }
  15163. };
  15164. Mesh.prototype.getEmittedParticleSystems = function () {
  15165. var results = new Array();
  15166. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15167. var particleSystem = this.getScene().particleSystems[index];
  15168. if (particleSystem.emitter === this) {
  15169. results.push(particleSystem);
  15170. }
  15171. }
  15172. return results;
  15173. };
  15174. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15175. var results = new Array();
  15176. var descendants = this.getDescendants();
  15177. descendants.push(this);
  15178. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15179. var particleSystem = this.getScene().particleSystems[index];
  15180. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15181. results.push(particleSystem);
  15182. }
  15183. }
  15184. return results;
  15185. };
  15186. Mesh.prototype.getChildren = function () {
  15187. var results = [];
  15188. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15189. var mesh = this.getScene().meshes[index];
  15190. if (mesh.parent === this) {
  15191. results.push(mesh);
  15192. }
  15193. }
  15194. return results;
  15195. };
  15196. Mesh.prototype._checkDelayState = function () {
  15197. var _this = this;
  15198. var that = this;
  15199. var scene = this.getScene();
  15200. if (this._geometry) {
  15201. this._geometry.load(scene);
  15202. }
  15203. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15204. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15205. scene._addPendingData(that);
  15206. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15207. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15208. if (data instanceof ArrayBuffer) {
  15209. _this._delayLoadingFunction(data, _this);
  15210. }
  15211. else {
  15212. _this._delayLoadingFunction(JSON.parse(data), _this);
  15213. }
  15214. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15215. scene._removePendingData(_this);
  15216. }, function () { }, scene.database, getBinaryData);
  15217. }
  15218. };
  15219. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15220. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15221. return false;
  15222. }
  15223. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15224. return false;
  15225. }
  15226. this._checkDelayState();
  15227. return true;
  15228. };
  15229. Mesh.prototype.setMaterialByID = function (id) {
  15230. var materials = this.getScene().materials;
  15231. for (var index = 0; index < materials.length; index++) {
  15232. if (materials[index].id === id) {
  15233. this.material = materials[index];
  15234. return;
  15235. }
  15236. }
  15237. // Multi
  15238. var multiMaterials = this.getScene().multiMaterials;
  15239. for (index = 0; index < multiMaterials.length; index++) {
  15240. if (multiMaterials[index].id === id) {
  15241. this.material = multiMaterials[index];
  15242. return;
  15243. }
  15244. }
  15245. };
  15246. Mesh.prototype.getAnimatables = function () {
  15247. var results = [];
  15248. if (this.material) {
  15249. results.push(this.material);
  15250. }
  15251. if (this.skeleton) {
  15252. results.push(this.skeleton);
  15253. }
  15254. return results;
  15255. };
  15256. // Geometry
  15257. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15258. // Position
  15259. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15260. return;
  15261. }
  15262. this._resetPointsArrayCache();
  15263. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15264. var temp = [];
  15265. for (var index = 0; index < data.length; index += 3) {
  15266. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15267. }
  15268. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15269. // Normals
  15270. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15271. return;
  15272. }
  15273. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15274. temp = [];
  15275. for (index = 0; index < data.length; index += 3) {
  15276. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15277. }
  15278. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15279. // flip faces?
  15280. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15281. this.flipFaces();
  15282. }
  15283. };
  15284. // Will apply current transform to mesh and reset world matrix
  15285. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15286. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15287. this.scaling.copyFromFloats(1, 1, 1);
  15288. this.position.copyFromFloats(0, 0, 0);
  15289. this.rotation.copyFromFloats(0, 0, 0);
  15290. //only if quaternion is already set
  15291. if (this.rotationQuaternion) {
  15292. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15293. }
  15294. this._worldMatrix = BABYLON.Matrix.Identity();
  15295. };
  15296. // Cache
  15297. Mesh.prototype._resetPointsArrayCache = function () {
  15298. this._positions = null;
  15299. };
  15300. Mesh.prototype._generatePointsArray = function () {
  15301. if (this._positions)
  15302. return true;
  15303. this._positions = [];
  15304. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15305. if (!data) {
  15306. return false;
  15307. }
  15308. for (var index = 0; index < data.length; index += 3) {
  15309. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15310. }
  15311. return true;
  15312. };
  15313. // Clone
  15314. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15315. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15316. };
  15317. // Dispose
  15318. Mesh.prototype.dispose = function (doNotRecurse) {
  15319. if (this._geometry) {
  15320. this._geometry.releaseForMesh(this, true);
  15321. }
  15322. // Instances
  15323. if (this._worldMatricesInstancesBuffer) {
  15324. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15325. this._worldMatricesInstancesBuffer = null;
  15326. }
  15327. while (this.instances.length) {
  15328. this.instances[0].dispose();
  15329. }
  15330. _super.prototype.dispose.call(this, doNotRecurse);
  15331. };
  15332. // Geometric tools
  15333. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15334. var _this = this;
  15335. var scene = this.getScene();
  15336. var onload = function (img) {
  15337. // Getting height map data
  15338. var canvas = document.createElement("canvas");
  15339. var context = canvas.getContext("2d");
  15340. var heightMapWidth = img.width;
  15341. var heightMapHeight = img.height;
  15342. canvas.width = heightMapWidth;
  15343. canvas.height = heightMapHeight;
  15344. context.drawImage(img, 0, 0);
  15345. // Create VertexData from map data
  15346. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15347. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15348. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15349. //execute success callback, if set
  15350. if (onSuccess) {
  15351. onSuccess(_this);
  15352. }
  15353. };
  15354. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15355. };
  15356. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15357. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15358. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15359. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15360. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15361. return;
  15362. }
  15363. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15364. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15365. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15366. var position = BABYLON.Vector3.Zero();
  15367. var normal = BABYLON.Vector3.Zero();
  15368. var uv = BABYLON.Vector2.Zero();
  15369. for (var index = 0; index < positions.length; index += 3) {
  15370. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15371. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15372. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15373. // Compute height
  15374. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15375. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15376. var pos = (u + v * heightMapWidth) * 4;
  15377. var r = buffer[pos] / 255.0;
  15378. var g = buffer[pos + 1] / 255.0;
  15379. var b = buffer[pos + 2] / 255.0;
  15380. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15381. normal.normalize();
  15382. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15383. position = position.add(normal);
  15384. position.toArray(positions, index);
  15385. }
  15386. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15387. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15388. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15389. };
  15390. Mesh.prototype.convertToFlatShadedMesh = function () {
  15391. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15392. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15393. var kinds = this.getVerticesDataKinds();
  15394. var vbs = [];
  15395. var data = [];
  15396. var newdata = [];
  15397. var updatableNormals = false;
  15398. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15399. var kind = kinds[kindIndex];
  15400. var vertexBuffer = this.getVertexBuffer(kind);
  15401. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15402. updatableNormals = vertexBuffer.isUpdatable();
  15403. kinds.splice(kindIndex, 1);
  15404. kindIndex--;
  15405. continue;
  15406. }
  15407. vbs[kind] = vertexBuffer;
  15408. data[kind] = vbs[kind].getData();
  15409. newdata[kind] = [];
  15410. }
  15411. // Save previous submeshes
  15412. var previousSubmeshes = this.subMeshes.slice(0);
  15413. var indices = this.getIndices();
  15414. var totalIndices = this.getTotalIndices();
  15415. // Generating unique vertices per face
  15416. for (var index = 0; index < totalIndices; index++) {
  15417. var vertexIndex = indices[index];
  15418. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15419. kind = kinds[kindIndex];
  15420. var stride = vbs[kind].getStrideSize();
  15421. for (var offset = 0; offset < stride; offset++) {
  15422. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15423. }
  15424. }
  15425. }
  15426. // Updating faces & normal
  15427. var normals = [];
  15428. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15429. for (index = 0; index < totalIndices; index += 3) {
  15430. indices[index] = index;
  15431. indices[index + 1] = index + 1;
  15432. indices[index + 2] = index + 2;
  15433. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15434. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15435. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15436. var p1p2 = p1.subtract(p2);
  15437. var p3p2 = p3.subtract(p2);
  15438. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15439. // Store same normals for every vertex
  15440. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15441. normals.push(normal.x);
  15442. normals.push(normal.y);
  15443. normals.push(normal.z);
  15444. }
  15445. }
  15446. this.setIndices(indices);
  15447. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15448. // Updating vertex buffers
  15449. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15450. kind = kinds[kindIndex];
  15451. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15452. }
  15453. // Updating submeshes
  15454. this.releaseSubMeshes();
  15455. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15456. var previousOne = previousSubmeshes[submeshIndex];
  15457. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15458. }
  15459. this.synchronizeInstances();
  15460. };
  15461. // will inverse faces orientations, and invert normals too if specified
  15462. Mesh.prototype.flipFaces = function (flipNormals) {
  15463. if (flipNormals === void 0) { flipNormals = false; }
  15464. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15465. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15466. for (var i = 0; i < vertex_data.normals.length; i++) {
  15467. vertex_data.normals[i] *= -1;
  15468. }
  15469. }
  15470. var temp;
  15471. for (var i = 0; i < vertex_data.indices.length; i += 3) {
  15472. // reassign indices
  15473. temp = vertex_data.indices[i + 1];
  15474. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15475. vertex_data.indices[i + 2] = temp;
  15476. }
  15477. vertex_data.applyToMesh(this);
  15478. };
  15479. // Instances
  15480. Mesh.prototype.createInstance = function (name) {
  15481. return new BABYLON.InstancedMesh(name, this);
  15482. };
  15483. Mesh.prototype.synchronizeInstances = function () {
  15484. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15485. var instance = this.instances[instanceIndex];
  15486. instance._syncSubMeshes();
  15487. }
  15488. };
  15489. /**
  15490. * Simplify the mesh according to the given array of settings.
  15491. * Function will return immediately and will simplify async.
  15492. * @param settings a collection of simplification settings.
  15493. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15494. * @param type the type of simplification to run.
  15495. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15496. */
  15497. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15498. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15499. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15500. this.getScene().simplificationQueue.addTask({
  15501. settings: settings,
  15502. parallelProcessing: parallelProcessing,
  15503. mesh: this,
  15504. simplificationType: simplificationType,
  15505. successCallback: successCallback
  15506. });
  15507. };
  15508. /**
  15509. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15510. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15511. * This should be used together with the simplification to avoid disappearing triangles.
  15512. * @param successCallback an optional success callback to be called after the optimization finished.
  15513. */
  15514. Mesh.prototype.optimizeIndices = function (successCallback) {
  15515. var _this = this;
  15516. var indices = this.getIndices();
  15517. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15518. var vectorPositions = [];
  15519. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15520. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15521. }
  15522. var dupes = [];
  15523. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15524. var realPos = vectorPositions.length - 1 - iteration;
  15525. var testedPosition = vectorPositions[realPos];
  15526. for (var j = 0; j < realPos; ++j) {
  15527. var againstPosition = vectorPositions[j];
  15528. if (testedPosition.equals(againstPosition)) {
  15529. dupes[realPos] = j;
  15530. break;
  15531. }
  15532. }
  15533. }, function () {
  15534. for (var i = 0; i < indices.length; ++i) {
  15535. indices[i] = dupes[indices[i]] || indices[i];
  15536. }
  15537. //indices are now reordered
  15538. var originalSubMeshes = _this.subMeshes.slice(0);
  15539. _this.setIndices(indices);
  15540. _this.subMeshes = originalSubMeshes;
  15541. if (successCallback) {
  15542. successCallback(_this);
  15543. }
  15544. });
  15545. };
  15546. // Statics
  15547. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15548. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15549. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15550. if (ribbonInstance) {
  15551. // positionFunction : ribbon case
  15552. // only pathArray and sideOrientation parameters are taken into account for positions update
  15553. var positionFunction = function (positions) {
  15554. var minlg = pathArray[0].length;
  15555. var i = 0;
  15556. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15557. for (var si = 1; si <= ns; si++) {
  15558. for (var p = 0; p < pathArray.length; p++) {
  15559. var path = pathArray[p];
  15560. var l = path.length;
  15561. minlg = (minlg < l) ? minlg : l;
  15562. var j = 0;
  15563. while (j < minlg) {
  15564. positions[i] = path[j].x;
  15565. positions[i + 1] = path[j].y;
  15566. positions[i + 2] = path[j].z;
  15567. j++;
  15568. i += 3;
  15569. }
  15570. if (ribbonInstance._closePath) {
  15571. positions[i] = path[0].x;
  15572. positions[i + 1] = path[0].y;
  15573. positions[i + 2] = path[0].z;
  15574. i += 3;
  15575. }
  15576. }
  15577. }
  15578. };
  15579. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15580. positionFunction(positions);
  15581. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15582. if (!(ribbonInstance.areNormalsFrozen)) {
  15583. var indices = ribbonInstance.getIndices();
  15584. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15585. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15586. if (ribbonInstance._closePath) {
  15587. var indexFirst = 0;
  15588. var indexLast = 0;
  15589. for (var p = 0; p < pathArray.length; p++) {
  15590. indexFirst = ribbonInstance._idx[p] * 3;
  15591. if (p + 1 < pathArray.length) {
  15592. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15593. }
  15594. else {
  15595. indexLast = normals.length - 3;
  15596. }
  15597. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15598. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15599. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15600. normals[indexLast] = normals[indexFirst];
  15601. normals[indexLast + 1] = normals[indexFirst + 1];
  15602. normals[indexLast + 2] = normals[indexFirst + 2];
  15603. }
  15604. }
  15605. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15606. }
  15607. return ribbonInstance;
  15608. }
  15609. else {
  15610. var ribbon = new Mesh(name, scene);
  15611. ribbon.sideOrientation = sideOrientation;
  15612. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15613. if (closePath) {
  15614. ribbon._idx = vertexData._idx;
  15615. }
  15616. ribbon._closePath = closePath;
  15617. vertexData.applyToMesh(ribbon, updatable);
  15618. return ribbon;
  15619. }
  15620. };
  15621. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15622. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15623. var disc = new Mesh(name, scene);
  15624. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15625. vertexData.applyToMesh(disc, updatable);
  15626. return disc;
  15627. };
  15628. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15629. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15630. // Check parameters
  15631. updatable = updatable || options.updatable;
  15632. sideOrientation = sideOrientation || options.sideOrientation;
  15633. var box = new Mesh(name, scene);
  15634. var vertexData = BABYLON.VertexData.CreateBox(options, sideOrientation);
  15635. vertexData.applyToMesh(box, updatable);
  15636. return box;
  15637. };
  15638. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15639. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15640. if (diameterOrScene instanceof BABYLON.Scene) {
  15641. scene = diameterOrScene;
  15642. updatable = options.updatable;
  15643. }
  15644. else {
  15645. var segments = options;
  15646. options = {
  15647. segments: segments,
  15648. diameterX: diameterOrScene,
  15649. diameterY: diameterOrScene,
  15650. diameterZ: diameterOrScene,
  15651. sideOrientation: sideOrientation
  15652. };
  15653. }
  15654. var sphere = new Mesh(name, scene);
  15655. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15656. vertexData.applyToMesh(sphere, updatable);
  15657. return sphere;
  15658. };
  15659. // Cylinder and cone
  15660. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15661. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15662. // subdivisions is a new parameter, we need to support old signature
  15663. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15664. if (scene !== undefined) {
  15665. updatable = scene;
  15666. }
  15667. scene = subdivisions;
  15668. subdivisions = 1;
  15669. }
  15670. var cylinder = new Mesh(name, scene);
  15671. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15672. vertexData.applyToMesh(cylinder, updatable);
  15673. return cylinder;
  15674. };
  15675. // Torus (Code from SharpDX.org)
  15676. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15677. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15678. var torus = new Mesh(name, scene);
  15679. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15680. vertexData.applyToMesh(torus, updatable);
  15681. return torus;
  15682. };
  15683. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15684. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15685. var torusKnot = new Mesh(name, scene);
  15686. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15687. vertexData.applyToMesh(torusKnot, updatable);
  15688. return torusKnot;
  15689. };
  15690. // Lines
  15691. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15692. if (linesInstance === void 0) { linesInstance = null; }
  15693. if (linesInstance) {
  15694. var positionFunction = function (positions) {
  15695. var i = 0;
  15696. for (var p = 0; p < points.length; p++) {
  15697. positions[i] = points[p].x;
  15698. positions[i + 1] = points[p].y;
  15699. positions[i + 2] = points[p].z;
  15700. i += 3;
  15701. }
  15702. };
  15703. linesInstance.updateMeshPositions(positionFunction, false);
  15704. return linesInstance;
  15705. }
  15706. // lines creation
  15707. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15708. var vertexData = BABYLON.VertexData.CreateLines(points);
  15709. vertexData.applyToMesh(lines, updatable);
  15710. return lines;
  15711. };
  15712. // Dashed Lines
  15713. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15714. if (linesInstance === void 0) { linesInstance = null; }
  15715. if (linesInstance) {
  15716. var positionFunction = function (positions) {
  15717. var curvect = BABYLON.Vector3.Zero();
  15718. var nbSeg = positions.length / 6;
  15719. var lg = 0;
  15720. var nb = 0;
  15721. var shft = 0;
  15722. var dashshft = 0;
  15723. var curshft = 0;
  15724. var p = 0;
  15725. var i = 0;
  15726. var j = 0;
  15727. for (i = 0; i < points.length - 1; i++) {
  15728. points[i + 1].subtractToRef(points[i], curvect);
  15729. lg += curvect.length();
  15730. }
  15731. shft = lg / nbSeg;
  15732. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15733. for (i = 0; i < points.length - 1; i++) {
  15734. points[i + 1].subtractToRef(points[i], curvect);
  15735. nb = Math.floor(curvect.length() / shft);
  15736. curvect.normalize();
  15737. j = 0;
  15738. while (j < nb && p < positions.length) {
  15739. curshft = shft * j;
  15740. positions[p] = points[i].x + curshft * curvect.x;
  15741. positions[p + 1] = points[i].y + curshft * curvect.y;
  15742. positions[p + 2] = points[i].z + curshft * curvect.z;
  15743. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15744. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15745. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15746. p += 6;
  15747. j++;
  15748. }
  15749. }
  15750. while (p < positions.length) {
  15751. positions[p] = points[i].x;
  15752. positions[p + 1] = points[i].y;
  15753. positions[p + 2] = points[i].z;
  15754. p += 3;
  15755. }
  15756. };
  15757. linesInstance.updateMeshPositions(positionFunction, false);
  15758. return linesInstance;
  15759. }
  15760. // dashed lines creation
  15761. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15762. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15763. vertexData.applyToMesh(dashedLines, updatable);
  15764. dashedLines.dashSize = dashSize;
  15765. dashedLines.gapSize = gapSize;
  15766. return dashedLines;
  15767. };
  15768. // Extrusion
  15769. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15770. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15771. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15772. scale = scale || 1;
  15773. rotation = rotation || 0;
  15774. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15775. return extruded;
  15776. };
  15777. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15778. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15779. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15780. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15781. return extrudedCustom;
  15782. };
  15783. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15784. // extrusion geometry
  15785. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15786. var tangents = path3D.getTangents();
  15787. var normals = path3D.getNormals();
  15788. var binormals = path3D.getBinormals();
  15789. var distances = path3D.getDistances();
  15790. var angle = 0;
  15791. var returnScale = function (i, distance) { return scale; };
  15792. var returnRotation = function (i, distance) { return rotation; };
  15793. var rotate = custom ? rotateFunction : returnRotation;
  15794. var scl = custom ? scaleFunction : returnScale;
  15795. var index = 0;
  15796. for (var i = 0; i < curve.length; i++) {
  15797. var shapePath = new Array();
  15798. var angleStep = rotate(i, distances[i]);
  15799. var scaleRatio = scl(i, distances[i]);
  15800. for (var p = 0; p < shape.length; p++) {
  15801. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15802. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15803. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15804. shapePath.push(rotated);
  15805. }
  15806. shapePaths[index] = shapePath;
  15807. angle += angleStep;
  15808. index++;
  15809. }
  15810. // cap
  15811. var capPath = function (shapePath) {
  15812. var pointCap = Array();
  15813. var barycenter = BABYLON.Vector3.Zero();
  15814. var i;
  15815. for (i = 0; i < shapePath.length; i++) {
  15816. barycenter.addInPlace(shapePath[i]);
  15817. }
  15818. barycenter.scaleInPlace(1 / shapePath.length);
  15819. for (i = 0; i < shapePath.length; i++) {
  15820. pointCap.push(barycenter);
  15821. }
  15822. return pointCap;
  15823. };
  15824. switch (cap) {
  15825. case Mesh.NO_CAP:
  15826. break;
  15827. case Mesh.CAP_START:
  15828. shapePaths.unshift(capPath(shapePaths[0]));
  15829. break;
  15830. case Mesh.CAP_END:
  15831. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15832. break;
  15833. case Mesh.CAP_ALL:
  15834. shapePaths.unshift(capPath(shapePaths[0]));
  15835. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15836. break;
  15837. default:
  15838. break;
  15839. }
  15840. return shapePaths;
  15841. };
  15842. var path3D;
  15843. var pathArray;
  15844. if (instance) {
  15845. path3D = (instance.path3D).update(curve);
  15846. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15847. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15848. return instance;
  15849. }
  15850. // extruded shape creation
  15851. path3D = new BABYLON.Path3D(curve);
  15852. var newShapePaths = new Array();
  15853. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15854. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15855. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15856. extrudedGeneric.pathArray = pathArray;
  15857. extrudedGeneric.path3D = path3D;
  15858. extrudedGeneric.cap = cap;
  15859. return extrudedGeneric;
  15860. };
  15861. // Lathe
  15862. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15863. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15864. radius = radius || 1;
  15865. tessellation = tessellation || radius * 60;
  15866. var pi2 = Math.PI * 2;
  15867. var Y = BABYLON.Axis.Y;
  15868. var shapeLathe = new Array();
  15869. // first rotatable point
  15870. var i = 0;
  15871. while (shape[i].x === 0) {
  15872. i++;
  15873. }
  15874. var pt = shape[i];
  15875. for (i = 0; i < shape.length; i++) {
  15876. shapeLathe.push(shape[i].subtract(pt));
  15877. }
  15878. // circle path
  15879. var step = pi2 / tessellation;
  15880. var rotated;
  15881. var path = new Array();
  15882. ;
  15883. for (i = 0; i < tessellation; i++) {
  15884. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15885. path.push(rotated);
  15886. }
  15887. path.push(path[0]);
  15888. // extrusion
  15889. var scaleFunction = function () { return 1; };
  15890. var rotateFunction = function () { return 0; };
  15891. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15892. return lathe;
  15893. };
  15894. // Plane & ground
  15895. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15896. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15897. var plane = new Mesh(name, scene);
  15898. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15899. vertexData.applyToMesh(plane, updatable);
  15900. return plane;
  15901. };
  15902. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15903. var ground = new BABYLON.GroundMesh(name, scene);
  15904. ground._setReady(false);
  15905. ground._subdivisions = subdivisions;
  15906. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15907. vertexData.applyToMesh(ground, updatable);
  15908. ground._setReady(true);
  15909. return ground;
  15910. };
  15911. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15912. var tiledGround = new Mesh(name, scene);
  15913. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15914. vertexData.applyToMesh(tiledGround, updatable);
  15915. return tiledGround;
  15916. };
  15917. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15918. var ground = new BABYLON.GroundMesh(name, scene);
  15919. ground._subdivisions = subdivisions;
  15920. ground._setReady(false);
  15921. var onload = function (img) {
  15922. // Getting height map data
  15923. var canvas = document.createElement("canvas");
  15924. var context = canvas.getContext("2d");
  15925. var heightMapWidth = img.width;
  15926. var heightMapHeight = img.height;
  15927. canvas.width = heightMapWidth;
  15928. canvas.height = heightMapHeight;
  15929. context.drawImage(img, 0, 0);
  15930. // Create VertexData from map data
  15931. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15932. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15933. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15934. vertexData.applyToMesh(ground, updatable);
  15935. ground._setReady(true);
  15936. //execute ready callback, if set
  15937. if (onReady) {
  15938. onReady(ground);
  15939. }
  15940. };
  15941. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15942. return ground;
  15943. };
  15944. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15945. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15946. if (tubeInstance === void 0) { tubeInstance = null; }
  15947. // tube geometry
  15948. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15949. var tangents = path3D.getTangents();
  15950. var normals = path3D.getNormals();
  15951. var distances = path3D.getDistances();
  15952. var pi2 = Math.PI * 2;
  15953. var step = pi2 / tessellation;
  15954. var returnRadius = function (i, distance) { return radius; };
  15955. var radiusFunctionFinal = radiusFunction || returnRadius;
  15956. var circlePath;
  15957. var rad;
  15958. var normal;
  15959. var rotated;
  15960. var rotationMatrix;
  15961. var index = 0;
  15962. for (var i = 0; i < path.length; i++) {
  15963. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15964. circlePath = Array(); // current circle array
  15965. normal = normals[i]; // current normal
  15966. for (var t = 0; t < tessellation; t++) {
  15967. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15968. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15969. circlePath.push(rotated);
  15970. }
  15971. circlePaths[index] = circlePath;
  15972. index++;
  15973. }
  15974. // cap
  15975. var capPath = function (nbPoints, pathIndex) {
  15976. var pointCap = Array();
  15977. for (var i = 0; i < nbPoints; i++) {
  15978. pointCap.push(path[pathIndex]);
  15979. }
  15980. return pointCap;
  15981. };
  15982. switch (cap) {
  15983. case Mesh.NO_CAP:
  15984. break;
  15985. case Mesh.CAP_START:
  15986. circlePaths.unshift(capPath(tessellation + 1, 0));
  15987. break;
  15988. case Mesh.CAP_END:
  15989. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15990. break;
  15991. case Mesh.CAP_ALL:
  15992. circlePaths.unshift(capPath(tessellation + 1, 0));
  15993. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15994. break;
  15995. default:
  15996. break;
  15997. }
  15998. return circlePaths;
  15999. };
  16000. var path3D;
  16001. var pathArray;
  16002. if (tubeInstance) {
  16003. path3D = (tubeInstance.path3D).update(path);
  16004. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  16005. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  16006. return tubeInstance;
  16007. }
  16008. // tube creation
  16009. path3D = new BABYLON.Path3D(path);
  16010. var newPathArray = new Array();
  16011. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16012. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16013. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  16014. tube.pathArray = pathArray;
  16015. tube.path3D = path3D;
  16016. tube.tessellation = tessellation;
  16017. tube.cap = cap;
  16018. return tube;
  16019. };
  16020. // Decals
  16021. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16022. if (angle === void 0) { angle = 0; }
  16023. var indices = sourceMesh.getIndices();
  16024. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16025. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16026. // Getting correct rotation
  16027. if (!normal) {
  16028. var target = new BABYLON.Vector3(0, 0, 1);
  16029. var camera = sourceMesh.getScene().activeCamera;
  16030. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16031. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16032. }
  16033. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16034. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16035. var pitch = Math.atan2(normal.y, len);
  16036. // Matrix
  16037. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16038. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16039. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16040. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16041. var vertexData = new BABYLON.VertexData();
  16042. vertexData.indices = [];
  16043. vertexData.positions = [];
  16044. vertexData.normals = [];
  16045. vertexData.uvs = [];
  16046. var currentVertexDataIndex = 0;
  16047. var extractDecalVector3 = function (indexId) {
  16048. var vertexId = indices[indexId];
  16049. var result = new BABYLON.PositionNormalVertex();
  16050. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16051. // Send vector to decal local world
  16052. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16053. // Get normal
  16054. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16055. return result;
  16056. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16057. var clip = function (vertices, axis) {
  16058. if (vertices.length === 0) {
  16059. return vertices;
  16060. }
  16061. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16062. var clipVertices = function (v0, v1) {
  16063. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16064. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16065. };
  16066. var result = new Array();
  16067. for (var index = 0; index < vertices.length; index += 3) {
  16068. var v1Out;
  16069. var v2Out;
  16070. var v3Out;
  16071. var total = 0;
  16072. var nV1, nV2, nV3, nV4;
  16073. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16074. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16075. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16076. v1Out = d1 > 0;
  16077. v2Out = d2 > 0;
  16078. v3Out = d3 > 0;
  16079. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16080. switch (total) {
  16081. case 0:
  16082. result.push(vertices[index]);
  16083. result.push(vertices[index + 1]);
  16084. result.push(vertices[index + 2]);
  16085. break;
  16086. case 1:
  16087. if (v1Out) {
  16088. nV1 = vertices[index + 1];
  16089. nV2 = vertices[index + 2];
  16090. nV3 = clipVertices(vertices[index], nV1);
  16091. nV4 = clipVertices(vertices[index], nV2);
  16092. }
  16093. if (v2Out) {
  16094. nV1 = vertices[index];
  16095. nV2 = vertices[index + 2];
  16096. nV3 = clipVertices(vertices[index + 1], nV1);
  16097. nV4 = clipVertices(vertices[index + 1], nV2);
  16098. result.push(nV3);
  16099. result.push(nV2.clone());
  16100. result.push(nV1.clone());
  16101. result.push(nV2.clone());
  16102. result.push(nV3.clone());
  16103. result.push(nV4);
  16104. break;
  16105. }
  16106. if (v3Out) {
  16107. nV1 = vertices[index];
  16108. nV2 = vertices[index + 1];
  16109. nV3 = clipVertices(vertices[index + 2], nV1);
  16110. nV4 = clipVertices(vertices[index + 2], nV2);
  16111. }
  16112. result.push(nV1.clone());
  16113. result.push(nV2.clone());
  16114. result.push(nV3);
  16115. result.push(nV4);
  16116. result.push(nV3.clone());
  16117. result.push(nV2.clone());
  16118. break;
  16119. case 2:
  16120. if (!v1Out) {
  16121. nV1 = vertices[index].clone();
  16122. nV2 = clipVertices(nV1, vertices[index + 1]);
  16123. nV3 = clipVertices(nV1, vertices[index + 2]);
  16124. result.push(nV1);
  16125. result.push(nV2);
  16126. result.push(nV3);
  16127. }
  16128. if (!v2Out) {
  16129. nV1 = vertices[index + 1].clone();
  16130. nV2 = clipVertices(nV1, vertices[index + 2]);
  16131. nV3 = clipVertices(nV1, vertices[index]);
  16132. result.push(nV1);
  16133. result.push(nV2);
  16134. result.push(nV3);
  16135. }
  16136. if (!v3Out) {
  16137. nV1 = vertices[index + 2].clone();
  16138. nV2 = clipVertices(nV1, vertices[index]);
  16139. nV3 = clipVertices(nV1, vertices[index + 1]);
  16140. result.push(nV1);
  16141. result.push(nV2);
  16142. result.push(nV3);
  16143. }
  16144. break;
  16145. case 3:
  16146. break;
  16147. }
  16148. }
  16149. return result;
  16150. };
  16151. for (var index = 0; index < indices.length; index += 3) {
  16152. var faceVertices = new Array();
  16153. faceVertices.push(extractDecalVector3(index));
  16154. faceVertices.push(extractDecalVector3(index + 1));
  16155. faceVertices.push(extractDecalVector3(index + 2));
  16156. // Clip
  16157. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16158. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16159. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16160. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16161. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16162. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16163. if (faceVertices.length === 0) {
  16164. continue;
  16165. }
  16166. // Add UVs and get back to world
  16167. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16168. var vertex = faceVertices[vIndex];
  16169. vertexData.indices.push(currentVertexDataIndex);
  16170. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16171. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16172. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16173. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16174. currentVertexDataIndex++;
  16175. }
  16176. }
  16177. // Return mesh
  16178. var decal = new Mesh(name, sourceMesh.getScene());
  16179. vertexData.applyToMesh(decal);
  16180. decal.position = position.clone();
  16181. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16182. return decal;
  16183. };
  16184. // Skeletons
  16185. /**
  16186. * Update the vertex buffers by applying transformation from the bones
  16187. * @param {skeleton} skeleton to apply
  16188. */
  16189. Mesh.prototype.applySkeleton = function (skeleton) {
  16190. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16191. return this;
  16192. }
  16193. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16194. return this;
  16195. }
  16196. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16197. return this;
  16198. }
  16199. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16200. return this;
  16201. }
  16202. var source;
  16203. if (!this._sourcePositions) {
  16204. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16205. this._sourcePositions = new Float32Array(source);
  16206. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16207. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16208. }
  16209. }
  16210. if (!this._sourceNormals) {
  16211. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16212. this._sourceNormals = new Float32Array(source);
  16213. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16214. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16215. }
  16216. }
  16217. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16218. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16219. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16220. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16221. var skeletonMatrices = skeleton.getTransformMatrices();
  16222. var tempVector3 = BABYLON.Vector3.Zero();
  16223. var finalMatrix = new BABYLON.Matrix();
  16224. var tempMatrix = new BABYLON.Matrix();
  16225. for (var index = 0; index < positionsData.length; index += 3) {
  16226. var index4 = (index / 3) * 4;
  16227. var matricesWeight0 = matricesWeightsData[index4];
  16228. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16229. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16230. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16231. if (matricesWeight0 > 0) {
  16232. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16233. finalMatrix.addToSelf(tempMatrix);
  16234. }
  16235. if (matricesWeight1 > 0) {
  16236. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16237. finalMatrix.addToSelf(tempMatrix);
  16238. }
  16239. if (matricesWeight2 > 0) {
  16240. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16241. finalMatrix.addToSelf(tempMatrix);
  16242. }
  16243. if (matricesWeight3 > 0) {
  16244. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16245. finalMatrix.addToSelf(tempMatrix);
  16246. }
  16247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16248. tempVector3.toArray(positionsData, index);
  16249. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16250. tempVector3.toArray(normalsData, index);
  16251. finalMatrix.reset();
  16252. }
  16253. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16254. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16255. return this;
  16256. };
  16257. // Tools
  16258. Mesh.MinMax = function (meshes) {
  16259. var minVector = null;
  16260. var maxVector = null;
  16261. for (var i in meshes) {
  16262. var mesh = meshes[i];
  16263. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16264. if (!minVector) {
  16265. minVector = boundingBox.minimumWorld;
  16266. maxVector = boundingBox.maximumWorld;
  16267. continue;
  16268. }
  16269. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16270. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16271. }
  16272. return {
  16273. min: minVector,
  16274. max: maxVector
  16275. };
  16276. };
  16277. Mesh.Center = function (meshesOrMinMaxVector) {
  16278. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16279. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16280. };
  16281. /**
  16282. * Merge the array of meshes into a single mesh for performance reasons.
  16283. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16284. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16285. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16286. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16287. */
  16288. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16289. if (disposeSource === void 0) { disposeSource = true; }
  16290. var index;
  16291. if (!allow32BitsIndices) {
  16292. var totalVertices = 0;
  16293. // Counting vertices
  16294. for (index = 0; index < meshes.length; index++) {
  16295. if (meshes[index]) {
  16296. totalVertices += meshes[index].getTotalVertices();
  16297. if (totalVertices > 65536) {
  16298. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16299. return null;
  16300. }
  16301. }
  16302. }
  16303. }
  16304. // Merge
  16305. var vertexData;
  16306. var otherVertexData;
  16307. var source;
  16308. for (index = 0; index < meshes.length; index++) {
  16309. if (meshes[index]) {
  16310. meshes[index].computeWorldMatrix(true);
  16311. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16312. otherVertexData.transform(meshes[index].getWorldMatrix());
  16313. if (vertexData) {
  16314. vertexData.merge(otherVertexData);
  16315. }
  16316. else {
  16317. vertexData = otherVertexData;
  16318. source = meshes[index];
  16319. }
  16320. }
  16321. }
  16322. if (!meshSubclass) {
  16323. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16324. }
  16325. vertexData.applyToMesh(meshSubclass);
  16326. // Setting properties
  16327. meshSubclass.material = source.material;
  16328. meshSubclass.checkCollisions = source.checkCollisions;
  16329. // Cleaning
  16330. if (disposeSource) {
  16331. for (index = 0; index < meshes.length; index++) {
  16332. if (meshes[index]) {
  16333. meshes[index].dispose();
  16334. }
  16335. }
  16336. }
  16337. return meshSubclass;
  16338. };
  16339. // Consts
  16340. Mesh._FRONTSIDE = 0;
  16341. Mesh._BACKSIDE = 1;
  16342. Mesh._DOUBLESIDE = 2;
  16343. Mesh._DEFAULTSIDE = 0;
  16344. Mesh._NO_CAP = 0;
  16345. Mesh._CAP_START = 1;
  16346. Mesh._CAP_END = 2;
  16347. Mesh._CAP_ALL = 3;
  16348. return Mesh;
  16349. })(BABYLON.AbstractMesh);
  16350. BABYLON.Mesh = Mesh;
  16351. })(BABYLON || (BABYLON = {}));
  16352. var BABYLON;
  16353. (function (BABYLON) {
  16354. var SubMesh = (function () {
  16355. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16356. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16357. this.materialIndex = materialIndex;
  16358. this.verticesStart = verticesStart;
  16359. this.verticesCount = verticesCount;
  16360. this.indexStart = indexStart;
  16361. this.indexCount = indexCount;
  16362. this._renderId = 0;
  16363. this._mesh = mesh;
  16364. this._renderingMesh = renderingMesh || mesh;
  16365. mesh.subMeshes.push(this);
  16366. this._trianglePlanes = [];
  16367. this._id = mesh.subMeshes.length - 1;
  16368. if (createBoundingBox) {
  16369. this.refreshBoundingInfo();
  16370. mesh.computeWorldMatrix(true);
  16371. }
  16372. }
  16373. SubMesh.prototype.getBoundingInfo = function () {
  16374. return this._boundingInfo;
  16375. };
  16376. SubMesh.prototype.getMesh = function () {
  16377. return this._mesh;
  16378. };
  16379. SubMesh.prototype.getRenderingMesh = function () {
  16380. return this._renderingMesh;
  16381. };
  16382. SubMesh.prototype.getMaterial = function () {
  16383. var rootMaterial = this._renderingMesh.material;
  16384. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16385. var multiMaterial = rootMaterial;
  16386. return multiMaterial.getSubMaterial(this.materialIndex);
  16387. }
  16388. if (!rootMaterial) {
  16389. return this._mesh.getScene().defaultMaterial;
  16390. }
  16391. return rootMaterial;
  16392. };
  16393. // Methods
  16394. SubMesh.prototype.refreshBoundingInfo = function () {
  16395. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16396. if (!data) {
  16397. this._boundingInfo = this._mesh._boundingInfo;
  16398. return;
  16399. }
  16400. var indices = this._renderingMesh.getIndices();
  16401. var extend;
  16402. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16403. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16404. }
  16405. else {
  16406. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16407. }
  16408. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16409. };
  16410. SubMesh.prototype._checkCollision = function (collider) {
  16411. return this._boundingInfo._checkCollision(collider);
  16412. };
  16413. SubMesh.prototype.updateBoundingInfo = function (world) {
  16414. if (!this._boundingInfo) {
  16415. this.refreshBoundingInfo();
  16416. }
  16417. this._boundingInfo._update(world);
  16418. };
  16419. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16420. return this._boundingInfo.isInFrustum(frustumPlanes);
  16421. };
  16422. SubMesh.prototype.render = function (enableAlphaMode) {
  16423. this._renderingMesh.render(this, enableAlphaMode);
  16424. };
  16425. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16426. if (!this._linesIndexBuffer) {
  16427. var linesIndices = [];
  16428. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16429. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16430. }
  16431. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16432. this.linesIndexCount = linesIndices.length;
  16433. }
  16434. return this._linesIndexBuffer;
  16435. };
  16436. SubMesh.prototype.canIntersects = function (ray) {
  16437. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16438. };
  16439. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16440. var intersectInfo = null;
  16441. // Triangles test
  16442. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16443. var p0 = positions[indices[index]];
  16444. var p1 = positions[indices[index + 1]];
  16445. var p2 = positions[indices[index + 2]];
  16446. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16447. if (currentIntersectInfo) {
  16448. if (currentIntersectInfo.distance < 0) {
  16449. continue;
  16450. }
  16451. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16452. intersectInfo = currentIntersectInfo;
  16453. intersectInfo.faceId = index / 3;
  16454. if (fastCheck) {
  16455. break;
  16456. }
  16457. }
  16458. }
  16459. }
  16460. return intersectInfo;
  16461. };
  16462. // Clone
  16463. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16464. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16465. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16466. return result;
  16467. };
  16468. // Dispose
  16469. SubMesh.prototype.dispose = function () {
  16470. if (this._linesIndexBuffer) {
  16471. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16472. this._linesIndexBuffer = null;
  16473. }
  16474. // Remove from mesh
  16475. var index = this._mesh.subMeshes.indexOf(this);
  16476. this._mesh.subMeshes.splice(index, 1);
  16477. };
  16478. // Statics
  16479. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16480. var minVertexIndex = Number.MAX_VALUE;
  16481. var maxVertexIndex = -Number.MAX_VALUE;
  16482. renderingMesh = renderingMesh || mesh;
  16483. var indices = renderingMesh.getIndices();
  16484. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16485. var vertexIndex = indices[index];
  16486. if (vertexIndex < minVertexIndex)
  16487. minVertexIndex = vertexIndex;
  16488. if (vertexIndex > maxVertexIndex)
  16489. maxVertexIndex = vertexIndex;
  16490. }
  16491. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16492. };
  16493. return SubMesh;
  16494. })();
  16495. BABYLON.SubMesh = SubMesh;
  16496. })(BABYLON || (BABYLON = {}));
  16497. var BABYLON;
  16498. (function (BABYLON) {
  16499. var BaseTexture = (function () {
  16500. function BaseTexture(scene) {
  16501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16502. this.hasAlpha = false;
  16503. this.getAlphaFromRGB = false;
  16504. this.level = 1;
  16505. this.isCube = false;
  16506. this.isRenderTarget = false;
  16507. this.animations = new Array();
  16508. this.coordinatesIndex = 0;
  16509. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16510. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16511. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16512. this.anisotropicFilteringLevel = 4;
  16513. this._scene = scene;
  16514. this._scene.textures.push(this);
  16515. }
  16516. BaseTexture.prototype.getScene = function () {
  16517. return this._scene;
  16518. };
  16519. BaseTexture.prototype.getTextureMatrix = function () {
  16520. return null;
  16521. };
  16522. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16523. return null;
  16524. };
  16525. BaseTexture.prototype.getInternalTexture = function () {
  16526. return this._texture;
  16527. };
  16528. BaseTexture.prototype.isReady = function () {
  16529. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16530. return true;
  16531. }
  16532. if (this._texture) {
  16533. return this._texture.isReady;
  16534. }
  16535. return false;
  16536. };
  16537. BaseTexture.prototype.getSize = function () {
  16538. if (this._texture._width) {
  16539. return { width: this._texture._width, height: this._texture._height };
  16540. }
  16541. if (this._texture._size) {
  16542. return { width: this._texture._size, height: this._texture._size };
  16543. }
  16544. return { width: 0, height: 0 };
  16545. };
  16546. BaseTexture.prototype.getBaseSize = function () {
  16547. if (!this.isReady())
  16548. return { width: 0, height: 0 };
  16549. if (this._texture._size) {
  16550. return { width: this._texture._size, height: this._texture._size };
  16551. }
  16552. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16553. };
  16554. BaseTexture.prototype.scale = function (ratio) {
  16555. };
  16556. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16557. get: function () {
  16558. return false;
  16559. },
  16560. enumerable: true,
  16561. configurable: true
  16562. });
  16563. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16564. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16565. for (var index = 0; index < texturesCache.length; index++) {
  16566. var texturesCacheEntry = texturesCache[index];
  16567. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16568. texturesCache.splice(index, 1);
  16569. return;
  16570. }
  16571. }
  16572. };
  16573. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16574. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16575. for (var index = 0; index < texturesCache.length; index++) {
  16576. var texturesCacheEntry = texturesCache[index];
  16577. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16578. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16579. texturesCacheEntry.references++;
  16580. return texturesCacheEntry;
  16581. }
  16582. }
  16583. }
  16584. return null;
  16585. };
  16586. BaseTexture.prototype.delayLoad = function () {
  16587. };
  16588. BaseTexture.prototype.releaseInternalTexture = function () {
  16589. if (!this._texture) {
  16590. return;
  16591. }
  16592. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16593. this._texture.references--;
  16594. // Final reference ?
  16595. if (this._texture.references === 0) {
  16596. var index = texturesCache.indexOf(this._texture);
  16597. texturesCache.splice(index, 1);
  16598. this._scene.getEngine()._releaseTexture(this._texture);
  16599. delete this._texture;
  16600. }
  16601. };
  16602. BaseTexture.prototype.clone = function () {
  16603. return null;
  16604. };
  16605. BaseTexture.prototype.dispose = function () {
  16606. // Remove from scene
  16607. var index = this._scene.textures.indexOf(this);
  16608. if (index >= 0) {
  16609. this._scene.textures.splice(index, 1);
  16610. }
  16611. if (this._texture === undefined) {
  16612. return;
  16613. }
  16614. this.releaseInternalTexture();
  16615. // Callback
  16616. if (this.onDispose) {
  16617. this.onDispose();
  16618. }
  16619. };
  16620. return BaseTexture;
  16621. })();
  16622. BABYLON.BaseTexture = BaseTexture;
  16623. })(BABYLON || (BABYLON = {}));
  16624. var BABYLON;
  16625. (function (BABYLON) {
  16626. var Texture = (function (_super) {
  16627. __extends(Texture, _super);
  16628. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16629. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16630. if (onLoad === void 0) { onLoad = null; }
  16631. if (onError === void 0) { onError = null; }
  16632. if (buffer === void 0) { buffer = null; }
  16633. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16634. _super.call(this, scene);
  16635. this.uOffset = 0;
  16636. this.vOffset = 0;
  16637. this.uScale = 1.0;
  16638. this.vScale = 1.0;
  16639. this.uAng = 0;
  16640. this.vAng = 0;
  16641. this.wAng = 0;
  16642. this.name = url;
  16643. this.url = url;
  16644. this._noMipmap = noMipmap;
  16645. this._invertY = invertY;
  16646. this._samplingMode = samplingMode;
  16647. this._buffer = buffer;
  16648. this._deleteBuffer = deleteBuffer;
  16649. if (!url) {
  16650. return;
  16651. }
  16652. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16653. if (!this._texture) {
  16654. if (!scene.useDelayedTextureLoading) {
  16655. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16656. if (deleteBuffer) {
  16657. delete this._buffer;
  16658. }
  16659. }
  16660. else {
  16661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16662. }
  16663. }
  16664. else {
  16665. BABYLON.Tools.SetImmediate(function () {
  16666. if (onLoad) {
  16667. onLoad();
  16668. }
  16669. });
  16670. }
  16671. }
  16672. Texture.prototype.delayLoad = function () {
  16673. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16674. return;
  16675. }
  16676. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16677. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16678. if (!this._texture) {
  16679. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16680. if (this._deleteBuffer) {
  16681. delete this._buffer;
  16682. }
  16683. }
  16684. };
  16685. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16686. if (!this._texture) {
  16687. return;
  16688. }
  16689. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16690. };
  16691. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16692. x -= this.uOffset + 0.5;
  16693. y -= this.vOffset + 0.5;
  16694. z -= 0.5;
  16695. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16696. t.x *= this.uScale;
  16697. t.y *= this.vScale;
  16698. t.x += 0.5;
  16699. t.y += 0.5;
  16700. t.z += 0.5;
  16701. };
  16702. Texture.prototype.getTextureMatrix = function () {
  16703. if (this.uOffset === this._cachedUOffset &&
  16704. this.vOffset === this._cachedVOffset &&
  16705. this.uScale === this._cachedUScale &&
  16706. this.vScale === this._cachedVScale &&
  16707. this.uAng === this._cachedUAng &&
  16708. this.vAng === this._cachedVAng &&
  16709. this.wAng === this._cachedWAng) {
  16710. return this._cachedTextureMatrix;
  16711. }
  16712. this._cachedUOffset = this.uOffset;
  16713. this._cachedVOffset = this.vOffset;
  16714. this._cachedUScale = this.uScale;
  16715. this._cachedVScale = this.vScale;
  16716. this._cachedUAng = this.uAng;
  16717. this._cachedVAng = this.vAng;
  16718. this._cachedWAng = this.wAng;
  16719. if (!this._cachedTextureMatrix) {
  16720. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16721. this._rowGenerationMatrix = new BABYLON.Matrix();
  16722. this._t0 = BABYLON.Vector3.Zero();
  16723. this._t1 = BABYLON.Vector3.Zero();
  16724. this._t2 = BABYLON.Vector3.Zero();
  16725. }
  16726. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16727. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16728. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16729. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16730. this._t1.subtractInPlace(this._t0);
  16731. this._t2.subtractInPlace(this._t0);
  16732. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16733. this._cachedTextureMatrix.m[0] = this._t1.x;
  16734. this._cachedTextureMatrix.m[1] = this._t1.y;
  16735. this._cachedTextureMatrix.m[2] = this._t1.z;
  16736. this._cachedTextureMatrix.m[4] = this._t2.x;
  16737. this._cachedTextureMatrix.m[5] = this._t2.y;
  16738. this._cachedTextureMatrix.m[6] = this._t2.z;
  16739. this._cachedTextureMatrix.m[8] = this._t0.x;
  16740. this._cachedTextureMatrix.m[9] = this._t0.y;
  16741. this._cachedTextureMatrix.m[10] = this._t0.z;
  16742. return this._cachedTextureMatrix;
  16743. };
  16744. Texture.prototype.getReflectionTextureMatrix = function () {
  16745. if (this.uOffset === this._cachedUOffset &&
  16746. this.vOffset === this._cachedVOffset &&
  16747. this.uScale === this._cachedUScale &&
  16748. this.vScale === this._cachedVScale &&
  16749. this.coordinatesMode === this._cachedCoordinatesMode) {
  16750. return this._cachedTextureMatrix;
  16751. }
  16752. if (!this._cachedTextureMatrix) {
  16753. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16754. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16755. }
  16756. this._cachedCoordinatesMode = this.coordinatesMode;
  16757. switch (this.coordinatesMode) {
  16758. case Texture.SPHERICAL_MODE:
  16759. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16760. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16761. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16762. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16763. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16764. break;
  16765. case Texture.PLANAR_MODE:
  16766. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16767. this._cachedTextureMatrix[0] = this.uScale;
  16768. this._cachedTextureMatrix[5] = this.vScale;
  16769. this._cachedTextureMatrix[12] = this.uOffset;
  16770. this._cachedTextureMatrix[13] = this.vOffset;
  16771. break;
  16772. case Texture.PROJECTION_MODE:
  16773. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16774. this._projectionModeMatrix.m[0] = 0.5;
  16775. this._projectionModeMatrix.m[5] = -0.5;
  16776. this._projectionModeMatrix.m[10] = 0.0;
  16777. this._projectionModeMatrix.m[12] = 0.5;
  16778. this._projectionModeMatrix.m[13] = 0.5;
  16779. this._projectionModeMatrix.m[14] = 1.0;
  16780. this._projectionModeMatrix.m[15] = 1.0;
  16781. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16782. break;
  16783. default:
  16784. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16785. break;
  16786. }
  16787. return this._cachedTextureMatrix;
  16788. };
  16789. Texture.prototype.clone = function () {
  16790. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16791. // Base texture
  16792. newTexture.hasAlpha = this.hasAlpha;
  16793. newTexture.level = this.level;
  16794. newTexture.wrapU = this.wrapU;
  16795. newTexture.wrapV = this.wrapV;
  16796. newTexture.coordinatesIndex = this.coordinatesIndex;
  16797. newTexture.coordinatesMode = this.coordinatesMode;
  16798. // Texture
  16799. newTexture.uOffset = this.uOffset;
  16800. newTexture.vOffset = this.vOffset;
  16801. newTexture.uScale = this.uScale;
  16802. newTexture.vScale = this.vScale;
  16803. newTexture.uAng = this.uAng;
  16804. newTexture.vAng = this.vAng;
  16805. newTexture.wAng = this.wAng;
  16806. return newTexture;
  16807. };
  16808. // Statics
  16809. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16810. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16811. if (onLoad === void 0) { onLoad = null; }
  16812. if (onError === void 0) { onError = null; }
  16813. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16814. };
  16815. // Constants
  16816. Texture.NEAREST_SAMPLINGMODE = 1;
  16817. Texture.BILINEAR_SAMPLINGMODE = 2;
  16818. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16819. Texture.EXPLICIT_MODE = 0;
  16820. Texture.SPHERICAL_MODE = 1;
  16821. Texture.PLANAR_MODE = 2;
  16822. Texture.CUBIC_MODE = 3;
  16823. Texture.PROJECTION_MODE = 4;
  16824. Texture.SKYBOX_MODE = 5;
  16825. Texture.CLAMP_ADDRESSMODE = 0;
  16826. Texture.WRAP_ADDRESSMODE = 1;
  16827. Texture.MIRROR_ADDRESSMODE = 2;
  16828. return Texture;
  16829. })(BABYLON.BaseTexture);
  16830. BABYLON.Texture = Texture;
  16831. })(BABYLON || (BABYLON = {}));
  16832. var BABYLON;
  16833. (function (BABYLON) {
  16834. var CubeTexture = (function (_super) {
  16835. __extends(CubeTexture, _super);
  16836. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16837. _super.call(this, scene);
  16838. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16839. this.name = rootUrl;
  16840. this.url = rootUrl;
  16841. this._noMipmap = noMipmap;
  16842. this.hasAlpha = false;
  16843. this._texture = this._getFromCache(rootUrl, noMipmap);
  16844. if (!extensions) {
  16845. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16846. }
  16847. this._extensions = extensions;
  16848. if (!this._texture) {
  16849. if (!scene.useDelayedTextureLoading) {
  16850. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16851. }
  16852. else {
  16853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16854. }
  16855. }
  16856. this.isCube = true;
  16857. this._textureMatrix = BABYLON.Matrix.Identity();
  16858. }
  16859. CubeTexture.prototype.clone = function () {
  16860. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16861. // Base texture
  16862. newTexture.level = this.level;
  16863. newTexture.wrapU = this.wrapU;
  16864. newTexture.wrapV = this.wrapV;
  16865. newTexture.coordinatesIndex = this.coordinatesIndex;
  16866. newTexture.coordinatesMode = this.coordinatesMode;
  16867. return newTexture;
  16868. };
  16869. // Methods
  16870. CubeTexture.prototype.delayLoad = function () {
  16871. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16872. return;
  16873. }
  16874. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16875. this._texture = this._getFromCache(this.url, this._noMipmap);
  16876. if (!this._texture) {
  16877. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16878. }
  16879. };
  16880. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16881. return this._textureMatrix;
  16882. };
  16883. return CubeTexture;
  16884. })(BABYLON.BaseTexture);
  16885. BABYLON.CubeTexture = CubeTexture;
  16886. })(BABYLON || (BABYLON = {}));
  16887. var BABYLON;
  16888. (function (BABYLON) {
  16889. var RenderTargetTexture = (function (_super) {
  16890. __extends(RenderTargetTexture, _super);
  16891. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16892. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16893. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16894. _super.call(this, null, scene, !generateMipMaps);
  16895. this.renderList = new Array();
  16896. this.renderParticles = true;
  16897. this.renderSprites = false;
  16898. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16899. this._currentRefreshId = -1;
  16900. this._refreshRate = 1;
  16901. this.name = name;
  16902. this.isRenderTarget = true;
  16903. this._size = size;
  16904. this._generateMipMaps = generateMipMaps;
  16905. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16906. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16907. // Rendering groups
  16908. this._renderingManager = new BABYLON.RenderingManager(scene);
  16909. }
  16910. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16911. this._currentRefreshId = -1;
  16912. };
  16913. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16914. get: function () {
  16915. return this._refreshRate;
  16916. },
  16917. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16918. set: function (value) {
  16919. this._refreshRate = value;
  16920. this.resetRefreshCounter();
  16921. },
  16922. enumerable: true,
  16923. configurable: true
  16924. });
  16925. RenderTargetTexture.prototype._shouldRender = function () {
  16926. if (this._currentRefreshId === -1) {
  16927. this._currentRefreshId = 1;
  16928. return true;
  16929. }
  16930. if (this.refreshRate === this._currentRefreshId) {
  16931. this._currentRefreshId = 1;
  16932. return true;
  16933. }
  16934. this._currentRefreshId++;
  16935. return false;
  16936. };
  16937. RenderTargetTexture.prototype.isReady = function () {
  16938. if (!this.getScene().renderTargetsEnabled) {
  16939. return false;
  16940. }
  16941. return _super.prototype.isReady.call(this);
  16942. };
  16943. RenderTargetTexture.prototype.getRenderSize = function () {
  16944. return this._size;
  16945. };
  16946. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16947. get: function () {
  16948. return true;
  16949. },
  16950. enumerable: true,
  16951. configurable: true
  16952. });
  16953. RenderTargetTexture.prototype.scale = function (ratio) {
  16954. var newSize = this._size * ratio;
  16955. this.resize(newSize, this._generateMipMaps);
  16956. };
  16957. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16958. this.releaseInternalTexture();
  16959. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16960. };
  16961. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16962. var scene = this.getScene();
  16963. var engine = scene.getEngine();
  16964. if (this._waitingRenderList) {
  16965. this.renderList = [];
  16966. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16967. var id = this._waitingRenderList[index];
  16968. this.renderList.push(scene.getMeshByID(id));
  16969. }
  16970. delete this._waitingRenderList;
  16971. }
  16972. if (this.renderList && this.renderList.length === 0) {
  16973. return;
  16974. }
  16975. // Bind
  16976. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16977. engine.bindFramebuffer(this._texture);
  16978. }
  16979. this._renderingManager.reset();
  16980. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16981. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16982. var mesh = currentRenderList[meshIndex];
  16983. if (mesh) {
  16984. if (!mesh.isReady()) {
  16985. // Reset _currentRefreshId
  16986. this.resetRefreshCounter();
  16987. continue;
  16988. }
  16989. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16990. mesh._activate(scene.getRenderId());
  16991. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16992. var subMesh = mesh.subMeshes[subIndex];
  16993. scene._activeIndices += subMesh.indexCount;
  16994. this._renderingManager.dispatch(subMesh);
  16995. }
  16996. }
  16997. }
  16998. }
  16999. if (this.onBeforeRender) {
  17000. this.onBeforeRender();
  17001. }
  17002. // Clear
  17003. if (this.onClear) {
  17004. this.onClear(engine);
  17005. }
  17006. else {
  17007. engine.clear(scene.clearColor, true, true);
  17008. }
  17009. if (!this._doNotChangeAspectRatio) {
  17010. scene.updateTransformMatrix(true);
  17011. }
  17012. // Render
  17013. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17014. if (useCameraPostProcess) {
  17015. scene.postProcessManager._finalizeFrame(false, this._texture);
  17016. }
  17017. if (!this._doNotChangeAspectRatio) {
  17018. scene.updateTransformMatrix(true);
  17019. }
  17020. if (this.onAfterRender) {
  17021. this.onAfterRender();
  17022. }
  17023. // Dump ?
  17024. if (dumpForDebug) {
  17025. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17026. }
  17027. // Unbind
  17028. engine.unBindFramebuffer(this._texture);
  17029. if (this.onAfterUnbind) {
  17030. this.onAfterUnbind();
  17031. }
  17032. };
  17033. RenderTargetTexture.prototype.clone = function () {
  17034. var textureSize = this.getSize();
  17035. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17036. // Base texture
  17037. newTexture.hasAlpha = this.hasAlpha;
  17038. newTexture.level = this.level;
  17039. // RenderTarget Texture
  17040. newTexture.coordinatesMode = this.coordinatesMode;
  17041. newTexture.renderList = this.renderList.slice(0);
  17042. return newTexture;
  17043. };
  17044. return RenderTargetTexture;
  17045. })(BABYLON.Texture);
  17046. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17047. })(BABYLON || (BABYLON = {}));
  17048. var BABYLON;
  17049. (function (BABYLON) {
  17050. var ProceduralTexture = (function (_super) {
  17051. __extends(ProceduralTexture, _super);
  17052. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17053. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17054. _super.call(this, null, scene, !generateMipMaps);
  17055. this._currentRefreshId = -1;
  17056. this._refreshRate = 1;
  17057. this._vertexDeclaration = [2];
  17058. this._vertexStrideSize = 2 * 4;
  17059. this._uniforms = new Array();
  17060. this._samplers = new Array();
  17061. this._textures = new Array();
  17062. this._floats = new Array();
  17063. this._floatsArrays = {};
  17064. this._colors3 = new Array();
  17065. this._colors4 = new Array();
  17066. this._vectors2 = new Array();
  17067. this._vectors3 = new Array();
  17068. this._matrices = new Array();
  17069. this._fallbackTextureUsed = false;
  17070. scene._proceduralTextures.push(this);
  17071. this.name = name;
  17072. this.isRenderTarget = true;
  17073. this._size = size;
  17074. this._generateMipMaps = generateMipMaps;
  17075. this.setFragment(fragment);
  17076. this._fallbackTexture = fallbackTexture;
  17077. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17078. // VBO
  17079. var vertices = [];
  17080. vertices.push(1, 1);
  17081. vertices.push(-1, 1);
  17082. vertices.push(-1, -1);
  17083. vertices.push(1, -1);
  17084. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17085. // Indices
  17086. var indices = [];
  17087. indices.push(0);
  17088. indices.push(1);
  17089. indices.push(2);
  17090. indices.push(0);
  17091. indices.push(2);
  17092. indices.push(3);
  17093. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17094. }
  17095. ProceduralTexture.prototype.reset = function () {
  17096. if (this._effect === undefined) {
  17097. return;
  17098. }
  17099. var engine = this.getScene().getEngine();
  17100. engine._releaseEffect(this._effect);
  17101. };
  17102. ProceduralTexture.prototype.isReady = function () {
  17103. var _this = this;
  17104. var engine = this.getScene().getEngine();
  17105. var shaders;
  17106. if (!this._fragment) {
  17107. return false;
  17108. }
  17109. if (this._fallbackTextureUsed) {
  17110. return true;
  17111. }
  17112. if (this._fragment.fragmentElement !== undefined) {
  17113. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17114. }
  17115. else {
  17116. shaders = { vertex: "procedural", fragment: this._fragment };
  17117. }
  17118. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17119. _this.releaseInternalTexture();
  17120. if (_this._fallbackTexture) {
  17121. _this._texture = _this._fallbackTexture._texture;
  17122. _this._texture.references++;
  17123. }
  17124. _this._fallbackTextureUsed = true;
  17125. });
  17126. return this._effect.isReady();
  17127. };
  17128. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17129. this._currentRefreshId = -1;
  17130. };
  17131. ProceduralTexture.prototype.setFragment = function (fragment) {
  17132. this._fragment = fragment;
  17133. };
  17134. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17135. get: function () {
  17136. return this._refreshRate;
  17137. },
  17138. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17139. set: function (value) {
  17140. this._refreshRate = value;
  17141. this.resetRefreshCounter();
  17142. },
  17143. enumerable: true,
  17144. configurable: true
  17145. });
  17146. ProceduralTexture.prototype._shouldRender = function () {
  17147. if (!this.isReady() || !this._texture) {
  17148. return false;
  17149. }
  17150. if (this._fallbackTextureUsed) {
  17151. return false;
  17152. }
  17153. if (this._currentRefreshId === -1) {
  17154. this._currentRefreshId = 1;
  17155. return true;
  17156. }
  17157. if (this.refreshRate === this._currentRefreshId) {
  17158. this._currentRefreshId = 1;
  17159. return true;
  17160. }
  17161. this._currentRefreshId++;
  17162. return false;
  17163. };
  17164. ProceduralTexture.prototype.getRenderSize = function () {
  17165. return this._size;
  17166. };
  17167. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17168. if (this._fallbackTextureUsed) {
  17169. return;
  17170. }
  17171. this.releaseInternalTexture();
  17172. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17173. };
  17174. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17175. if (this._uniforms.indexOf(uniformName) === -1) {
  17176. this._uniforms.push(uniformName);
  17177. }
  17178. };
  17179. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17180. if (this._samplers.indexOf(name) === -1) {
  17181. this._samplers.push(name);
  17182. }
  17183. this._textures[name] = texture;
  17184. return this;
  17185. };
  17186. ProceduralTexture.prototype.setFloat = function (name, value) {
  17187. this._checkUniform(name);
  17188. this._floats[name] = value;
  17189. return this;
  17190. };
  17191. ProceduralTexture.prototype.setFloats = function (name, value) {
  17192. this._checkUniform(name);
  17193. this._floatsArrays[name] = value;
  17194. return this;
  17195. };
  17196. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17197. this._checkUniform(name);
  17198. this._colors3[name] = value;
  17199. return this;
  17200. };
  17201. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17202. this._checkUniform(name);
  17203. this._colors4[name] = value;
  17204. return this;
  17205. };
  17206. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17207. this._checkUniform(name);
  17208. this._vectors2[name] = value;
  17209. return this;
  17210. };
  17211. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17212. this._checkUniform(name);
  17213. this._vectors3[name] = value;
  17214. return this;
  17215. };
  17216. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17217. this._checkUniform(name);
  17218. this._matrices[name] = value;
  17219. return this;
  17220. };
  17221. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17222. var scene = this.getScene();
  17223. var engine = scene.getEngine();
  17224. engine.bindFramebuffer(this._texture);
  17225. // Clear
  17226. engine.clear(scene.clearColor, true, true);
  17227. // Render
  17228. engine.enableEffect(this._effect);
  17229. engine.setState(false);
  17230. // Texture
  17231. for (var name in this._textures) {
  17232. this._effect.setTexture(name, this._textures[name]);
  17233. }
  17234. // Float
  17235. for (name in this._floats) {
  17236. this._effect.setFloat(name, this._floats[name]);
  17237. }
  17238. // Floats
  17239. for (name in this._floatsArrays) {
  17240. this._effect.setArray(name, this._floatsArrays[name]);
  17241. }
  17242. // Color3
  17243. for (name in this._colors3) {
  17244. this._effect.setColor3(name, this._colors3[name]);
  17245. }
  17246. // Color4
  17247. for (name in this._colors4) {
  17248. var color = this._colors4[name];
  17249. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17250. }
  17251. // Vector2
  17252. for (name in this._vectors2) {
  17253. this._effect.setVector2(name, this._vectors2[name]);
  17254. }
  17255. // Vector3
  17256. for (name in this._vectors3) {
  17257. this._effect.setVector3(name, this._vectors3[name]);
  17258. }
  17259. // Matrix
  17260. for (name in this._matrices) {
  17261. this._effect.setMatrix(name, this._matrices[name]);
  17262. }
  17263. // VBOs
  17264. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17265. // Draw order
  17266. engine.draw(true, 0, 6);
  17267. // Unbind
  17268. engine.unBindFramebuffer(this._texture);
  17269. };
  17270. ProceduralTexture.prototype.clone = function () {
  17271. var textureSize = this.getSize();
  17272. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17273. // Base texture
  17274. newTexture.hasAlpha = this.hasAlpha;
  17275. newTexture.level = this.level;
  17276. // RenderTarget Texture
  17277. newTexture.coordinatesMode = this.coordinatesMode;
  17278. return newTexture;
  17279. };
  17280. ProceduralTexture.prototype.dispose = function () {
  17281. var index = this.getScene()._proceduralTextures.indexOf(this);
  17282. if (index >= 0) {
  17283. this.getScene()._proceduralTextures.splice(index, 1);
  17284. }
  17285. _super.prototype.dispose.call(this);
  17286. };
  17287. return ProceduralTexture;
  17288. })(BABYLON.Texture);
  17289. BABYLON.ProceduralTexture = ProceduralTexture;
  17290. })(BABYLON || (BABYLON = {}));
  17291. var BABYLON;
  17292. (function (BABYLON) {
  17293. var MirrorTexture = (function (_super) {
  17294. __extends(MirrorTexture, _super);
  17295. function MirrorTexture(name, size, scene, generateMipMaps) {
  17296. var _this = this;
  17297. _super.call(this, name, size, scene, generateMipMaps, true);
  17298. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17299. this._transformMatrix = BABYLON.Matrix.Zero();
  17300. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17301. this.onBeforeRender = function () {
  17302. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17303. _this._savedViewMatrix = scene.getViewMatrix();
  17304. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17305. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17306. scene.clipPlane = _this.mirrorPlane;
  17307. scene.getEngine().cullBackFaces = false;
  17308. };
  17309. this.onAfterRender = function () {
  17310. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17311. scene.getEngine().cullBackFaces = true;
  17312. delete scene.clipPlane;
  17313. };
  17314. }
  17315. MirrorTexture.prototype.clone = function () {
  17316. var textureSize = this.getSize();
  17317. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17318. // Base texture
  17319. newTexture.hasAlpha = this.hasAlpha;
  17320. newTexture.level = this.level;
  17321. // Mirror Texture
  17322. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17323. newTexture.renderList = this.renderList.slice(0);
  17324. return newTexture;
  17325. };
  17326. return MirrorTexture;
  17327. })(BABYLON.RenderTargetTexture);
  17328. BABYLON.MirrorTexture = MirrorTexture;
  17329. })(BABYLON || (BABYLON = {}));
  17330. var BABYLON;
  17331. (function (BABYLON) {
  17332. var DynamicTexture = (function (_super) {
  17333. __extends(DynamicTexture, _super);
  17334. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17336. _super.call(this, null, scene, !generateMipMaps);
  17337. this.name = name;
  17338. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17339. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17340. this._generateMipMaps = generateMipMaps;
  17341. if (options.getContext) {
  17342. this._canvas = options;
  17343. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17344. }
  17345. else {
  17346. this._canvas = document.createElement("canvas");
  17347. if (options.width) {
  17348. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17349. }
  17350. else {
  17351. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17352. }
  17353. }
  17354. var textureSize = this.getSize();
  17355. this._canvas.width = textureSize.width;
  17356. this._canvas.height = textureSize.height;
  17357. this._context = this._canvas.getContext("2d");
  17358. }
  17359. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17360. get: function () {
  17361. return true;
  17362. },
  17363. enumerable: true,
  17364. configurable: true
  17365. });
  17366. DynamicTexture.prototype.scale = function (ratio) {
  17367. var textureSize = this.getSize();
  17368. textureSize.width *= ratio;
  17369. textureSize.height *= ratio;
  17370. this._canvas.width = textureSize.width;
  17371. this._canvas.height = textureSize.height;
  17372. this.releaseInternalTexture();
  17373. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17374. };
  17375. DynamicTexture.prototype.getContext = function () {
  17376. return this._context;
  17377. };
  17378. DynamicTexture.prototype.clear = function () {
  17379. var size = this.getSize();
  17380. this._context.fillRect(0, 0, size.width, size.height);
  17381. };
  17382. DynamicTexture.prototype.update = function (invertY) {
  17383. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17384. };
  17385. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17386. if (update === void 0) { update = true; }
  17387. var size = this.getSize();
  17388. if (clearColor) {
  17389. this._context.fillStyle = clearColor;
  17390. this._context.fillRect(0, 0, size.width, size.height);
  17391. }
  17392. this._context.font = font;
  17393. if (x === null) {
  17394. var textSize = this._context.measureText(text);
  17395. x = (size.width - textSize.width) / 2;
  17396. }
  17397. this._context.fillStyle = color;
  17398. this._context.fillText(text, x, y);
  17399. if (update) {
  17400. this.update(invertY);
  17401. }
  17402. };
  17403. DynamicTexture.prototype.clone = function () {
  17404. var textureSize = this.getSize();
  17405. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17406. // Base texture
  17407. newTexture.hasAlpha = this.hasAlpha;
  17408. newTexture.level = this.level;
  17409. // Dynamic Texture
  17410. newTexture.wrapU = this.wrapU;
  17411. newTexture.wrapV = this.wrapV;
  17412. return newTexture;
  17413. };
  17414. return DynamicTexture;
  17415. })(BABYLON.Texture);
  17416. BABYLON.DynamicTexture = DynamicTexture;
  17417. })(BABYLON || (BABYLON = {}));
  17418. var BABYLON;
  17419. (function (BABYLON) {
  17420. var VideoTexture = (function (_super) {
  17421. __extends(VideoTexture, _super);
  17422. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17423. var _this = this;
  17424. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17425. if (invertY === void 0) { invertY = false; }
  17426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17427. _super.call(this, null, scene, !generateMipMaps, invertY);
  17428. this._autoLaunch = true;
  17429. this.name = name;
  17430. this.video = document.createElement("video");
  17431. this.video.autoplay = false;
  17432. this.video.loop = true;
  17433. this.video.addEventListener("canplaythrough", function () {
  17434. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17435. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17436. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17437. }
  17438. else {
  17439. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17440. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17441. generateMipMaps = false;
  17442. }
  17443. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17444. _this._texture.isReady = true;
  17445. });
  17446. urls.forEach(function (url) {
  17447. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17448. var source = document.createElement("source");
  17449. source.src = url;
  17450. _this.video.appendChild(source);
  17451. });
  17452. this._lastUpdate = BABYLON.Tools.Now;
  17453. }
  17454. VideoTexture.prototype.update = function () {
  17455. if (this._autoLaunch) {
  17456. this._autoLaunch = false;
  17457. this.video.play();
  17458. }
  17459. var now = BABYLON.Tools.Now;
  17460. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17461. return false;
  17462. }
  17463. this._lastUpdate = now;
  17464. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17465. return true;
  17466. };
  17467. return VideoTexture;
  17468. })(BABYLON.Texture);
  17469. BABYLON.VideoTexture = VideoTexture;
  17470. })(BABYLON || (BABYLON = {}));
  17471. var BABYLON;
  17472. (function (BABYLON) {
  17473. var CustomProceduralTexture = (function (_super) {
  17474. __extends(CustomProceduralTexture, _super);
  17475. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17476. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17477. this._animate = true;
  17478. this._time = 0;
  17479. this._texturePath = texturePath;
  17480. //Try to load json
  17481. this.loadJson(texturePath);
  17482. this.refreshRate = 1;
  17483. }
  17484. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17485. var _this = this;
  17486. var that = this;
  17487. function noConfigFile() {
  17488. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17489. try {
  17490. that.setFragment(that._texturePath);
  17491. }
  17492. catch (ex) {
  17493. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17494. }
  17495. }
  17496. var configFileUrl = jsonUrl + "/config.json";
  17497. var xhr = new XMLHttpRequest();
  17498. xhr.open("GET", configFileUrl, true);
  17499. xhr.addEventListener("load", function () {
  17500. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17501. try {
  17502. _this._config = JSON.parse(xhr.response);
  17503. _this.updateShaderUniforms();
  17504. _this.updateTextures();
  17505. _this.setFragment(_this._texturePath + "/custom");
  17506. _this._animate = _this._config.animate;
  17507. _this.refreshRate = _this._config.refreshrate;
  17508. }
  17509. catch (ex) {
  17510. noConfigFile();
  17511. }
  17512. }
  17513. else {
  17514. noConfigFile();
  17515. }
  17516. }, false);
  17517. xhr.addEventListener("error", function () {
  17518. noConfigFile();
  17519. }, false);
  17520. try {
  17521. xhr.send();
  17522. }
  17523. catch (ex) {
  17524. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17525. }
  17526. };
  17527. CustomProceduralTexture.prototype.isReady = function () {
  17528. if (!_super.prototype.isReady.call(this)) {
  17529. return false;
  17530. }
  17531. for (var name in this._textures) {
  17532. var texture = this._textures[name];
  17533. if (!texture.isReady()) {
  17534. return false;
  17535. }
  17536. }
  17537. return true;
  17538. };
  17539. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17540. if (this._animate) {
  17541. this._time += this.getScene().getAnimationRatio() * 0.03;
  17542. this.updateShaderUniforms();
  17543. }
  17544. _super.prototype.render.call(this, useCameraPostProcess);
  17545. };
  17546. CustomProceduralTexture.prototype.updateTextures = function () {
  17547. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17548. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17549. }
  17550. };
  17551. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17552. if (this._config) {
  17553. for (var j = 0; j < this._config.uniforms.length; j++) {
  17554. var uniform = this._config.uniforms[j];
  17555. switch (uniform.type) {
  17556. case "float":
  17557. this.setFloat(uniform.name, uniform.value);
  17558. break;
  17559. case "color3":
  17560. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17561. break;
  17562. case "color4":
  17563. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17564. break;
  17565. case "vector2":
  17566. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17567. break;
  17568. case "vector3":
  17569. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17570. break;
  17571. }
  17572. }
  17573. }
  17574. this.setFloat("time", this._time);
  17575. };
  17576. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17577. get: function () {
  17578. return this._animate;
  17579. },
  17580. set: function (value) {
  17581. this._animate = value;
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. return CustomProceduralTexture;
  17587. })(BABYLON.ProceduralTexture);
  17588. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17589. })(BABYLON || (BABYLON = {}));
  17590. var BABYLON;
  17591. (function (BABYLON) {
  17592. var WoodProceduralTexture = (function (_super) {
  17593. __extends(WoodProceduralTexture, _super);
  17594. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17595. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17596. this._ampScale = 100.0;
  17597. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17598. this.updateShaderUniforms();
  17599. this.refreshRate = 0;
  17600. }
  17601. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17602. this.setFloat("ampScale", this._ampScale);
  17603. this.setColor3("woodColor", this._woodColor);
  17604. };
  17605. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17606. get: function () {
  17607. return this._ampScale;
  17608. },
  17609. set: function (value) {
  17610. this._ampScale = value;
  17611. this.updateShaderUniforms();
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17617. get: function () {
  17618. return this._woodColor;
  17619. },
  17620. set: function (value) {
  17621. this._woodColor = value;
  17622. this.updateShaderUniforms();
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. return WoodProceduralTexture;
  17628. })(BABYLON.ProceduralTexture);
  17629. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17630. var FireProceduralTexture = (function (_super) {
  17631. __extends(FireProceduralTexture, _super);
  17632. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17633. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17634. this._time = 0.0;
  17635. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17636. this._autoGenerateTime = true;
  17637. this._alphaThreshold = 0.5;
  17638. this._fireColors = FireProceduralTexture.RedFireColors;
  17639. this.updateShaderUniforms();
  17640. this.refreshRate = 1;
  17641. }
  17642. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17643. this.setFloat("time", this._time);
  17644. this.setVector2("speed", this._speed);
  17645. this.setColor3("c1", this._fireColors[0]);
  17646. this.setColor3("c2", this._fireColors[1]);
  17647. this.setColor3("c3", this._fireColors[2]);
  17648. this.setColor3("c4", this._fireColors[3]);
  17649. this.setColor3("c5", this._fireColors[4]);
  17650. this.setColor3("c6", this._fireColors[5]);
  17651. this.setFloat("alphaThreshold", this._alphaThreshold);
  17652. };
  17653. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17654. if (this._autoGenerateTime) {
  17655. this._time += this.getScene().getAnimationRatio() * 0.03;
  17656. this.updateShaderUniforms();
  17657. }
  17658. _super.prototype.render.call(this, useCameraPostProcess);
  17659. };
  17660. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17661. get: function () {
  17662. return [
  17663. new BABYLON.Color3(0.5, 0.0, 1.0),
  17664. new BABYLON.Color3(0.9, 0.0, 1.0),
  17665. new BABYLON.Color3(0.2, 0.0, 1.0),
  17666. new BABYLON.Color3(1.0, 0.9, 1.0),
  17667. new BABYLON.Color3(0.1, 0.1, 1.0),
  17668. new BABYLON.Color3(0.9, 0.9, 1.0)
  17669. ];
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17675. get: function () {
  17676. return [
  17677. new BABYLON.Color3(0.5, 1.0, 0.0),
  17678. new BABYLON.Color3(0.5, 1.0, 0.0),
  17679. new BABYLON.Color3(0.3, 0.4, 0.0),
  17680. new BABYLON.Color3(0.5, 1.0, 0.0),
  17681. new BABYLON.Color3(0.2, 0.0, 0.0),
  17682. new BABYLON.Color3(0.5, 1.0, 0.0)
  17683. ];
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17689. get: function () {
  17690. return [
  17691. new BABYLON.Color3(0.5, 0.0, 0.1),
  17692. new BABYLON.Color3(0.9, 0.0, 0.0),
  17693. new BABYLON.Color3(0.2, 0.0, 0.0),
  17694. new BABYLON.Color3(1.0, 0.9, 0.0),
  17695. new BABYLON.Color3(0.1, 0.1, 0.1),
  17696. new BABYLON.Color3(0.9, 0.9, 0.9)
  17697. ];
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17703. get: function () {
  17704. return [
  17705. new BABYLON.Color3(0.1, 0.0, 0.5),
  17706. new BABYLON.Color3(0.0, 0.0, 0.5),
  17707. new BABYLON.Color3(0.1, 0.0, 0.2),
  17708. new BABYLON.Color3(0.0, 0.0, 1.0),
  17709. new BABYLON.Color3(0.1, 0.2, 0.3),
  17710. new BABYLON.Color3(0.0, 0.2, 0.9)
  17711. ];
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17717. get: function () {
  17718. return this._fireColors;
  17719. },
  17720. set: function (value) {
  17721. this._fireColors = value;
  17722. this.updateShaderUniforms();
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17728. get: function () {
  17729. return this._time;
  17730. },
  17731. set: function (value) {
  17732. this._time = value;
  17733. this.updateShaderUniforms();
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17739. get: function () {
  17740. return this._speed;
  17741. },
  17742. set: function (value) {
  17743. this._speed = value;
  17744. this.updateShaderUniforms();
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17750. get: function () {
  17751. return this._alphaThreshold;
  17752. },
  17753. set: function (value) {
  17754. this._alphaThreshold = value;
  17755. this.updateShaderUniforms();
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. return FireProceduralTexture;
  17761. })(BABYLON.ProceduralTexture);
  17762. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17763. var CloudProceduralTexture = (function (_super) {
  17764. __extends(CloudProceduralTexture, _super);
  17765. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17766. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17767. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17768. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17769. this.updateShaderUniforms();
  17770. this.refreshRate = 0;
  17771. }
  17772. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17773. this.setColor4("skyColor", this._skyColor);
  17774. this.setColor4("cloudColor", this._cloudColor);
  17775. };
  17776. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17777. get: function () {
  17778. return this._skyColor;
  17779. },
  17780. set: function (value) {
  17781. this._skyColor = value;
  17782. this.updateShaderUniforms();
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17788. get: function () {
  17789. return this._cloudColor;
  17790. },
  17791. set: function (value) {
  17792. this._cloudColor = value;
  17793. this.updateShaderUniforms();
  17794. },
  17795. enumerable: true,
  17796. configurable: true
  17797. });
  17798. return CloudProceduralTexture;
  17799. })(BABYLON.ProceduralTexture);
  17800. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17801. var GrassProceduralTexture = (function (_super) {
  17802. __extends(GrassProceduralTexture, _super);
  17803. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17804. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17805. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17806. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17807. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17808. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17809. this._grassColors = [
  17810. new BABYLON.Color3(0.29, 0.38, 0.02),
  17811. new BABYLON.Color3(0.36, 0.49, 0.09),
  17812. new BABYLON.Color3(0.51, 0.6, 0.28)
  17813. ];
  17814. this.updateShaderUniforms();
  17815. this.refreshRate = 0;
  17816. }
  17817. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17818. this.setColor3("herb1Color", this._grassColors[0]);
  17819. this.setColor3("herb2Color", this._grassColors[1]);
  17820. this.setColor3("herb3Color", this._grassColors[2]);
  17821. this.setColor3("groundColor", this._groundColor);
  17822. };
  17823. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17824. get: function () {
  17825. return this._grassColors;
  17826. },
  17827. set: function (value) {
  17828. this._grassColors = value;
  17829. this.updateShaderUniforms();
  17830. },
  17831. enumerable: true,
  17832. configurable: true
  17833. });
  17834. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17835. get: function () {
  17836. return this._groundColor;
  17837. },
  17838. set: function (value) {
  17839. this.groundColor = value;
  17840. this.updateShaderUniforms();
  17841. },
  17842. enumerable: true,
  17843. configurable: true
  17844. });
  17845. return GrassProceduralTexture;
  17846. })(BABYLON.ProceduralTexture);
  17847. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17848. var RoadProceduralTexture = (function (_super) {
  17849. __extends(RoadProceduralTexture, _super);
  17850. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17851. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17852. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17853. this.updateShaderUniforms();
  17854. this.refreshRate = 0;
  17855. }
  17856. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17857. this.setColor3("roadColor", this._roadColor);
  17858. };
  17859. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17860. get: function () {
  17861. return this._roadColor;
  17862. },
  17863. set: function (value) {
  17864. this._roadColor = value;
  17865. this.updateShaderUniforms();
  17866. },
  17867. enumerable: true,
  17868. configurable: true
  17869. });
  17870. return RoadProceduralTexture;
  17871. })(BABYLON.ProceduralTexture);
  17872. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17873. var BrickProceduralTexture = (function (_super) {
  17874. __extends(BrickProceduralTexture, _super);
  17875. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17876. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17877. this._numberOfBricksHeight = 15;
  17878. this._numberOfBricksWidth = 5;
  17879. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17880. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17881. this.updateShaderUniforms();
  17882. this.refreshRate = 0;
  17883. }
  17884. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17885. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17886. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17887. this.setColor3("brickColor", this._brickColor);
  17888. this.setColor3("jointColor", this._jointColor);
  17889. };
  17890. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17891. get: function () {
  17892. return this._numberOfBricksHeight;
  17893. },
  17894. set: function (value) {
  17895. this._numberOfBricksHeight = value;
  17896. this.updateShaderUniforms();
  17897. },
  17898. enumerable: true,
  17899. configurable: true
  17900. });
  17901. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17902. get: function () {
  17903. return this._numberOfBricksWidth;
  17904. },
  17905. set: function (value) {
  17906. this._numberOfBricksWidth = value;
  17907. this.updateShaderUniforms();
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17913. get: function () {
  17914. return this._jointColor;
  17915. },
  17916. set: function (value) {
  17917. this._jointColor = value;
  17918. this.updateShaderUniforms();
  17919. },
  17920. enumerable: true,
  17921. configurable: true
  17922. });
  17923. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17924. get: function () {
  17925. return this._brickColor;
  17926. },
  17927. set: function (value) {
  17928. this._brickColor = value;
  17929. this.updateShaderUniforms();
  17930. },
  17931. enumerable: true,
  17932. configurable: true
  17933. });
  17934. return BrickProceduralTexture;
  17935. })(BABYLON.ProceduralTexture);
  17936. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17937. var MarbleProceduralTexture = (function (_super) {
  17938. __extends(MarbleProceduralTexture, _super);
  17939. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17940. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17941. this._numberOfTilesHeight = 3;
  17942. this._numberOfTilesWidth = 3;
  17943. this._amplitude = 9.0;
  17944. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17945. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17946. this.updateShaderUniforms();
  17947. this.refreshRate = 0;
  17948. }
  17949. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17950. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17951. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17952. this.setFloat("amplitude", this._amplitude);
  17953. this.setColor3("marbleColor", this._marbleColor);
  17954. this.setColor3("jointColor", this._jointColor);
  17955. };
  17956. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17957. get: function () {
  17958. return this._numberOfTilesHeight;
  17959. },
  17960. set: function (value) {
  17961. this._numberOfTilesHeight = value;
  17962. this.updateShaderUniforms();
  17963. },
  17964. enumerable: true,
  17965. configurable: true
  17966. });
  17967. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17968. get: function () {
  17969. return this._numberOfTilesWidth;
  17970. },
  17971. set: function (value) {
  17972. this._numberOfTilesWidth = value;
  17973. this.updateShaderUniforms();
  17974. },
  17975. enumerable: true,
  17976. configurable: true
  17977. });
  17978. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17979. get: function () {
  17980. return this._jointColor;
  17981. },
  17982. set: function (value) {
  17983. this._jointColor = value;
  17984. this.updateShaderUniforms();
  17985. },
  17986. enumerable: true,
  17987. configurable: true
  17988. });
  17989. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17990. get: function () {
  17991. return this._marbleColor;
  17992. },
  17993. set: function (value) {
  17994. this._marbleColor = value;
  17995. this.updateShaderUniforms();
  17996. },
  17997. enumerable: true,
  17998. configurable: true
  17999. });
  18000. return MarbleProceduralTexture;
  18001. })(BABYLON.ProceduralTexture);
  18002. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18003. })(BABYLON || (BABYLON = {}));
  18004. var BABYLON;
  18005. (function (BABYLON) {
  18006. var EffectFallbacks = (function () {
  18007. function EffectFallbacks() {
  18008. this._defines = {};
  18009. this._currentRank = 32;
  18010. this._maxRank = -1;
  18011. }
  18012. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18013. if (!this._defines[rank]) {
  18014. if (rank < this._currentRank) {
  18015. this._currentRank = rank;
  18016. }
  18017. if (rank > this._maxRank) {
  18018. this._maxRank = rank;
  18019. }
  18020. this._defines[rank] = new Array();
  18021. }
  18022. this._defines[rank].push(define);
  18023. };
  18024. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18025. get: function () {
  18026. return this._currentRank <= this._maxRank;
  18027. },
  18028. enumerable: true,
  18029. configurable: true
  18030. });
  18031. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18032. var currentFallbacks = this._defines[this._currentRank];
  18033. for (var index = 0; index < currentFallbacks.length; index++) {
  18034. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18035. }
  18036. this._currentRank++;
  18037. return currentDefines;
  18038. };
  18039. return EffectFallbacks;
  18040. })();
  18041. BABYLON.EffectFallbacks = EffectFallbacks;
  18042. var Effect = (function () {
  18043. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18044. var _this = this;
  18045. this._isReady = false;
  18046. this._compilationError = "";
  18047. this._valueCache = [];
  18048. this._engine = engine;
  18049. this.name = baseName;
  18050. this.defines = defines;
  18051. this._uniformsNames = uniformsNames.concat(samplers);
  18052. this._samplers = samplers;
  18053. this._attributesNames = attributesNames;
  18054. this.onError = onError;
  18055. this.onCompiled = onCompiled;
  18056. var vertexSource;
  18057. var fragmentSource;
  18058. if (baseName.vertexElement) {
  18059. vertexSource = document.getElementById(baseName.vertexElement);
  18060. if (!vertexSource) {
  18061. vertexSource = baseName.vertexElement;
  18062. }
  18063. }
  18064. else {
  18065. vertexSource = baseName.vertex || baseName;
  18066. }
  18067. if (baseName.fragmentElement) {
  18068. fragmentSource = document.getElementById(baseName.fragmentElement);
  18069. if (!fragmentSource) {
  18070. fragmentSource = baseName.fragmentElement;
  18071. }
  18072. }
  18073. else {
  18074. fragmentSource = baseName.fragment || baseName;
  18075. }
  18076. this._loadVertexShader(vertexSource, function (vertexCode) {
  18077. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18078. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18079. });
  18080. });
  18081. }
  18082. // Properties
  18083. Effect.prototype.isReady = function () {
  18084. return this._isReady;
  18085. };
  18086. Effect.prototype.getProgram = function () {
  18087. return this._program;
  18088. };
  18089. Effect.prototype.getAttributesNames = function () {
  18090. return this._attributesNames;
  18091. };
  18092. Effect.prototype.getAttributeLocation = function (index) {
  18093. return this._attributes[index];
  18094. };
  18095. Effect.prototype.getAttributeLocationByName = function (name) {
  18096. var index = this._attributesNames.indexOf(name);
  18097. return this._attributes[index];
  18098. };
  18099. Effect.prototype.getAttributesCount = function () {
  18100. return this._attributes.length;
  18101. };
  18102. Effect.prototype.getUniformIndex = function (uniformName) {
  18103. return this._uniformsNames.indexOf(uniformName);
  18104. };
  18105. Effect.prototype.getUniform = function (uniformName) {
  18106. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18107. };
  18108. Effect.prototype.getSamplers = function () {
  18109. return this._samplers;
  18110. };
  18111. Effect.prototype.getCompilationError = function () {
  18112. return this._compilationError;
  18113. };
  18114. // Methods
  18115. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18116. // DOM element ?
  18117. if (vertex instanceof HTMLElement) {
  18118. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18119. callback(vertexCode);
  18120. return;
  18121. }
  18122. // Is in local store ?
  18123. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18124. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18125. return;
  18126. }
  18127. var vertexShaderUrl;
  18128. if (vertex[0] === "." || vertex[0] === "/") {
  18129. vertexShaderUrl = vertex;
  18130. }
  18131. else {
  18132. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18133. }
  18134. // Vertex shader
  18135. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18136. };
  18137. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18138. // DOM element ?
  18139. if (fragment instanceof HTMLElement) {
  18140. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18141. callback(fragmentCode);
  18142. return;
  18143. }
  18144. // Is in local store ?
  18145. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18146. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18147. return;
  18148. }
  18149. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18150. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18151. return;
  18152. }
  18153. var fragmentShaderUrl;
  18154. if (fragment[0] === "." || fragment[0] === "/") {
  18155. fragmentShaderUrl = fragment;
  18156. }
  18157. else {
  18158. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18159. }
  18160. // Fragment shader
  18161. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18162. };
  18163. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18164. try {
  18165. var engine = this._engine;
  18166. if (!engine.getCaps().highPrecisionShaderSupported) {
  18167. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18168. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18169. }
  18170. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18171. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18172. this._attributes = engine.getAttributes(this._program, attributesNames);
  18173. for (var index = 0; index < this._samplers.length; index++) {
  18174. var sampler = this.getUniform(this._samplers[index]);
  18175. if (sampler == null) {
  18176. this._samplers.splice(index, 1);
  18177. index--;
  18178. }
  18179. }
  18180. engine.bindSamplers(this);
  18181. this._isReady = true;
  18182. if (this.onCompiled) {
  18183. this.onCompiled(this);
  18184. }
  18185. }
  18186. catch (e) {
  18187. // Is it a problem with precision?
  18188. if (e.message.indexOf("highp") !== -1) {
  18189. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18190. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18191. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18192. return;
  18193. }
  18194. // Let's go through fallbacks then
  18195. if (fallbacks && fallbacks.isMoreFallbacks) {
  18196. defines = fallbacks.reduce(defines);
  18197. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18198. }
  18199. else {
  18200. BABYLON.Tools.Error("Unable to compile effect: ");
  18201. if (this.name.vertexElement) {
  18202. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18203. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18204. }
  18205. else if (this.name.vertex) {
  18206. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18207. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18208. }
  18209. else {
  18210. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18211. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18212. }
  18213. BABYLON.Tools.Error("Defines: " + defines);
  18214. BABYLON.Tools.Error("Error: " + e.message);
  18215. this._compilationError = e.message;
  18216. if (this.onError) {
  18217. this.onError(this, this._compilationError);
  18218. }
  18219. }
  18220. }
  18221. };
  18222. Effect.prototype._bindTexture = function (channel, texture) {
  18223. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18224. };
  18225. Effect.prototype.setTexture = function (channel, texture) {
  18226. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18227. };
  18228. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18229. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18230. };
  18231. //public _cacheMatrix(uniformName, matrix) {
  18232. // if (!this._valueCache[uniformName]) {
  18233. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18234. // }
  18235. // for (var index = 0; index < 16; index++) {
  18236. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18237. // }
  18238. //};
  18239. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18240. if (!this._valueCache[uniformName]) {
  18241. this._valueCache[uniformName] = [x, y];
  18242. return;
  18243. }
  18244. this._valueCache[uniformName][0] = x;
  18245. this._valueCache[uniformName][1] = y;
  18246. };
  18247. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18248. if (!this._valueCache[uniformName]) {
  18249. this._valueCache[uniformName] = [x, y, z];
  18250. return;
  18251. }
  18252. this._valueCache[uniformName][0] = x;
  18253. this._valueCache[uniformName][1] = y;
  18254. this._valueCache[uniformName][2] = z;
  18255. };
  18256. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18257. if (!this._valueCache[uniformName]) {
  18258. this._valueCache[uniformName] = [x, y, z, w];
  18259. return;
  18260. }
  18261. this._valueCache[uniformName][0] = x;
  18262. this._valueCache[uniformName][1] = y;
  18263. this._valueCache[uniformName][2] = z;
  18264. this._valueCache[uniformName][3] = w;
  18265. };
  18266. Effect.prototype.setArray = function (uniformName, array) {
  18267. this._engine.setArray(this.getUniform(uniformName), array);
  18268. return this;
  18269. };
  18270. Effect.prototype.setArray2 = function (uniformName, array) {
  18271. this._engine.setArray2(this.getUniform(uniformName), array);
  18272. return this;
  18273. };
  18274. Effect.prototype.setArray3 = function (uniformName, array) {
  18275. this._engine.setArray3(this.getUniform(uniformName), array);
  18276. return this;
  18277. };
  18278. Effect.prototype.setArray4 = function (uniformName, array) {
  18279. this._engine.setArray4(this.getUniform(uniformName), array);
  18280. return this;
  18281. };
  18282. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18283. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18284. return this;
  18285. };
  18286. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18287. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18288. // return;
  18289. //this._cacheMatrix(uniformName, matrix);
  18290. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18291. return this;
  18292. };
  18293. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18294. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18295. return this;
  18296. };
  18297. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18298. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18299. return this;
  18300. };
  18301. Effect.prototype.setFloat = function (uniformName, value) {
  18302. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18303. return this;
  18304. this._valueCache[uniformName] = value;
  18305. this._engine.setFloat(this.getUniform(uniformName), value);
  18306. return this;
  18307. };
  18308. Effect.prototype.setBool = function (uniformName, bool) {
  18309. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18310. return this;
  18311. this._valueCache[uniformName] = bool;
  18312. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18313. return this;
  18314. };
  18315. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18316. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18317. return this;
  18318. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18319. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18320. return this;
  18321. };
  18322. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18323. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18324. return this;
  18325. this._cacheFloat2(uniformName, x, y);
  18326. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18327. return this;
  18328. };
  18329. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18330. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18331. return this;
  18332. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18333. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18334. return this;
  18335. };
  18336. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18337. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18338. return this;
  18339. this._cacheFloat3(uniformName, x, y, z);
  18340. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18341. return this;
  18342. };
  18343. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18344. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  18345. return this;
  18346. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18347. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18348. return this;
  18349. };
  18350. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18351. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18352. return this;
  18353. this._cacheFloat4(uniformName, x, y, z, w);
  18354. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18355. return this;
  18356. };
  18357. Effect.prototype.setColor3 = function (uniformName, color3) {
  18358. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18359. return this;
  18360. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18361. this._engine.setColor3(this.getUniform(uniformName), color3);
  18362. return this;
  18363. };
  18364. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18365. 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)
  18366. return this;
  18367. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18368. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18369. return this;
  18370. };
  18371. // Statics
  18372. Effect.ShadersStore = {};
  18373. return Effect;
  18374. })();
  18375. BABYLON.Effect = Effect;
  18376. })(BABYLON || (BABYLON = {}));
  18377. var BABYLON;
  18378. (function (BABYLON) {
  18379. var Material = (function () {
  18380. function Material(name, scene, doNotAdd) {
  18381. this.name = name;
  18382. this.checkReadyOnEveryCall = true;
  18383. this.checkReadyOnlyOnce = false;
  18384. this.state = "";
  18385. this.alpha = 1.0;
  18386. this.backFaceCulling = true;
  18387. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18388. this.disableDepthWrite = false;
  18389. this._wasPreviouslyReady = false;
  18390. this._fillMode = Material.TriangleFillMode;
  18391. this.pointSize = 1.0;
  18392. this.zOffset = 0;
  18393. this.id = name;
  18394. this._scene = scene;
  18395. if (!doNotAdd) {
  18396. scene.materials.push(this);
  18397. }
  18398. }
  18399. Object.defineProperty(Material, "TriangleFillMode", {
  18400. get: function () {
  18401. return Material._TriangleFillMode;
  18402. },
  18403. enumerable: true,
  18404. configurable: true
  18405. });
  18406. Object.defineProperty(Material, "WireFrameFillMode", {
  18407. get: function () {
  18408. return Material._WireFrameFillMode;
  18409. },
  18410. enumerable: true,
  18411. configurable: true
  18412. });
  18413. Object.defineProperty(Material, "PointFillMode", {
  18414. get: function () {
  18415. return Material._PointFillMode;
  18416. },
  18417. enumerable: true,
  18418. configurable: true
  18419. });
  18420. Object.defineProperty(Material.prototype, "wireframe", {
  18421. get: function () {
  18422. return this._fillMode === Material.WireFrameFillMode;
  18423. },
  18424. set: function (value) {
  18425. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18426. },
  18427. enumerable: true,
  18428. configurable: true
  18429. });
  18430. Object.defineProperty(Material.prototype, "pointsCloud", {
  18431. get: function () {
  18432. return this._fillMode === Material.PointFillMode;
  18433. },
  18434. set: function (value) {
  18435. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. Object.defineProperty(Material.prototype, "fillMode", {
  18441. get: function () {
  18442. return this._fillMode;
  18443. },
  18444. set: function (value) {
  18445. this._fillMode = value;
  18446. },
  18447. enumerable: true,
  18448. configurable: true
  18449. });
  18450. Material.prototype.isReady = function (mesh, useInstances) {
  18451. return true;
  18452. };
  18453. Material.prototype.getEffect = function () {
  18454. return this._effect;
  18455. };
  18456. Material.prototype.getScene = function () {
  18457. return this._scene;
  18458. };
  18459. Material.prototype.needAlphaBlending = function () {
  18460. return (this.alpha < 1.0);
  18461. };
  18462. Material.prototype.needAlphaTesting = function () {
  18463. return false;
  18464. };
  18465. Material.prototype.getAlphaTestTexture = function () {
  18466. return null;
  18467. };
  18468. Material.prototype.trackCreation = function (onCompiled, onError) {
  18469. };
  18470. Material.prototype._preBind = function () {
  18471. var engine = this._scene.getEngine();
  18472. engine.enableEffect(this._effect);
  18473. engine.setState(this.backFaceCulling, this.zOffset);
  18474. };
  18475. Material.prototype.bind = function (world, mesh) {
  18476. this._scene._cachedMaterial = this;
  18477. if (this.onBind) {
  18478. this.onBind(this, mesh);
  18479. }
  18480. if (this.disableDepthWrite) {
  18481. var engine = this._scene.getEngine();
  18482. this._cachedDepthWriteState = engine.getDepthWrite();
  18483. engine.setDepthWrite(false);
  18484. }
  18485. };
  18486. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18487. };
  18488. Material.prototype.unbind = function () {
  18489. if (this.disableDepthWrite) {
  18490. var engine = this._scene.getEngine();
  18491. engine.setDepthWrite(this._cachedDepthWriteState);
  18492. }
  18493. };
  18494. Material.prototype.clone = function (name) {
  18495. return null;
  18496. };
  18497. Material.prototype.dispose = function (forceDisposeEffect) {
  18498. // Remove from scene
  18499. var index = this._scene.materials.indexOf(this);
  18500. this._scene.materials.splice(index, 1);
  18501. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18502. if (forceDisposeEffect && this._effect) {
  18503. this._scene.getEngine()._releaseEffect(this._effect);
  18504. this._effect = null;
  18505. }
  18506. // Callback
  18507. if (this.onDispose) {
  18508. this.onDispose();
  18509. }
  18510. };
  18511. Material._TriangleFillMode = 0;
  18512. Material._WireFrameFillMode = 1;
  18513. Material._PointFillMode = 2;
  18514. return Material;
  18515. })();
  18516. BABYLON.Material = Material;
  18517. })(BABYLON || (BABYLON = {}));
  18518. var BABYLON;
  18519. (function (BABYLON) {
  18520. var maxSimultaneousLights = 4;
  18521. var FresnelParameters = (function () {
  18522. function FresnelParameters() {
  18523. this.isEnabled = true;
  18524. this.leftColor = BABYLON.Color3.White();
  18525. this.rightColor = BABYLON.Color3.Black();
  18526. this.bias = 0;
  18527. this.power = 1;
  18528. }
  18529. return FresnelParameters;
  18530. })();
  18531. BABYLON.FresnelParameters = FresnelParameters;
  18532. var StandardMaterialDefines = (function () {
  18533. function StandardMaterialDefines() {
  18534. this.DIFFUSE = false;
  18535. this.AMBIENT = false;
  18536. this.OPACITY = false;
  18537. this.OPACITYRGB = false;
  18538. this.REFLECTION = false;
  18539. this.EMISSIVE = false;
  18540. this.SPECULAR = false;
  18541. this.BUMP = false;
  18542. this.SPECULAROVERALPHA = false;
  18543. this.CLIPPLANE = false;
  18544. this.ALPHATEST = false;
  18545. this.ALPHAFROMDIFFUSE = false;
  18546. this.POINTSIZE = false;
  18547. this.FOG = false;
  18548. this.LIGHT0 = false;
  18549. this.LIGHT1 = false;
  18550. this.LIGHT2 = false;
  18551. this.LIGHT3 = false;
  18552. this.SPOTLIGHT0 = false;
  18553. this.SPOTLIGHT1 = false;
  18554. this.SPOTLIGHT2 = false;
  18555. this.SPOTLIGHT3 = false;
  18556. this.HEMILIGHT0 = false;
  18557. this.HEMILIGHT1 = false;
  18558. this.HEMILIGHT2 = false;
  18559. this.HEMILIGHT3 = false;
  18560. this.POINTDIRLIGHT0 = false;
  18561. this.POINTDIRLIGHT1 = false;
  18562. this.POINTDIRLIGHT2 = false;
  18563. this.POINTDIRLIGHT3 = false;
  18564. this.SPECULARTERM = false;
  18565. this.SHADOW0 = false;
  18566. this.SHADOW1 = false;
  18567. this.SHADOW2 = false;
  18568. this.SHADOW3 = false;
  18569. this.SHADOWS = false;
  18570. this.SHADOWVSM0 = false;
  18571. this.SHADOWVSM1 = false;
  18572. this.SHADOWVSM2 = false;
  18573. this.SHADOWVSM3 = false;
  18574. this.SHADOWPCF0 = false;
  18575. this.SHADOWPCF1 = false;
  18576. this.SHADOWPCF2 = false;
  18577. this.SHADOWPCF3 = false;
  18578. this.DIFFUSEFRESNEL = false;
  18579. this.OPACITYFRESNEL = false;
  18580. this.REFLECTIONFRESNEL = false;
  18581. this.EMISSIVEFRESNEL = false;
  18582. this.FRESNEL = false;
  18583. this.NORMAL = false;
  18584. this.UV1 = false;
  18585. this.UV2 = false;
  18586. this.VERTEXCOLOR = false;
  18587. this.VERTEXALPHA = false;
  18588. this.BONES = false;
  18589. this.BONES4 = false;
  18590. this.BonesPerMesh = 0;
  18591. this.INSTANCES = false;
  18592. this.GLOSSINESS = false;
  18593. this.ROUGHNESS = false;
  18594. this._keys = Object.keys(this);
  18595. }
  18596. StandardMaterialDefines.prototype.isEqual = function (other) {
  18597. for (var index = 0; index < this._keys.length; index++) {
  18598. var prop = this._keys[index];
  18599. if (this[prop] !== other[prop]) {
  18600. return false;
  18601. }
  18602. }
  18603. return true;
  18604. };
  18605. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18606. for (var index = 0; index < this._keys.length; index++) {
  18607. var prop = this._keys[index];
  18608. other[prop] = this[prop];
  18609. }
  18610. };
  18611. StandardMaterialDefines.prototype.reset = function () {
  18612. for (var index = 0; index < this._keys.length; index++) {
  18613. var prop = this._keys[index];
  18614. if (prop === "BonesPerMesh") {
  18615. this[prop] = 0;
  18616. continue;
  18617. }
  18618. this[prop] = false;
  18619. }
  18620. };
  18621. StandardMaterialDefines.prototype.toString = function () {
  18622. var result = "";
  18623. for (var index = 0; index < this._keys.length; index++) {
  18624. var prop = this._keys[index];
  18625. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18626. result += "#define BonesPerMesh " + this[prop] + "\n";
  18627. continue;
  18628. }
  18629. if (this[prop]) {
  18630. result += "#define " + prop + "\n";
  18631. }
  18632. }
  18633. return result;
  18634. };
  18635. return StandardMaterialDefines;
  18636. })();
  18637. var StandardMaterial = (function (_super) {
  18638. __extends(StandardMaterial, _super);
  18639. function StandardMaterial(name, scene) {
  18640. var _this = this;
  18641. _super.call(this, name, scene);
  18642. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18643. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18644. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18645. this.specularPower = 64;
  18646. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18647. this.useAlphaFromDiffuseTexture = false;
  18648. this.useSpecularOverAlpha = true;
  18649. this.fogEnabled = true;
  18650. this.roughness = 0;
  18651. this.useGlossinessFromSpecularMapAlpha = false;
  18652. this._renderTargets = new BABYLON.SmartArray(16);
  18653. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18654. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18655. this._scaledDiffuse = new BABYLON.Color3();
  18656. this._scaledSpecular = new BABYLON.Color3();
  18657. this._defines = new StandardMaterialDefines();
  18658. this._cachedDefines = new StandardMaterialDefines();
  18659. this._cachedDefines.BonesPerMesh = -1;
  18660. this.getRenderTargetTextures = function () {
  18661. _this._renderTargets.reset();
  18662. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18663. _this._renderTargets.push(_this.reflectionTexture);
  18664. }
  18665. return _this._renderTargets;
  18666. };
  18667. }
  18668. StandardMaterial.prototype.needAlphaBlending = function () {
  18669. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18670. };
  18671. StandardMaterial.prototype.needAlphaTesting = function () {
  18672. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18673. };
  18674. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18675. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18676. };
  18677. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18678. return this.diffuseTexture;
  18679. };
  18680. // Methods
  18681. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18682. if (this.checkReadyOnlyOnce) {
  18683. if (this._wasPreviouslyReady) {
  18684. return true;
  18685. }
  18686. }
  18687. var scene = this.getScene();
  18688. if (!this.checkReadyOnEveryCall) {
  18689. if (this._renderId === scene.getRenderId()) {
  18690. return true;
  18691. }
  18692. }
  18693. var engine = scene.getEngine();
  18694. var needNormals = false;
  18695. var needUVs = false;
  18696. this._defines.reset();
  18697. // Textures
  18698. if (scene.texturesEnabled) {
  18699. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18700. if (!this.diffuseTexture.isReady()) {
  18701. return false;
  18702. }
  18703. else {
  18704. needUVs = true;
  18705. this._defines.DIFFUSE = true;
  18706. }
  18707. }
  18708. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18709. if (!this.ambientTexture.isReady()) {
  18710. return false;
  18711. }
  18712. else {
  18713. needUVs = true;
  18714. this._defines.AMBIENT = true;
  18715. }
  18716. }
  18717. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18718. if (!this.opacityTexture.isReady()) {
  18719. return false;
  18720. }
  18721. else {
  18722. needUVs = true;
  18723. this._defines.OPACITY = true;
  18724. if (this.opacityTexture.getAlphaFromRGB) {
  18725. this._defines.OPACITYRGB = true;
  18726. }
  18727. }
  18728. }
  18729. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18730. if (!this.reflectionTexture.isReady()) {
  18731. return false;
  18732. }
  18733. else {
  18734. needNormals = true;
  18735. needUVs = true;
  18736. this._defines.REFLECTION = true;
  18737. if (this.roughness > 0) {
  18738. this._defines.ROUGHNESS = true;
  18739. }
  18740. }
  18741. }
  18742. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18743. if (!this.emissiveTexture.isReady()) {
  18744. return false;
  18745. }
  18746. else {
  18747. needUVs = true;
  18748. this._defines.EMISSIVE = true;
  18749. }
  18750. }
  18751. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18752. if (!this.specularTexture.isReady()) {
  18753. return false;
  18754. }
  18755. else {
  18756. needUVs = true;
  18757. this._defines.SPECULAR = true;
  18758. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18759. }
  18760. }
  18761. }
  18762. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18763. if (!this.bumpTexture.isReady()) {
  18764. return false;
  18765. }
  18766. else {
  18767. needUVs = true;
  18768. this._defines.BUMP = true;
  18769. }
  18770. }
  18771. // Effect
  18772. if (scene.clipPlane) {
  18773. this._defines.CLIPPLANE = true;
  18774. }
  18775. if (engine.getAlphaTesting()) {
  18776. this._defines.ALPHATEST = true;
  18777. }
  18778. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18779. this._defines.ALPHAFROMDIFFUSE = true;
  18780. }
  18781. // Point size
  18782. if (this.pointsCloud || scene.forcePointsCloud) {
  18783. this._defines.POINTSIZE = true;
  18784. }
  18785. // Fog
  18786. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18787. this._defines.FOG = true;
  18788. }
  18789. var lightIndex = 0;
  18790. if (scene.lightsEnabled) {
  18791. for (var index = 0; index < scene.lights.length; index++) {
  18792. var light = scene.lights[index];
  18793. if (!light.isEnabled()) {
  18794. continue;
  18795. }
  18796. // Excluded check
  18797. if (light._excludedMeshesIds.length > 0) {
  18798. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18799. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18800. if (excludedMesh) {
  18801. light.excludedMeshes.push(excludedMesh);
  18802. }
  18803. }
  18804. light._excludedMeshesIds = [];
  18805. }
  18806. // Included check
  18807. if (light._includedOnlyMeshesIds.length > 0) {
  18808. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18809. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18810. if (includedOnlyMesh) {
  18811. light.includedOnlyMeshes.push(includedOnlyMesh);
  18812. }
  18813. }
  18814. light._includedOnlyMeshesIds = [];
  18815. }
  18816. if (!light.canAffectMesh(mesh)) {
  18817. continue;
  18818. }
  18819. needNormals = true;
  18820. this._defines["LIGHT" + lightIndex] = true;
  18821. var type;
  18822. if (light instanceof BABYLON.SpotLight) {
  18823. type = "SPOTLIGHT" + lightIndex;
  18824. }
  18825. else if (light instanceof BABYLON.HemisphericLight) {
  18826. type = "HEMILIGHT" + lightIndex;
  18827. }
  18828. else {
  18829. type = "POINTDIRLIGHT" + lightIndex;
  18830. }
  18831. this._defines[type] = true;
  18832. // Specular
  18833. if (!light.specular.equalsFloats(0, 0, 0)) {
  18834. this._defines.SPECULARTERM = true;
  18835. }
  18836. // Shadows
  18837. if (scene.shadowsEnabled) {
  18838. var shadowGenerator = light.getShadowGenerator();
  18839. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18840. this._defines["SHADOW" + lightIndex] = true;
  18841. this._defines.SHADOWS = true;
  18842. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18843. this._defines["SHADOWVSM" + lightIndex] = true;
  18844. }
  18845. if (shadowGenerator.usePoissonSampling) {
  18846. this._defines["SHADOWPCF" + lightIndex] = true;
  18847. }
  18848. }
  18849. }
  18850. lightIndex++;
  18851. if (lightIndex === maxSimultaneousLights)
  18852. break;
  18853. }
  18854. }
  18855. if (StandardMaterial.FresnelEnabled) {
  18856. // Fresnel
  18857. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18858. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18859. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18860. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18861. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18862. this._defines.DIFFUSEFRESNEL = true;
  18863. }
  18864. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18865. this._defines.OPACITYFRESNEL = true;
  18866. }
  18867. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18868. this._defines.REFLECTIONFRESNEL = true;
  18869. }
  18870. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18871. this._defines.EMISSIVEFRESNEL = true;
  18872. }
  18873. needNormals = true;
  18874. this._defines.FRESNEL = true;
  18875. }
  18876. }
  18877. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18878. this._defines.SPECULAROVERALPHA = true;
  18879. }
  18880. // Attribs
  18881. if (mesh) {
  18882. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18883. this._defines.NORMAL = true;
  18884. }
  18885. if (needUVs) {
  18886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18887. this._defines.UV1 = true;
  18888. }
  18889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18890. this._defines.UV2 = true;
  18891. }
  18892. }
  18893. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18894. this._defines.VERTEXCOLOR = true;
  18895. if (mesh.hasVertexAlpha) {
  18896. this._defines.VERTEXALPHA = true;
  18897. }
  18898. }
  18899. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18900. this._defines.BONES = true;
  18901. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18902. this._defines.BONES4 = true;
  18903. }
  18904. // Instances
  18905. if (useInstances) {
  18906. this._defines.INSTANCES = true;
  18907. }
  18908. }
  18909. // Get correct effect
  18910. if (!this._defines.isEqual(this._cachedDefines)) {
  18911. this._defines.cloneTo(this._cachedDefines);
  18912. scene.resetCachedMaterial();
  18913. // Fallbacks
  18914. var fallbacks = new BABYLON.EffectFallbacks();
  18915. if (this._defines.REFLECTION) {
  18916. fallbacks.addFallback(0, "REFLECTION");
  18917. }
  18918. if (this._defines.SPECULAR) {
  18919. fallbacks.addFallback(0, "SPECULAR");
  18920. }
  18921. if (this._defines.BUMP) {
  18922. fallbacks.addFallback(0, "BUMP");
  18923. }
  18924. if (this._defines.SPECULAROVERALPHA) {
  18925. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18926. }
  18927. if (this._defines.FOG) {
  18928. fallbacks.addFallback(1, "FOG");
  18929. }
  18930. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18931. if (!this._defines["LIGHT" + lightIndex]) {
  18932. continue;
  18933. }
  18934. if (lightIndex > 0) {
  18935. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18936. }
  18937. if (this._defines["SHADOW" + lightIndex]) {
  18938. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18939. }
  18940. if (this._defines["SHADOWPCF" + lightIndex]) {
  18941. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18942. }
  18943. if (this._defines["SHADOWVSM" + lightIndex]) {
  18944. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18945. }
  18946. }
  18947. if (this._defines.SPECULARTERM) {
  18948. fallbacks.addFallback(0, "SPECULARTERM");
  18949. }
  18950. if (this._defines.DIFFUSEFRESNEL) {
  18951. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18952. }
  18953. if (this._defines.OPACITYFRESNEL) {
  18954. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18955. }
  18956. if (this._defines.REFLECTIONFRESNEL) {
  18957. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18958. }
  18959. if (this._defines.EMISSIVEFRESNEL) {
  18960. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18961. }
  18962. if (this._defines.FRESNEL) {
  18963. fallbacks.addFallback(4, "FRESNEL");
  18964. }
  18965. if (this._defines.BONES4) {
  18966. fallbacks.addFallback(0, "BONES4");
  18967. }
  18968. //Attributes
  18969. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18970. if (this._defines.NORMAL) {
  18971. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18972. }
  18973. if (this._defines.UV1) {
  18974. attribs.push(BABYLON.VertexBuffer.UVKind);
  18975. }
  18976. if (this._defines.UV2) {
  18977. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18978. }
  18979. if (this._defines.VERTEXCOLOR) {
  18980. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18981. }
  18982. if (this._defines.BONES) {
  18983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18985. }
  18986. if (this._defines.INSTANCES) {
  18987. attribs.push("world0");
  18988. attribs.push("world1");
  18989. attribs.push("world2");
  18990. attribs.push("world3");
  18991. }
  18992. // Legacy browser patch
  18993. var shaderName = "default";
  18994. if (!scene.getEngine().getCaps().standardDerivatives) {
  18995. shaderName = "legacydefault";
  18996. }
  18997. var join = this._defines.toString();
  18998. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18999. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19000. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19001. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19002. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19003. "vFogInfos", "vFogColor", "pointSize",
  19004. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  19005. "mBones",
  19006. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  19007. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19008. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19009. "roughness"
  19010. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  19011. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19012. ], join, fallbacks, this.onCompiled, this.onError);
  19013. }
  19014. if (!this._effect.isReady()) {
  19015. return false;
  19016. }
  19017. this._renderId = scene.getRenderId();
  19018. this._wasPreviouslyReady = true;
  19019. return true;
  19020. };
  19021. StandardMaterial.prototype.unbind = function () {
  19022. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19023. this._effect.setTexture("reflection2DSampler", null);
  19024. }
  19025. _super.prototype.unbind.call(this);
  19026. };
  19027. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19028. this._effect.setMatrix("world", world);
  19029. };
  19030. StandardMaterial.prototype.bind = function (world, mesh) {
  19031. var scene = this.getScene();
  19032. // Matrices
  19033. this.bindOnlyWorldMatrix(world);
  19034. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19035. // Bones
  19036. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19037. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19038. }
  19039. if (scene.getCachedMaterial() !== this) {
  19040. if (StandardMaterial.FresnelEnabled) {
  19041. // Fresnel
  19042. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19043. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19044. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19045. }
  19046. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19047. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19048. }
  19049. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19050. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19051. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19052. }
  19053. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19054. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19055. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19056. }
  19057. }
  19058. // Textures
  19059. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19060. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19061. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19062. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19063. }
  19064. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19065. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19066. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19067. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19068. }
  19069. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19070. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19071. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19072. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19073. }
  19074. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19075. if (this.reflectionTexture.isCube) {
  19076. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19077. if (this._defines.ROUGHNESS) {
  19078. this._effect.setFloat("roughness", this.roughness);
  19079. }
  19080. }
  19081. else {
  19082. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19083. }
  19084. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19085. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19086. }
  19087. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19088. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19089. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19090. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19091. }
  19092. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19093. this._effect.setTexture("specularSampler", this.specularTexture);
  19094. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19095. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19096. }
  19097. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19098. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19099. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19100. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19101. }
  19102. // Clip plane
  19103. if (scene.clipPlane) {
  19104. var clipPlane = scene.clipPlane;
  19105. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19106. }
  19107. // Point size
  19108. if (this.pointsCloud) {
  19109. this._effect.setFloat("pointSize", this.pointSize);
  19110. }
  19111. // Colors
  19112. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19113. // Scaling down color according to emissive
  19114. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19115. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19116. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19117. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19118. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19119. if (this._defines.SPECULARTERM) {
  19120. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19121. }
  19122. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19123. }
  19124. // Scaling down color according to emissive
  19125. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19126. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19127. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19128. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19129. if (scene.lightsEnabled) {
  19130. var lightIndex = 0;
  19131. for (var index = 0; index < scene.lights.length; index++) {
  19132. var light = scene.lights[index];
  19133. if (!light.isEnabled()) {
  19134. continue;
  19135. }
  19136. if (!light.canAffectMesh(mesh)) {
  19137. continue;
  19138. }
  19139. if (light instanceof BABYLON.PointLight) {
  19140. // Point Light
  19141. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19142. }
  19143. else if (light instanceof BABYLON.DirectionalLight) {
  19144. // Directional Light
  19145. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19146. }
  19147. else if (light instanceof BABYLON.SpotLight) {
  19148. // Spot Light
  19149. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19150. }
  19151. else if (light instanceof BABYLON.HemisphericLight) {
  19152. // Hemispheric Light
  19153. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19154. }
  19155. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19156. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19157. if (this._defines.SPECULARTERM) {
  19158. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19159. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19160. }
  19161. // Shadows
  19162. if (scene.shadowsEnabled) {
  19163. var shadowGenerator = light.getShadowGenerator();
  19164. if (mesh.receiveShadows && shadowGenerator) {
  19165. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19166. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19167. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19168. }
  19169. }
  19170. lightIndex++;
  19171. if (lightIndex === maxSimultaneousLights)
  19172. break;
  19173. }
  19174. }
  19175. // View
  19176. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19177. this._effect.setMatrix("view", scene.getViewMatrix());
  19178. }
  19179. // Fog
  19180. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19181. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19182. this._effect.setColor3("vFogColor", scene.fogColor);
  19183. }
  19184. _super.prototype.bind.call(this, world, mesh);
  19185. };
  19186. StandardMaterial.prototype.getAnimatables = function () {
  19187. var results = [];
  19188. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19189. results.push(this.diffuseTexture);
  19190. }
  19191. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19192. results.push(this.ambientTexture);
  19193. }
  19194. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19195. results.push(this.opacityTexture);
  19196. }
  19197. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19198. results.push(this.reflectionTexture);
  19199. }
  19200. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19201. results.push(this.emissiveTexture);
  19202. }
  19203. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19204. results.push(this.specularTexture);
  19205. }
  19206. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19207. results.push(this.bumpTexture);
  19208. }
  19209. return results;
  19210. };
  19211. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19212. if (this.diffuseTexture) {
  19213. this.diffuseTexture.dispose();
  19214. }
  19215. if (this.ambientTexture) {
  19216. this.ambientTexture.dispose();
  19217. }
  19218. if (this.opacityTexture) {
  19219. this.opacityTexture.dispose();
  19220. }
  19221. if (this.reflectionTexture) {
  19222. this.reflectionTexture.dispose();
  19223. }
  19224. if (this.emissiveTexture) {
  19225. this.emissiveTexture.dispose();
  19226. }
  19227. if (this.specularTexture) {
  19228. this.specularTexture.dispose();
  19229. }
  19230. if (this.bumpTexture) {
  19231. this.bumpTexture.dispose();
  19232. }
  19233. _super.prototype.dispose.call(this, forceDisposeEffect);
  19234. };
  19235. StandardMaterial.prototype.clone = function (name) {
  19236. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19237. // Base material
  19238. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19239. newStandardMaterial.alpha = this.alpha;
  19240. newStandardMaterial.fillMode = this.fillMode;
  19241. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19242. // Standard material
  19243. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19244. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19245. }
  19246. if (this.ambientTexture && this.ambientTexture.clone) {
  19247. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19248. }
  19249. if (this.opacityTexture && this.opacityTexture.clone) {
  19250. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19251. }
  19252. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19253. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19254. }
  19255. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19256. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19257. }
  19258. if (this.specularTexture && this.specularTexture.clone) {
  19259. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19260. }
  19261. if (this.bumpTexture && this.bumpTexture.clone) {
  19262. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19263. }
  19264. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19265. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19266. newStandardMaterial.specularColor = this.specularColor.clone();
  19267. newStandardMaterial.specularPower = this.specularPower;
  19268. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19269. return newStandardMaterial;
  19270. };
  19271. // Statics
  19272. // Flags used to enable or disable a type of texture for all Standard Materials
  19273. StandardMaterial.DiffuseTextureEnabled = true;
  19274. StandardMaterial.AmbientTextureEnabled = true;
  19275. StandardMaterial.OpacityTextureEnabled = true;
  19276. StandardMaterial.ReflectionTextureEnabled = true;
  19277. StandardMaterial.EmissiveTextureEnabled = true;
  19278. StandardMaterial.SpecularTextureEnabled = true;
  19279. StandardMaterial.BumpTextureEnabled = true;
  19280. StandardMaterial.FresnelEnabled = true;
  19281. return StandardMaterial;
  19282. })(BABYLON.Material);
  19283. BABYLON.StandardMaterial = StandardMaterial;
  19284. })(BABYLON || (BABYLON = {}));
  19285. var BABYLON;
  19286. (function (BABYLON) {
  19287. var MultiMaterial = (function (_super) {
  19288. __extends(MultiMaterial, _super);
  19289. function MultiMaterial(name, scene) {
  19290. _super.call(this, name, scene, true);
  19291. this.subMaterials = new Array();
  19292. scene.multiMaterials.push(this);
  19293. }
  19294. // Properties
  19295. MultiMaterial.prototype.getSubMaterial = function (index) {
  19296. if (index < 0 || index >= this.subMaterials.length) {
  19297. return this.getScene().defaultMaterial;
  19298. }
  19299. return this.subMaterials[index];
  19300. };
  19301. // Methods
  19302. MultiMaterial.prototype.isReady = function (mesh) {
  19303. for (var index = 0; index < this.subMaterials.length; index++) {
  19304. var subMaterial = this.subMaterials[index];
  19305. if (subMaterial) {
  19306. if (!this.subMaterials[index].isReady(mesh)) {
  19307. return false;
  19308. }
  19309. }
  19310. }
  19311. return true;
  19312. };
  19313. MultiMaterial.prototype.clone = function (name) {
  19314. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19315. for (var index = 0; index < this.subMaterials.length; index++) {
  19316. var subMaterial = this.subMaterials[index];
  19317. newMultiMaterial.subMaterials.push(subMaterial);
  19318. }
  19319. return newMultiMaterial;
  19320. };
  19321. return MultiMaterial;
  19322. })(BABYLON.Material);
  19323. BABYLON.MultiMaterial = MultiMaterial;
  19324. })(BABYLON || (BABYLON = {}));
  19325. var BABYLON;
  19326. (function (BABYLON) {
  19327. var SceneLoader = (function () {
  19328. function SceneLoader() {
  19329. }
  19330. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19331. get: function () {
  19332. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19333. },
  19334. set: function (value) {
  19335. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19336. },
  19337. enumerable: true,
  19338. configurable: true
  19339. });
  19340. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19341. get: function () {
  19342. return SceneLoader._ShowLoadingScreen;
  19343. },
  19344. set: function (value) {
  19345. SceneLoader._ShowLoadingScreen = value;
  19346. },
  19347. enumerable: true,
  19348. configurable: true
  19349. });
  19350. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19351. var dotPosition = sceneFilename.lastIndexOf(".");
  19352. var queryStringPosition = sceneFilename.indexOf("?");
  19353. if (queryStringPosition === -1) {
  19354. queryStringPosition = sceneFilename.length;
  19355. }
  19356. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19357. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19358. var plugin = this._registeredPlugins[index];
  19359. if (plugin.extensions.indexOf(extension) !== -1) {
  19360. return plugin;
  19361. }
  19362. }
  19363. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19364. };
  19365. // Public functions
  19366. SceneLoader.RegisterPlugin = function (plugin) {
  19367. plugin.extensions = plugin.extensions.toLowerCase();
  19368. SceneLoader._registeredPlugins.push(plugin);
  19369. };
  19370. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19371. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19372. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19373. return;
  19374. }
  19375. var loadingToken = {};
  19376. scene._addPendingData(loadingToken);
  19377. var manifestChecked = function (success) {
  19378. scene.database = database;
  19379. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19380. var importMeshFromData = function (data) {
  19381. var meshes = [];
  19382. var particleSystems = [];
  19383. var skeletons = [];
  19384. try {
  19385. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19386. if (onerror) {
  19387. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19388. }
  19389. scene._removePendingData(loadingToken);
  19390. return;
  19391. }
  19392. }
  19393. catch (e) {
  19394. if (onerror) {
  19395. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19396. }
  19397. scene._removePendingData(loadingToken);
  19398. return;
  19399. }
  19400. if (onsuccess) {
  19401. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19402. onsuccess(meshes, particleSystems, skeletons);
  19403. scene._removePendingData(loadingToken);
  19404. }
  19405. };
  19406. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19407. // Direct load
  19408. importMeshFromData(sceneFilename.substr(5));
  19409. return;
  19410. }
  19411. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19412. importMeshFromData(data);
  19413. }, progressCallBack, database);
  19414. };
  19415. if (scene.getEngine().enableOfflineSupport) {
  19416. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19417. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19418. }
  19419. else {
  19420. manifestChecked(true);
  19421. }
  19422. };
  19423. /**
  19424. * Load a scene
  19425. * @param rootUrl a string that defines the root url for scene and resources
  19426. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19427. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19428. */
  19429. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19430. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19431. };
  19432. /**
  19433. * Append a scene
  19434. * @param rootUrl a string that defines the root url for scene and resources
  19435. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19436. * @param scene is the instance of BABYLON.Scene to append to
  19437. */
  19438. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19439. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19440. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19441. return;
  19442. }
  19443. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19444. var database;
  19445. var loadingToken = {};
  19446. scene._addPendingData(loadingToken);
  19447. if (SceneLoader.ShowLoadingScreen) {
  19448. scene.getEngine().displayLoadingUI();
  19449. }
  19450. var loadSceneFromData = function (data) {
  19451. scene.database = database;
  19452. if (!plugin.load(scene, data, rootUrl)) {
  19453. if (onerror) {
  19454. onerror(scene);
  19455. }
  19456. scene._removePendingData(loadingToken);
  19457. scene.getEngine().hideLoadingUI();
  19458. return;
  19459. }
  19460. if (onsuccess) {
  19461. onsuccess(scene);
  19462. }
  19463. scene._removePendingData(loadingToken);
  19464. if (SceneLoader.ShowLoadingScreen) {
  19465. scene.executeWhenReady(function () {
  19466. scene.getEngine().hideLoadingUI();
  19467. });
  19468. }
  19469. };
  19470. var manifestChecked = function (success) {
  19471. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19472. };
  19473. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19474. // Direct load
  19475. loadSceneFromData(sceneFilename.substr(5));
  19476. return;
  19477. }
  19478. if (rootUrl.indexOf("file:") === -1) {
  19479. if (scene.getEngine().enableOfflineSupport) {
  19480. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19481. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19482. }
  19483. else {
  19484. manifestChecked(true);
  19485. }
  19486. }
  19487. else {
  19488. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19489. }
  19490. };
  19491. // Flags
  19492. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19493. SceneLoader._ShowLoadingScreen = true;
  19494. // Members
  19495. SceneLoader._registeredPlugins = new Array();
  19496. return SceneLoader;
  19497. })();
  19498. BABYLON.SceneLoader = SceneLoader;
  19499. ;
  19500. })(BABYLON || (BABYLON = {}));
  19501. var BABYLON;
  19502. (function (BABYLON) {
  19503. var Internals;
  19504. (function (Internals) {
  19505. var checkColors4 = function (colors, count) {
  19506. // Check if color3 was used
  19507. if (colors.length === count * 3) {
  19508. var colors4 = [];
  19509. for (var index = 0; index < colors.length; index += 3) {
  19510. var newIndex = (index / 3) * 4;
  19511. colors4[newIndex] = colors[index];
  19512. colors4[newIndex + 1] = colors[index + 1];
  19513. colors4[newIndex + 2] = colors[index + 2];
  19514. colors4[newIndex + 3] = 1.0;
  19515. }
  19516. return colors4;
  19517. }
  19518. return colors;
  19519. };
  19520. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19521. var texture = null;
  19522. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19523. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19524. texture.name = parsedTexture.name;
  19525. texture.hasAlpha = parsedTexture.hasAlpha;
  19526. texture.level = parsedTexture.level;
  19527. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19528. }
  19529. return texture;
  19530. };
  19531. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19532. if (parsedTexture.isCube) {
  19533. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19534. }
  19535. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19536. return null;
  19537. }
  19538. var texture;
  19539. if (parsedTexture.mirrorPlane) {
  19540. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19541. texture._waitingRenderList = parsedTexture.renderList;
  19542. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19543. }
  19544. else if (parsedTexture.isRenderTarget) {
  19545. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19546. texture._waitingRenderList = parsedTexture.renderList;
  19547. }
  19548. else {
  19549. if (parsedTexture.base64String) {
  19550. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19551. }
  19552. else {
  19553. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19554. }
  19555. }
  19556. texture.name = parsedTexture.name;
  19557. texture.hasAlpha = parsedTexture.hasAlpha;
  19558. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19559. texture.level = parsedTexture.level;
  19560. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19561. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19562. texture.uOffset = parsedTexture.uOffset;
  19563. texture.vOffset = parsedTexture.vOffset;
  19564. texture.uScale = parsedTexture.uScale;
  19565. texture.vScale = parsedTexture.vScale;
  19566. texture.uAng = parsedTexture.uAng;
  19567. texture.vAng = parsedTexture.vAng;
  19568. texture.wAng = parsedTexture.wAng;
  19569. texture.wrapU = parsedTexture.wrapU;
  19570. texture.wrapV = parsedTexture.wrapV;
  19571. // Animations
  19572. if (parsedTexture.animations) {
  19573. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19574. var parsedAnimation = parsedTexture.animations[animationIndex];
  19575. texture.animations.push(parseAnimation(parsedAnimation));
  19576. }
  19577. }
  19578. return texture;
  19579. };
  19580. var parseSkeleton = function (parsedSkeleton, scene) {
  19581. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19582. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19583. var parsedBone = parsedSkeleton.bones[index];
  19584. var parentBone = null;
  19585. if (parsedBone.parentBoneIndex > -1) {
  19586. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19587. }
  19588. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19589. if (parsedBone.animation) {
  19590. bone.animations.push(parseAnimation(parsedBone.animation));
  19591. }
  19592. }
  19593. return skeleton;
  19594. };
  19595. var parseFresnelParameters = function (parsedFresnelParameters) {
  19596. var fresnelParameters = new BABYLON.FresnelParameters();
  19597. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19598. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19599. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19600. fresnelParameters.bias = parsedFresnelParameters.bias;
  19601. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19602. return fresnelParameters;
  19603. };
  19604. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19605. var material;
  19606. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19607. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19608. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19609. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19610. material.specularPower = parsedMaterial.specularPower;
  19611. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19612. material.alpha = parsedMaterial.alpha;
  19613. material.id = parsedMaterial.id;
  19614. if (parsedMaterial.disableDepthWrite) {
  19615. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19616. }
  19617. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19618. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19619. material.wireframe = parsedMaterial.wireframe;
  19620. if (parsedMaterial.diffuseTexture) {
  19621. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19622. }
  19623. if (parsedMaterial.diffuseFresnelParameters) {
  19624. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19625. }
  19626. if (parsedMaterial.ambientTexture) {
  19627. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19628. }
  19629. if (parsedMaterial.opacityTexture) {
  19630. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19631. }
  19632. if (parsedMaterial.opacityFresnelParameters) {
  19633. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19634. }
  19635. if (parsedMaterial.reflectionTexture) {
  19636. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19637. }
  19638. if (parsedMaterial.reflectionFresnelParameters) {
  19639. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19640. }
  19641. if (parsedMaterial.emissiveTexture) {
  19642. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19643. }
  19644. if (parsedMaterial.emissiveFresnelParameters) {
  19645. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19646. }
  19647. if (parsedMaterial.specularTexture) {
  19648. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19649. }
  19650. if (parsedMaterial.bumpTexture) {
  19651. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19652. }
  19653. if (parsedMaterial.checkReadyOnlyOnce) {
  19654. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19655. }
  19656. return material;
  19657. };
  19658. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19659. for (var index = 0; index < parsedData.materials.length; index++) {
  19660. var parsedMaterial = parsedData.materials[index];
  19661. if (parsedMaterial.id === id) {
  19662. return parseMaterial(parsedMaterial, scene, rootUrl);
  19663. }
  19664. }
  19665. return null;
  19666. };
  19667. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19668. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19669. multiMaterial.id = parsedMultiMaterial.id;
  19670. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19671. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19672. var subMatId = parsedMultiMaterial.materials[matIndex];
  19673. if (subMatId) {
  19674. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19675. }
  19676. else {
  19677. multiMaterial.subMaterials.push(null);
  19678. }
  19679. }
  19680. return multiMaterial;
  19681. };
  19682. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19683. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19684. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19685. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19686. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19687. var parsedFlare = parsedLensFlareSystem.flares[index];
  19688. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19689. }
  19690. return lensFlareSystem;
  19691. };
  19692. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19693. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19694. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19695. if (parsedParticleSystem.textureName) {
  19696. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19697. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19698. }
  19699. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19700. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19701. particleSystem.minSize = parsedParticleSystem.minSize;
  19702. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19703. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19704. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19705. particleSystem.emitter = emitter;
  19706. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19707. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19708. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19709. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19710. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19711. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19712. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19713. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19714. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19715. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19716. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19717. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19718. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19719. particleSystem.start();
  19720. return particleSystem;
  19721. };
  19722. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19723. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19724. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19725. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19726. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19727. shadowGenerator.getShadowMap().renderList.push(mesh);
  19728. }
  19729. if (parsedShadowGenerator.usePoissonSampling) {
  19730. shadowGenerator.usePoissonSampling = true;
  19731. }
  19732. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19733. shadowGenerator.useVarianceShadowMap = true;
  19734. }
  19735. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19736. shadowGenerator.useBlurVarianceShadowMap = true;
  19737. if (parsedShadowGenerator.blurScale) {
  19738. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19739. }
  19740. if (parsedShadowGenerator.blurBoxOffset) {
  19741. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19742. }
  19743. }
  19744. if (parsedShadowGenerator.bias !== undefined) {
  19745. shadowGenerator.bias = parsedShadowGenerator.bias;
  19746. }
  19747. return shadowGenerator;
  19748. };
  19749. var parseAnimation = function (parsedAnimation) {
  19750. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19751. var dataType = parsedAnimation.dataType;
  19752. var keys = [];
  19753. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19754. var key = parsedAnimation.keys[index];
  19755. var data;
  19756. switch (dataType) {
  19757. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19758. data = key.values[0];
  19759. break;
  19760. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19761. data = BABYLON.Quaternion.FromArray(key.values);
  19762. break;
  19763. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19764. data = BABYLON.Matrix.FromArray(key.values);
  19765. break;
  19766. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19767. default:
  19768. data = BABYLON.Vector3.FromArray(key.values);
  19769. break;
  19770. }
  19771. keys.push({
  19772. frame: key.frame,
  19773. value: data
  19774. });
  19775. }
  19776. animation.setKeys(keys);
  19777. return animation;
  19778. };
  19779. var parseLight = function (parsedLight, scene) {
  19780. var light;
  19781. switch (parsedLight.type) {
  19782. case 0:
  19783. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19784. break;
  19785. case 1:
  19786. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19787. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19788. break;
  19789. case 2:
  19790. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19791. break;
  19792. case 3:
  19793. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19794. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19795. break;
  19796. }
  19797. light.id = parsedLight.id;
  19798. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19799. if (parsedLight.intensity !== undefined) {
  19800. light.intensity = parsedLight.intensity;
  19801. }
  19802. if (parsedLight.range) {
  19803. light.range = parsedLight.range;
  19804. }
  19805. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19806. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19807. if (parsedLight.excludedMeshesIds) {
  19808. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19809. }
  19810. // Parent
  19811. if (parsedLight.parentId) {
  19812. light._waitingParentId = parsedLight.parentId;
  19813. }
  19814. if (parsedLight.includedOnlyMeshesIds) {
  19815. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19816. }
  19817. // Animations
  19818. if (parsedLight.animations) {
  19819. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19820. var parsedAnimation = parsedLight.animations[animationIndex];
  19821. light.animations.push(parseAnimation(parsedAnimation));
  19822. }
  19823. }
  19824. if (parsedLight.autoAnimate) {
  19825. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19826. }
  19827. };
  19828. var parseCamera = function (parsedCamera, scene) {
  19829. var camera;
  19830. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19831. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19832. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19833. var alpha = parsedCamera.alpha;
  19834. var beta = parsedCamera.beta;
  19835. var radius = parsedCamera.radius;
  19836. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19837. var interaxial_distance = parsedCamera.interaxial_distance;
  19838. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19839. }
  19840. else {
  19841. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19842. }
  19843. }
  19844. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19845. interaxial_distance = parsedCamera.interaxial_distance;
  19846. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19847. }
  19848. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19849. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19850. }
  19851. else if (parsedCamera.type === "FollowCamera") {
  19852. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19853. camera.heightOffset = parsedCamera.heightOffset;
  19854. camera.radius = parsedCamera.radius;
  19855. camera.rotationOffset = parsedCamera.rotationOffset;
  19856. if (lockedTargetMesh)
  19857. camera.target = lockedTargetMesh;
  19858. }
  19859. else if (parsedCamera.type === "GamepadCamera") {
  19860. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19861. }
  19862. else if (parsedCamera.type === "TouchCamera") {
  19863. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19864. }
  19865. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19866. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19867. }
  19868. else if (parsedCamera.type === "WebVRFreeCamera") {
  19869. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19870. }
  19871. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19872. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19873. }
  19874. else {
  19875. // Free Camera is the default value
  19876. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19877. }
  19878. // apply 3d rig, when found
  19879. if (parsedCamera.cameraRigMode) {
  19880. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19881. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19882. }
  19883. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19884. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19885. camera.lockedTarget = lockedTargetMesh;
  19886. }
  19887. camera.id = parsedCamera.id;
  19888. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19889. // Parent
  19890. if (parsedCamera.parentId) {
  19891. camera._waitingParentId = parsedCamera.parentId;
  19892. }
  19893. // Target
  19894. if (parsedCamera.target) {
  19895. if (camera.setTarget) {
  19896. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19897. }
  19898. else {
  19899. //For ArcRotate
  19900. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19901. }
  19902. }
  19903. else {
  19904. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19905. }
  19906. camera.fov = parsedCamera.fov;
  19907. camera.minZ = parsedCamera.minZ;
  19908. camera.maxZ = parsedCamera.maxZ;
  19909. camera.speed = parsedCamera.speed;
  19910. camera.inertia = parsedCamera.inertia;
  19911. camera.checkCollisions = parsedCamera.checkCollisions;
  19912. camera.applyGravity = parsedCamera.applyGravity;
  19913. if (parsedCamera.ellipsoid) {
  19914. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19915. }
  19916. // Animations
  19917. if (parsedCamera.animations) {
  19918. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19919. var parsedAnimation = parsedCamera.animations[animationIndex];
  19920. camera.animations.push(parseAnimation(parsedAnimation));
  19921. }
  19922. }
  19923. if (parsedCamera.autoAnimate) {
  19924. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19925. }
  19926. // Layer Mask
  19927. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19928. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19929. }
  19930. else {
  19931. camera.layerMask = 0x0FFFFFFF;
  19932. }
  19933. return camera;
  19934. };
  19935. var parseGeometry = function (parsedGeometry, scene) {
  19936. var id = parsedGeometry.id;
  19937. return scene.getGeometryByID(id);
  19938. };
  19939. var parseBox = function (parsedBox, scene) {
  19940. if (parseGeometry(parsedBox, scene)) {
  19941. return null; // null since geometry could be something else than a box...
  19942. }
  19943. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19944. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19945. scene.pushGeometry(box, true);
  19946. return box;
  19947. };
  19948. var parseSphere = function (parsedSphere, scene) {
  19949. if (parseGeometry(parsedSphere, scene)) {
  19950. return null; // null since geometry could be something else than a sphere...
  19951. }
  19952. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19953. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19954. scene.pushGeometry(sphere, true);
  19955. return sphere;
  19956. };
  19957. var parseCylinder = function (parsedCylinder, scene) {
  19958. if (parseGeometry(parsedCylinder, scene)) {
  19959. return null; // null since geometry could be something else than a cylinder...
  19960. }
  19961. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19962. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19963. scene.pushGeometry(cylinder, true);
  19964. return cylinder;
  19965. };
  19966. var parseTorus = function (parsedTorus, scene) {
  19967. if (parseGeometry(parsedTorus, scene)) {
  19968. return null; // null since geometry could be something else than a torus...
  19969. }
  19970. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19971. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19972. scene.pushGeometry(torus, true);
  19973. return torus;
  19974. };
  19975. var parseGround = function (parsedGround, scene) {
  19976. if (parseGeometry(parsedGround, scene)) {
  19977. return null; // null since geometry could be something else than a ground...
  19978. }
  19979. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19980. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19981. scene.pushGeometry(ground, true);
  19982. return ground;
  19983. };
  19984. var parsePlane = function (parsedPlane, scene) {
  19985. if (parseGeometry(parsedPlane, scene)) {
  19986. return null; // null since geometry could be something else than a plane...
  19987. }
  19988. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19989. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19990. scene.pushGeometry(plane, true);
  19991. return plane;
  19992. };
  19993. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19994. if (parseGeometry(parsedTorusKnot, scene)) {
  19995. return null; // null since geometry could be something else than a torusKnot...
  19996. }
  19997. 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);
  19998. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19999. scene.pushGeometry(torusKnot, true);
  20000. return torusKnot;
  20001. };
  20002. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20003. if (parseGeometry(parsedVertexData, scene)) {
  20004. return null; // null since geometry could be a primitive
  20005. }
  20006. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20007. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20008. if (parsedVertexData.delayLoadingFile) {
  20009. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20010. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20011. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20012. geometry._delayInfo = [];
  20013. if (parsedVertexData.hasUVs) {
  20014. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20015. }
  20016. if (parsedVertexData.hasUVs2) {
  20017. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20018. }
  20019. if (parsedVertexData.hasUVs3) {
  20020. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20021. }
  20022. if (parsedVertexData.hasUVs4) {
  20023. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20024. }
  20025. if (parsedVertexData.hasUVs5) {
  20026. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20027. }
  20028. if (parsedVertexData.hasUVs6) {
  20029. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20030. }
  20031. if (parsedVertexData.hasColors) {
  20032. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20033. }
  20034. if (parsedVertexData.hasMatricesIndices) {
  20035. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20036. }
  20037. if (parsedVertexData.hasMatricesWeights) {
  20038. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20039. }
  20040. geometry._delayLoadingFunction = importVertexData;
  20041. }
  20042. else {
  20043. importVertexData(parsedVertexData, geometry);
  20044. }
  20045. scene.pushGeometry(geometry, true);
  20046. return geometry;
  20047. };
  20048. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20049. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20050. mesh.id = parsedMesh.id;
  20051. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20052. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20053. if (parsedMesh.rotationQuaternion) {
  20054. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20055. }
  20056. else if (parsedMesh.rotation) {
  20057. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20058. }
  20059. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20060. if (parsedMesh.localMatrix) {
  20061. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20062. }
  20063. else if (parsedMesh.pivotMatrix) {
  20064. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20065. }
  20066. mesh.setEnabled(parsedMesh.isEnabled);
  20067. mesh.isVisible = parsedMesh.isVisible;
  20068. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20069. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20070. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20071. if (parsedMesh.applyFog !== undefined) {
  20072. mesh.applyFog = parsedMesh.applyFog;
  20073. }
  20074. if (parsedMesh.pickable !== undefined) {
  20075. mesh.isPickable = parsedMesh.pickable;
  20076. }
  20077. if (parsedMesh.alphaIndex !== undefined) {
  20078. mesh.alphaIndex = parsedMesh.alphaIndex;
  20079. }
  20080. mesh.receiveShadows = parsedMesh.receiveShadows;
  20081. mesh.billboardMode = parsedMesh.billboardMode;
  20082. if (parsedMesh.visibility !== undefined) {
  20083. mesh.visibility = parsedMesh.visibility;
  20084. }
  20085. mesh.checkCollisions = parsedMesh.checkCollisions;
  20086. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20087. // freezeWorldMatrix
  20088. if (parsedMesh.freezeWorldMatrix) {
  20089. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20090. }
  20091. // Parent
  20092. if (parsedMesh.parentId) {
  20093. mesh._waitingParentId = parsedMesh.parentId;
  20094. }
  20095. // Actions
  20096. if (parsedMesh.actions !== undefined) {
  20097. mesh._waitingActions = parsedMesh.actions;
  20098. }
  20099. // Geometry
  20100. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20101. if (parsedMesh.delayLoadingFile) {
  20102. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20103. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20104. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20105. if (parsedMesh._binaryInfo) {
  20106. mesh._binaryInfo = parsedMesh._binaryInfo;
  20107. }
  20108. mesh._delayInfo = [];
  20109. if (parsedMesh.hasUVs) {
  20110. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20111. }
  20112. if (parsedMesh.hasUVs2) {
  20113. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20114. }
  20115. if (parsedMesh.hasUVs3) {
  20116. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20117. }
  20118. if (parsedMesh.hasUVs4) {
  20119. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20120. }
  20121. if (parsedMesh.hasUVs5) {
  20122. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20123. }
  20124. if (parsedMesh.hasUVs6) {
  20125. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20126. }
  20127. if (parsedMesh.hasColors) {
  20128. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20129. }
  20130. if (parsedMesh.hasMatricesIndices) {
  20131. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20132. }
  20133. if (parsedMesh.hasMatricesWeights) {
  20134. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20135. }
  20136. mesh._delayLoadingFunction = importGeometry;
  20137. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20138. mesh._checkDelayState();
  20139. }
  20140. }
  20141. else {
  20142. importGeometry(parsedMesh, mesh);
  20143. }
  20144. // Material
  20145. if (parsedMesh.materialId) {
  20146. mesh.setMaterialByID(parsedMesh.materialId);
  20147. }
  20148. else {
  20149. mesh.material = null;
  20150. }
  20151. // Skeleton
  20152. if (parsedMesh.skeletonId > -1) {
  20153. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20154. }
  20155. // Physics
  20156. if (parsedMesh.physicsImpostor) {
  20157. if (!scene.isPhysicsEnabled()) {
  20158. scene.enablePhysics();
  20159. }
  20160. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20161. }
  20162. // Animations
  20163. if (parsedMesh.animations) {
  20164. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20165. var parsedAnimation = parsedMesh.animations[animationIndex];
  20166. mesh.animations.push(parseAnimation(parsedAnimation));
  20167. }
  20168. }
  20169. if (parsedMesh.autoAnimate) {
  20170. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20171. }
  20172. // Layer Mask
  20173. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20174. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20175. }
  20176. else {
  20177. mesh.layerMask = 0x0FFFFFFF;
  20178. }
  20179. // Instances
  20180. if (parsedMesh.instances) {
  20181. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20182. var parsedInstance = parsedMesh.instances[index];
  20183. var instance = mesh.createInstance(parsedInstance.name);
  20184. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20185. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20186. if (parsedInstance.rotationQuaternion) {
  20187. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20188. }
  20189. else if (parsedInstance.rotation) {
  20190. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20191. }
  20192. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20193. instance.checkCollisions = mesh.checkCollisions;
  20194. if (parsedMesh.animations) {
  20195. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20196. parsedAnimation = parsedMesh.animations[animationIndex];
  20197. instance.animations.push(parseAnimation(parsedAnimation));
  20198. }
  20199. }
  20200. }
  20201. }
  20202. return mesh;
  20203. };
  20204. var parseActions = function (parsedActions, object, scene) {
  20205. var actionManager = new BABYLON.ActionManager(scene);
  20206. if (object === null)
  20207. scene.actionManager = actionManager;
  20208. else
  20209. object.actionManager = actionManager;
  20210. // instanciate a new object
  20211. var instanciate = function (name, params) {
  20212. var newInstance = Object.create(BABYLON[name].prototype);
  20213. newInstance.constructor.apply(newInstance, params);
  20214. return newInstance;
  20215. };
  20216. var parseParameter = function (name, value, target, propertyPath) {
  20217. if (propertyPath === null) {
  20218. // String, boolean or float
  20219. var floatValue = parseFloat(value);
  20220. if (value === "true" || value === "false")
  20221. return value === "true";
  20222. else
  20223. return isNaN(floatValue) ? value : floatValue;
  20224. }
  20225. var effectiveTarget = propertyPath.split(".");
  20226. var values = value.split(",");
  20227. // Get effective Target
  20228. for (var i = 0; i < effectiveTarget.length; i++) {
  20229. target = target[effectiveTarget[i]];
  20230. }
  20231. // Return appropriate value with its type
  20232. if (typeof (target) === "boolean")
  20233. return values[0] === "true";
  20234. if (typeof (target) === "string")
  20235. return values[0];
  20236. // Parameters with multiple values such as Vector3 etc.
  20237. var split = new Array();
  20238. for (var i = 0; i < values.length; i++)
  20239. split.push(parseFloat(values[i]));
  20240. if (target instanceof BABYLON.Vector3)
  20241. return BABYLON.Vector3.FromArray(split);
  20242. if (target instanceof BABYLON.Vector4)
  20243. return BABYLON.Vector4.FromArray(split);
  20244. if (target instanceof BABYLON.Color3)
  20245. return BABYLON.Color3.FromArray(split);
  20246. if (target instanceof BABYLON.Color4)
  20247. return BABYLON.Color4.FromArray(split);
  20248. return parseFloat(values[0]);
  20249. };
  20250. // traverse graph per trigger
  20251. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20252. if (combineArray === void 0) { combineArray = null; }
  20253. if (parsedAction.detached)
  20254. return;
  20255. var parameters = new Array();
  20256. var target = null;
  20257. var propertyPath = null;
  20258. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20259. // Parameters
  20260. if (parsedAction.type === 2)
  20261. parameters.push(actionManager);
  20262. else
  20263. parameters.push(trigger);
  20264. if (combine) {
  20265. var actions = new Array();
  20266. for (var j = 0; j < parsedAction.combine.length; j++) {
  20267. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20268. }
  20269. parameters.push(actions);
  20270. }
  20271. else {
  20272. for (var i = 0; i < parsedAction.properties.length; i++) {
  20273. var value = parsedAction.properties[i].value;
  20274. var name = parsedAction.properties[i].name;
  20275. var targetType = parsedAction.properties[i].targetType;
  20276. if (name === "target")
  20277. if (targetType !== null && targetType === "SceneProperties")
  20278. value = target = scene;
  20279. else
  20280. value = target = scene.getNodeByName(value);
  20281. else if (name === "parent")
  20282. value = scene.getNodeByName(value);
  20283. else if (name === "sound")
  20284. value = scene.getSoundByName(value);
  20285. else if (name !== "propertyPath") {
  20286. if (parsedAction.type === 2 && name === "operator")
  20287. value = BABYLON.ValueCondition[value];
  20288. else
  20289. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20290. }
  20291. else {
  20292. propertyPath = value;
  20293. }
  20294. parameters.push(value);
  20295. }
  20296. }
  20297. if (combineArray === null) {
  20298. parameters.push(condition);
  20299. }
  20300. else {
  20301. parameters.push(null);
  20302. }
  20303. // If interpolate value action
  20304. if (parsedAction.name === "InterpolateValueAction") {
  20305. var param = parameters[parameters.length - 2];
  20306. parameters[parameters.length - 1] = param;
  20307. parameters[parameters.length - 2] = condition;
  20308. }
  20309. // Action or condition(s) and not CombineAction
  20310. var newAction = instanciate(parsedAction.name, parameters);
  20311. if (combineArray === null) {
  20312. if (newAction instanceof BABYLON.Condition) {
  20313. condition = newAction;
  20314. newAction = action;
  20315. }
  20316. else {
  20317. condition = null;
  20318. if (action)
  20319. action.then(newAction);
  20320. else
  20321. actionManager.registerAction(newAction);
  20322. }
  20323. }
  20324. else {
  20325. combineArray.push(newAction);
  20326. }
  20327. for (var i = 0; i < parsedAction.children.length; i++)
  20328. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20329. };
  20330. // triggers
  20331. for (var i = 0; i < parsedActions.children.length; i++) {
  20332. var triggerParams;
  20333. var trigger = parsedActions.children[i];
  20334. if (trigger.properties.length > 0) {
  20335. var param = trigger.properties[0].value;
  20336. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20337. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20338. }
  20339. else
  20340. triggerParams = BABYLON.ActionManager[trigger.name];
  20341. for (var j = 0; j < trigger.children.length; j++) {
  20342. if (!trigger.detached)
  20343. traverse(trigger.children[j], triggerParams, null, null);
  20344. }
  20345. }
  20346. };
  20347. var parseSound = function (parsedSound, scene, rootUrl) {
  20348. var soundName = parsedSound.name;
  20349. var soundUrl = rootUrl + soundName;
  20350. var options = {
  20351. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20352. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20353. rolloffFactor: parsedSound.rolloffFactor,
  20354. refDistance: parsedSound.refDistance,
  20355. distanceModel: parsedSound.distanceModel,
  20356. playbackRate: parsedSound.playbackRate
  20357. };
  20358. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20359. scene._addPendingData(newSound);
  20360. if (parsedSound.position) {
  20361. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20362. newSound.setPosition(soundPosition);
  20363. }
  20364. if (parsedSound.isDirectional) {
  20365. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20366. if (parsedSound.localDirectionToMesh) {
  20367. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20368. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20369. }
  20370. }
  20371. if (parsedSound.connectedMeshId) {
  20372. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20373. if (connectedMesh) {
  20374. newSound.attachToMesh(connectedMesh);
  20375. }
  20376. }
  20377. };
  20378. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20379. names = (names instanceof Array) ? names : [names];
  20380. for (var i in names) {
  20381. if (mesh.name === names[i]) {
  20382. hierarchyIds.push(mesh.id);
  20383. return true;
  20384. }
  20385. }
  20386. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20387. hierarchyIds.push(mesh.id);
  20388. return true;
  20389. }
  20390. return false;
  20391. };
  20392. var importVertexData = function (parsedVertexData, geometry) {
  20393. var vertexData = new BABYLON.VertexData();
  20394. // positions
  20395. var positions = parsedVertexData.positions;
  20396. if (positions) {
  20397. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20398. }
  20399. // normals
  20400. var normals = parsedVertexData.normals;
  20401. if (normals) {
  20402. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20403. }
  20404. // uvs
  20405. var uvs = parsedVertexData.uvs;
  20406. if (uvs) {
  20407. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20408. }
  20409. // uv2s
  20410. var uv2s = parsedVertexData.uv2s;
  20411. if (uv2s) {
  20412. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20413. }
  20414. // uv3s
  20415. var uv3s = parsedVertexData.uv3s;
  20416. if (uv3s) {
  20417. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20418. }
  20419. // uv4s
  20420. var uv4s = parsedVertexData.uv4s;
  20421. if (uv4s) {
  20422. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20423. }
  20424. // uv5s
  20425. var uv5s = parsedVertexData.uv5s;
  20426. if (uv5s) {
  20427. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20428. }
  20429. // uv6s
  20430. var uv6s = parsedVertexData.uv6s;
  20431. if (uv6s) {
  20432. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20433. }
  20434. // colors
  20435. var colors = parsedVertexData.colors;
  20436. if (colors) {
  20437. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20438. }
  20439. // matricesIndices
  20440. var matricesIndices = parsedVertexData.matricesIndices;
  20441. if (matricesIndices) {
  20442. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20443. }
  20444. // matricesWeights
  20445. var matricesWeights = parsedVertexData.matricesWeights;
  20446. if (matricesWeights) {
  20447. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20448. }
  20449. // indices
  20450. var indices = parsedVertexData.indices;
  20451. if (indices) {
  20452. vertexData.indices = indices;
  20453. }
  20454. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20455. };
  20456. var importGeometry = function (parsedGeometry, mesh) {
  20457. var scene = mesh.getScene();
  20458. // Geometry
  20459. var geometryId = parsedGeometry.geometryId;
  20460. if (geometryId) {
  20461. var geometry = scene.getGeometryByID(geometryId);
  20462. if (geometry) {
  20463. geometry.applyToMesh(mesh);
  20464. }
  20465. }
  20466. else if (parsedGeometry instanceof ArrayBuffer) {
  20467. var binaryInfo = mesh._binaryInfo;
  20468. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20469. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20470. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20471. }
  20472. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20473. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20474. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20475. }
  20476. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20477. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20478. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20479. }
  20480. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20481. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20482. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20483. }
  20484. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20485. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20486. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20487. }
  20488. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20489. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20490. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20491. }
  20492. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20493. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20494. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20495. }
  20496. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20497. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20498. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20499. }
  20500. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20501. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20502. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20503. }
  20504. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20505. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20506. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20507. }
  20508. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20509. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20510. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20511. }
  20512. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20513. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20514. mesh.setIndices(indicesData);
  20515. }
  20516. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20517. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20518. mesh.subMeshes = [];
  20519. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20520. var materialIndex = subMeshesData[(i * 5) + 0];
  20521. var verticesStart = subMeshesData[(i * 5) + 1];
  20522. var verticesCount = subMeshesData[(i * 5) + 2];
  20523. var indexStart = subMeshesData[(i * 5) + 3];
  20524. var indexCount = subMeshesData[(i * 5) + 4];
  20525. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20526. }
  20527. }
  20528. }
  20529. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20530. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20531. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20532. if (parsedGeometry.uvs) {
  20533. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20534. }
  20535. if (parsedGeometry.uvs2) {
  20536. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20537. }
  20538. if (parsedGeometry.uvs3) {
  20539. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20540. }
  20541. if (parsedGeometry.uvs4) {
  20542. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20543. }
  20544. if (parsedGeometry.uvs5) {
  20545. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20546. }
  20547. if (parsedGeometry.uvs6) {
  20548. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20549. }
  20550. if (parsedGeometry.colors) {
  20551. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20552. }
  20553. if (parsedGeometry.matricesIndices) {
  20554. if (!parsedGeometry.matricesIndices._isExpanded) {
  20555. var floatIndices = [];
  20556. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20557. var matricesIndex = parsedGeometry.matricesIndices[i];
  20558. floatIndices.push(matricesIndex & 0x000000FF);
  20559. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20560. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20561. floatIndices.push(matricesIndex >> 24);
  20562. }
  20563. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20564. }
  20565. else {
  20566. delete parsedGeometry.matricesIndices._isExpanded;
  20567. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20568. }
  20569. }
  20570. if (parsedGeometry.matricesWeights) {
  20571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20572. }
  20573. mesh.setIndices(parsedGeometry.indices);
  20574. }
  20575. // SubMeshes
  20576. if (parsedGeometry.subMeshes) {
  20577. mesh.subMeshes = [];
  20578. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20579. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20580. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20581. }
  20582. }
  20583. // Flat shading
  20584. if (mesh._shouldGenerateFlatShading) {
  20585. mesh.convertToFlatShadedMesh();
  20586. delete mesh._shouldGenerateFlatShading;
  20587. }
  20588. // Update
  20589. mesh.computeWorldMatrix(true);
  20590. // Octree
  20591. if (scene._selectionOctree) {
  20592. scene._selectionOctree.addMesh(mesh);
  20593. }
  20594. };
  20595. BABYLON.SceneLoader.RegisterPlugin({
  20596. extensions: ".babylon",
  20597. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20598. var parsedData = JSON.parse(data);
  20599. var loadedSkeletonsIds = [];
  20600. var loadedMaterialsIds = [];
  20601. var hierarchyIds = [];
  20602. for (var index = 0; index < parsedData.meshes.length; index++) {
  20603. var parsedMesh = parsedData.meshes[index];
  20604. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20605. if (meshesNames instanceof Array) {
  20606. // Remove found mesh name from list.
  20607. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20608. }
  20609. //Geometry?
  20610. if (parsedMesh.geometryId) {
  20611. //does the file contain geometries?
  20612. if (parsedData.geometries) {
  20613. //find the correct geometry and add it to the scene
  20614. var found = false;
  20615. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20616. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20617. return;
  20618. }
  20619. else {
  20620. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20621. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20622. switch (geometryType) {
  20623. case "boxes":
  20624. parseBox(parsedGeometryData, scene);
  20625. break;
  20626. case "spheres":
  20627. parseSphere(parsedGeometryData, scene);
  20628. break;
  20629. case "cylinders":
  20630. parseCylinder(parsedGeometryData, scene);
  20631. break;
  20632. case "toruses":
  20633. parseTorus(parsedGeometryData, scene);
  20634. break;
  20635. case "grounds":
  20636. parseGround(parsedGeometryData, scene);
  20637. break;
  20638. case "planes":
  20639. parsePlane(parsedGeometryData, scene);
  20640. break;
  20641. case "torusKnots":
  20642. parseTorusKnot(parsedGeometryData, scene);
  20643. break;
  20644. case "vertexData":
  20645. parseVertexData(parsedGeometryData, scene, rootUrl);
  20646. break;
  20647. }
  20648. found = true;
  20649. }
  20650. });
  20651. }
  20652. });
  20653. if (!found) {
  20654. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20655. }
  20656. }
  20657. }
  20658. // Material ?
  20659. if (parsedMesh.materialId) {
  20660. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20661. if (!materialFound && parsedData.multiMaterials) {
  20662. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20663. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20664. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20665. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20666. var subMatId = parsedMultiMaterial.materials[matIndex];
  20667. loadedMaterialsIds.push(subMatId);
  20668. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20669. }
  20670. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20671. parseMultiMaterial(parsedMultiMaterial, scene);
  20672. materialFound = true;
  20673. break;
  20674. }
  20675. }
  20676. }
  20677. if (!materialFound) {
  20678. loadedMaterialsIds.push(parsedMesh.materialId);
  20679. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20680. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20681. }
  20682. }
  20683. }
  20684. // Skeleton ?
  20685. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20686. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20687. if (!skeletonAlreadyLoaded) {
  20688. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20689. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20690. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20691. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20692. loadedSkeletonsIds.push(parsedSkeleton.id);
  20693. }
  20694. }
  20695. }
  20696. }
  20697. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20698. meshes.push(mesh);
  20699. }
  20700. }
  20701. // Connecting parents
  20702. for (index = 0; index < scene.meshes.length; index++) {
  20703. var currentMesh = scene.meshes[index];
  20704. if (currentMesh._waitingParentId) {
  20705. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20706. currentMesh._waitingParentId = undefined;
  20707. }
  20708. }
  20709. // freeze world matrix application
  20710. for (index = 0; index < scene.meshes.length; index++) {
  20711. var currentMesh = scene.meshes[index];
  20712. if (currentMesh._waitingFreezeWorldMatrix) {
  20713. currentMesh.freezeWorldMatrix();
  20714. currentMesh._waitingFreezeWorldMatrix = undefined;
  20715. }
  20716. }
  20717. // Particles
  20718. if (parsedData.particleSystems) {
  20719. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20720. var parsedParticleSystem = parsedData.particleSystems[index];
  20721. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20722. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20723. }
  20724. }
  20725. }
  20726. return true;
  20727. },
  20728. load: function (scene, data, rootUrl) {
  20729. var parsedData = JSON.parse(data);
  20730. // Scene
  20731. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20732. scene.autoClear = parsedData.autoClear;
  20733. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20734. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20735. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20736. // Fog
  20737. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20738. scene.fogMode = parsedData.fogMode;
  20739. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20740. scene.fogStart = parsedData.fogStart;
  20741. scene.fogEnd = parsedData.fogEnd;
  20742. scene.fogDensity = parsedData.fogDensity;
  20743. }
  20744. // Lights
  20745. for (var index = 0; index < parsedData.lights.length; index++) {
  20746. var parsedLight = parsedData.lights[index];
  20747. parseLight(parsedLight, scene);
  20748. }
  20749. // Materials
  20750. if (parsedData.materials) {
  20751. for (index = 0; index < parsedData.materials.length; index++) {
  20752. var parsedMaterial = parsedData.materials[index];
  20753. parseMaterial(parsedMaterial, scene, rootUrl);
  20754. }
  20755. }
  20756. if (parsedData.multiMaterials) {
  20757. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20758. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20759. parseMultiMaterial(parsedMultiMaterial, scene);
  20760. }
  20761. }
  20762. // Skeletons
  20763. if (parsedData.skeletons) {
  20764. for (index = 0; index < parsedData.skeletons.length; index++) {
  20765. var parsedSkeleton = parsedData.skeletons[index];
  20766. parseSkeleton(parsedSkeleton, scene);
  20767. }
  20768. }
  20769. // Geometries
  20770. var geometries = parsedData.geometries;
  20771. if (geometries) {
  20772. // Boxes
  20773. var boxes = geometries.boxes;
  20774. if (boxes) {
  20775. for (index = 0; index < boxes.length; index++) {
  20776. var parsedBox = boxes[index];
  20777. parseBox(parsedBox, scene);
  20778. }
  20779. }
  20780. // Spheres
  20781. var spheres = geometries.spheres;
  20782. if (spheres) {
  20783. for (index = 0; index < spheres.length; index++) {
  20784. var parsedSphere = spheres[index];
  20785. parseSphere(parsedSphere, scene);
  20786. }
  20787. }
  20788. // Cylinders
  20789. var cylinders = geometries.cylinders;
  20790. if (cylinders) {
  20791. for (index = 0; index < cylinders.length; index++) {
  20792. var parsedCylinder = cylinders[index];
  20793. parseCylinder(parsedCylinder, scene);
  20794. }
  20795. }
  20796. // Toruses
  20797. var toruses = geometries.toruses;
  20798. if (toruses) {
  20799. for (index = 0; index < toruses.length; index++) {
  20800. var parsedTorus = toruses[index];
  20801. parseTorus(parsedTorus, scene);
  20802. }
  20803. }
  20804. // Grounds
  20805. var grounds = geometries.grounds;
  20806. if (grounds) {
  20807. for (index = 0; index < grounds.length; index++) {
  20808. var parsedGround = grounds[index];
  20809. parseGround(parsedGround, scene);
  20810. }
  20811. }
  20812. // Planes
  20813. var planes = geometries.planes;
  20814. if (planes) {
  20815. for (index = 0; index < planes.length; index++) {
  20816. var parsedPlane = planes[index];
  20817. parsePlane(parsedPlane, scene);
  20818. }
  20819. }
  20820. // TorusKnots
  20821. var torusKnots = geometries.torusKnots;
  20822. if (torusKnots) {
  20823. for (index = 0; index < torusKnots.length; index++) {
  20824. var parsedTorusKnot = torusKnots[index];
  20825. parseTorusKnot(parsedTorusKnot, scene);
  20826. }
  20827. }
  20828. // VertexData
  20829. var vertexData = geometries.vertexData;
  20830. if (vertexData) {
  20831. for (index = 0; index < vertexData.length; index++) {
  20832. var parsedVertexData = vertexData[index];
  20833. parseVertexData(parsedVertexData, scene, rootUrl);
  20834. }
  20835. }
  20836. }
  20837. // Meshes
  20838. for (index = 0; index < parsedData.meshes.length; index++) {
  20839. var parsedMesh = parsedData.meshes[index];
  20840. parseMesh(parsedMesh, scene, rootUrl);
  20841. }
  20842. // Cameras
  20843. for (index = 0; index < parsedData.cameras.length; index++) {
  20844. var parsedCamera = parsedData.cameras[index];
  20845. parseCamera(parsedCamera, scene);
  20846. }
  20847. if (parsedData.activeCameraID) {
  20848. scene.setActiveCameraByID(parsedData.activeCameraID);
  20849. }
  20850. // Browsing all the graph to connect the dots
  20851. for (index = 0; index < scene.cameras.length; index++) {
  20852. var camera = scene.cameras[index];
  20853. if (camera._waitingParentId) {
  20854. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20855. camera._waitingParentId = undefined;
  20856. }
  20857. }
  20858. for (index = 0; index < scene.lights.length; index++) {
  20859. var light = scene.lights[index];
  20860. if (light._waitingParentId) {
  20861. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20862. light._waitingParentId = undefined;
  20863. }
  20864. }
  20865. // Sounds
  20866. if (parsedData.sounds) {
  20867. for (index = 0; index < parsedData.sounds.length; index++) {
  20868. var parsedSound = parsedData.sounds[index];
  20869. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20870. parseSound(parsedSound, scene, rootUrl);
  20871. }
  20872. else {
  20873. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20874. }
  20875. }
  20876. }
  20877. // Connect parents & children and parse actions
  20878. for (index = 0; index < scene.meshes.length; index++) {
  20879. var mesh = scene.meshes[index];
  20880. if (mesh._waitingParentId) {
  20881. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20882. mesh._waitingParentId = undefined;
  20883. }
  20884. if (mesh._waitingActions) {
  20885. parseActions(mesh._waitingActions, mesh, scene);
  20886. mesh._waitingActions = undefined;
  20887. }
  20888. }
  20889. // freeze world matrix application
  20890. for (index = 0; index < scene.meshes.length; index++) {
  20891. var currentMesh = scene.meshes[index];
  20892. if (currentMesh._waitingFreezeWorldMatrix) {
  20893. currentMesh.freezeWorldMatrix();
  20894. currentMesh._waitingFreezeWorldMatrix = undefined;
  20895. }
  20896. }
  20897. // Particles Systems
  20898. if (parsedData.particleSystems) {
  20899. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20900. var parsedParticleSystem = parsedData.particleSystems[index];
  20901. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20902. }
  20903. }
  20904. // Lens flares
  20905. if (parsedData.lensFlareSystems) {
  20906. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20907. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20908. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20909. }
  20910. }
  20911. // Shadows
  20912. if (parsedData.shadowGenerators) {
  20913. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20914. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20915. parseShadowGenerator(parsedShadowGenerator, scene);
  20916. }
  20917. }
  20918. // Actions (scene)
  20919. if (parsedData.actions) {
  20920. parseActions(parsedData.actions, null, scene);
  20921. }
  20922. // Finish
  20923. return true;
  20924. }
  20925. });
  20926. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20927. })(BABYLON || (BABYLON = {}));
  20928. var BABYLON;
  20929. (function (BABYLON) {
  20930. var SpriteManager = (function () {
  20931. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20933. this.name = name;
  20934. this.cellSize = cellSize;
  20935. this.sprites = new Array();
  20936. this.renderingGroupId = 0;
  20937. this.fogEnabled = true;
  20938. this._vertexDeclaration = [4, 4, 4, 4];
  20939. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20940. this._capacity = capacity;
  20941. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20942. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20943. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20944. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20945. this._scene = scene;
  20946. this._scene.spriteManagers.push(this);
  20947. // VBO
  20948. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20949. var indices = [];
  20950. var index = 0;
  20951. for (var count = 0; count < capacity; count++) {
  20952. indices.push(index);
  20953. indices.push(index + 1);
  20954. indices.push(index + 2);
  20955. indices.push(index);
  20956. indices.push(index + 2);
  20957. indices.push(index + 3);
  20958. index += 4;
  20959. }
  20960. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20961. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20962. // Effects
  20963. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20964. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20965. }
  20966. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20967. var arrayOffset = index * 16;
  20968. if (offsetX === 0)
  20969. offsetX = this._epsilon;
  20970. else if (offsetX === 1)
  20971. offsetX = 1 - this._epsilon;
  20972. if (offsetY === 0)
  20973. offsetY = this._epsilon;
  20974. else if (offsetY === 1)
  20975. offsetY = 1 - this._epsilon;
  20976. this._vertices[arrayOffset] = sprite.position.x;
  20977. this._vertices[arrayOffset + 1] = sprite.position.y;
  20978. this._vertices[arrayOffset + 2] = sprite.position.z;
  20979. this._vertices[arrayOffset + 3] = sprite.angle;
  20980. this._vertices[arrayOffset + 4] = sprite.width;
  20981. this._vertices[arrayOffset + 5] = sprite.height;
  20982. this._vertices[arrayOffset + 6] = offsetX;
  20983. this._vertices[arrayOffset + 7] = offsetY;
  20984. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20985. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20986. var offset = (sprite.cellIndex / rowSize) >> 0;
  20987. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20988. this._vertices[arrayOffset + 11] = offset;
  20989. // Color
  20990. this._vertices[arrayOffset + 12] = sprite.color.r;
  20991. this._vertices[arrayOffset + 13] = sprite.color.g;
  20992. this._vertices[arrayOffset + 14] = sprite.color.b;
  20993. this._vertices[arrayOffset + 15] = sprite.color.a;
  20994. };
  20995. SpriteManager.prototype.render = function () {
  20996. // Check
  20997. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20998. return;
  20999. var engine = this._scene.getEngine();
  21000. var baseSize = this._spriteTexture.getBaseSize();
  21001. // Sprites
  21002. var deltaTime = engine.getDeltaTime();
  21003. var max = Math.min(this._capacity, this.sprites.length);
  21004. var rowSize = baseSize.width / this.cellSize;
  21005. var offset = 0;
  21006. for (var index = 0; index < max; index++) {
  21007. var sprite = this.sprites[index];
  21008. if (!sprite) {
  21009. continue;
  21010. }
  21011. sprite._animate(deltaTime);
  21012. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21013. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21014. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21015. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21016. }
  21017. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21018. // Render
  21019. var effect = this._effectBase;
  21020. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21021. effect = this._effectFog;
  21022. }
  21023. engine.enableEffect(effect);
  21024. var viewMatrix = this._scene.getViewMatrix();
  21025. effect.setTexture("diffuseSampler", this._spriteTexture);
  21026. effect.setMatrix("view", viewMatrix);
  21027. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21028. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21029. // Fog
  21030. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21031. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21032. effect.setColor3("vFogColor", this._scene.fogColor);
  21033. }
  21034. // VBOs
  21035. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21036. // Draw order
  21037. engine.setDepthFunctionToLessOrEqual();
  21038. effect.setBool("alphaTest", true);
  21039. engine.setColorWrite(false);
  21040. engine.draw(true, 0, max * 6);
  21041. engine.setColorWrite(true);
  21042. effect.setBool("alphaTest", false);
  21043. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21044. engine.draw(true, 0, max * 6);
  21045. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21046. };
  21047. SpriteManager.prototype.dispose = function () {
  21048. if (this._vertexBuffer) {
  21049. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21050. this._vertexBuffer = null;
  21051. }
  21052. if (this._indexBuffer) {
  21053. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21054. this._indexBuffer = null;
  21055. }
  21056. if (this._spriteTexture) {
  21057. this._spriteTexture.dispose();
  21058. this._spriteTexture = null;
  21059. }
  21060. // Remove from scene
  21061. var index = this._scene.spriteManagers.indexOf(this);
  21062. this._scene.spriteManagers.splice(index, 1);
  21063. // Callback
  21064. if (this.onDispose) {
  21065. this.onDispose();
  21066. }
  21067. };
  21068. return SpriteManager;
  21069. })();
  21070. BABYLON.SpriteManager = SpriteManager;
  21071. })(BABYLON || (BABYLON = {}));
  21072. var BABYLON;
  21073. (function (BABYLON) {
  21074. var Sprite = (function () {
  21075. function Sprite(name, manager) {
  21076. this.name = name;
  21077. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21078. this.width = 1.0;
  21079. this.height = 1.0;
  21080. this.angle = 0;
  21081. this.cellIndex = 0;
  21082. this.invertU = 0;
  21083. this.invertV = 0;
  21084. this.animations = new Array();
  21085. this._animationStarted = false;
  21086. this._loopAnimation = false;
  21087. this._fromIndex = 0;
  21088. this._toIndex = 0;
  21089. this._delay = 0;
  21090. this._direction = 1;
  21091. this._frameCount = 0;
  21092. this._time = 0;
  21093. this._manager = manager;
  21094. this._manager.sprites.push(this);
  21095. this.position = BABYLON.Vector3.Zero();
  21096. }
  21097. Object.defineProperty(Sprite.prototype, "size", {
  21098. get: function () {
  21099. return this.width;
  21100. },
  21101. set: function (value) {
  21102. this.width = value;
  21103. this.height = value;
  21104. },
  21105. enumerable: true,
  21106. configurable: true
  21107. });
  21108. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21109. this._fromIndex = from;
  21110. this._toIndex = to;
  21111. this._loopAnimation = loop;
  21112. this._delay = delay;
  21113. this._animationStarted = true;
  21114. this._direction = from < to ? 1 : -1;
  21115. this.cellIndex = from;
  21116. this._time = 0;
  21117. };
  21118. Sprite.prototype.stopAnimation = function () {
  21119. this._animationStarted = false;
  21120. };
  21121. Sprite.prototype._animate = function (deltaTime) {
  21122. if (!this._animationStarted)
  21123. return;
  21124. this._time += deltaTime;
  21125. if (this._time > this._delay) {
  21126. this._time = this._time % this._delay;
  21127. this.cellIndex += this._direction;
  21128. if (this.cellIndex == this._toIndex) {
  21129. if (this._loopAnimation) {
  21130. this.cellIndex = this._fromIndex;
  21131. }
  21132. else {
  21133. this._animationStarted = false;
  21134. if (this.disposeWhenFinishedAnimating) {
  21135. this.dispose();
  21136. }
  21137. }
  21138. }
  21139. }
  21140. };
  21141. Sprite.prototype.dispose = function () {
  21142. for (var i = 0; i < this._manager.sprites.length; i++) {
  21143. if (this._manager.sprites[i] == this) {
  21144. this._manager.sprites.splice(i, 1);
  21145. }
  21146. }
  21147. };
  21148. return Sprite;
  21149. })();
  21150. BABYLON.Sprite = Sprite;
  21151. })(BABYLON || (BABYLON = {}));
  21152. var BABYLON;
  21153. (function (BABYLON) {
  21154. var Layer = (function () {
  21155. function Layer(name, imgUrl, scene, isBackground, color) {
  21156. this.name = name;
  21157. this._vertexDeclaration = [2];
  21158. this._vertexStrideSize = 2 * 4;
  21159. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21160. this.isBackground = isBackground === undefined ? true : isBackground;
  21161. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21162. this._scene = scene;
  21163. this._scene.layers.push(this);
  21164. // VBO
  21165. var vertices = [];
  21166. vertices.push(1, 1);
  21167. vertices.push(-1, 1);
  21168. vertices.push(-1, -1);
  21169. vertices.push(1, -1);
  21170. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21171. // Indices
  21172. var indices = [];
  21173. indices.push(0);
  21174. indices.push(1);
  21175. indices.push(2);
  21176. indices.push(0);
  21177. indices.push(2);
  21178. indices.push(3);
  21179. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21180. // Effects
  21181. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21182. }
  21183. Layer.prototype.render = function () {
  21184. // Check
  21185. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21186. return;
  21187. var engine = this._scene.getEngine();
  21188. // Render
  21189. engine.enableEffect(this._effect);
  21190. engine.setState(false);
  21191. // Texture
  21192. this._effect.setTexture("textureSampler", this.texture);
  21193. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21194. // Color
  21195. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21196. // VBOs
  21197. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21198. // Draw order
  21199. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21200. engine.draw(true, 0, 6);
  21201. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21202. };
  21203. Layer.prototype.dispose = function () {
  21204. if (this._vertexBuffer) {
  21205. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21206. this._vertexBuffer = null;
  21207. }
  21208. if (this._indexBuffer) {
  21209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21210. this._indexBuffer = null;
  21211. }
  21212. if (this.texture) {
  21213. this.texture.dispose();
  21214. this.texture = null;
  21215. }
  21216. // Remove from scene
  21217. var index = this._scene.layers.indexOf(this);
  21218. this._scene.layers.splice(index, 1);
  21219. // Callback
  21220. if (this.onDispose) {
  21221. this.onDispose();
  21222. }
  21223. };
  21224. return Layer;
  21225. })();
  21226. BABYLON.Layer = Layer;
  21227. })(BABYLON || (BABYLON = {}));
  21228. var BABYLON;
  21229. (function (BABYLON) {
  21230. var Particle = (function () {
  21231. function Particle() {
  21232. this.position = BABYLON.Vector3.Zero();
  21233. this.direction = BABYLON.Vector3.Zero();
  21234. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21235. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21236. this.lifeTime = 1.0;
  21237. this.age = 0;
  21238. this.size = 0;
  21239. this.angle = 0;
  21240. this.angularSpeed = 0;
  21241. }
  21242. Particle.prototype.copyTo = function (other) {
  21243. other.position.copyFrom(this.position);
  21244. other.direction.copyFrom(this.direction);
  21245. other.color.copyFrom(this.color);
  21246. other.colorStep.copyFrom(this.colorStep);
  21247. other.lifeTime = this.lifeTime;
  21248. other.age = this.age;
  21249. other.size = this.size;
  21250. other.angle = this.angle;
  21251. other.angularSpeed = this.angularSpeed;
  21252. };
  21253. return Particle;
  21254. })();
  21255. BABYLON.Particle = Particle;
  21256. })(BABYLON || (BABYLON = {}));
  21257. var BABYLON;
  21258. (function (BABYLON) {
  21259. var randomNumber = function (min, max) {
  21260. if (min === max) {
  21261. return (min);
  21262. }
  21263. var random = Math.random();
  21264. return ((random * (max - min)) + min);
  21265. };
  21266. var ParticleSystem = (function () {
  21267. function ParticleSystem(name, capacity, scene, customEffect) {
  21268. var _this = this;
  21269. this.name = name;
  21270. this.renderingGroupId = 0;
  21271. this.emitter = null;
  21272. this.emitRate = 10;
  21273. this.manualEmitCount = -1;
  21274. this.updateSpeed = 0.01;
  21275. this.targetStopDuration = 0;
  21276. this.disposeOnStop = false;
  21277. this.minEmitPower = 1;
  21278. this.maxEmitPower = 1;
  21279. this.minLifeTime = 1;
  21280. this.maxLifeTime = 1;
  21281. this.minSize = 1;
  21282. this.maxSize = 1;
  21283. this.minAngularSpeed = 0;
  21284. this.maxAngularSpeed = 0;
  21285. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21286. this.forceDepthWrite = false;
  21287. this.gravity = BABYLON.Vector3.Zero();
  21288. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21289. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21290. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21291. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21292. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21293. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21294. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21295. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21296. this.particles = new Array();
  21297. this._vertexDeclaration = [3, 4, 4];
  21298. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21299. this._stockParticles = new Array();
  21300. this._newPartsExcess = 0;
  21301. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21302. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21303. this._scaledDirection = BABYLON.Vector3.Zero();
  21304. this._scaledGravity = BABYLON.Vector3.Zero();
  21305. this._currentRenderId = -1;
  21306. this._started = false;
  21307. this._stopped = false;
  21308. this._actualFrame = 0;
  21309. this.id = name;
  21310. this._capacity = capacity;
  21311. this._scene = scene;
  21312. this._customEffect = customEffect;
  21313. scene.particleSystems.push(this);
  21314. // VBO
  21315. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21316. var indices = [];
  21317. var index = 0;
  21318. for (var count = 0; count < capacity; count++) {
  21319. indices.push(index);
  21320. indices.push(index + 1);
  21321. indices.push(index + 2);
  21322. indices.push(index);
  21323. indices.push(index + 2);
  21324. indices.push(index + 3);
  21325. index += 4;
  21326. }
  21327. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21328. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21329. // Default behaviors
  21330. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21331. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21332. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21333. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21334. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21335. };
  21336. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21337. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21338. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21339. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21340. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21341. };
  21342. this.updateFunction = function (particles) {
  21343. for (var index = 0; index < particles.length; index++) {
  21344. var particle = particles[index];
  21345. particle.age += _this._scaledUpdateSpeed;
  21346. if (particle.age >= particle.lifeTime) {
  21347. _this.recycleParticle(particle);
  21348. index--;
  21349. continue;
  21350. }
  21351. else {
  21352. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21353. particle.color.addInPlace(_this._scaledColorStep);
  21354. if (particle.color.a < 0)
  21355. particle.color.a = 0;
  21356. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21357. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21358. particle.position.addInPlace(_this._scaledDirection);
  21359. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21360. particle.direction.addInPlace(_this._scaledGravity);
  21361. }
  21362. }
  21363. };
  21364. }
  21365. ParticleSystem.prototype.recycleParticle = function (particle) {
  21366. var lastParticle = this.particles.pop();
  21367. if (lastParticle !== particle) {
  21368. lastParticle.copyTo(particle);
  21369. this._stockParticles.push(lastParticle);
  21370. }
  21371. };
  21372. ParticleSystem.prototype.getCapacity = function () {
  21373. return this._capacity;
  21374. };
  21375. ParticleSystem.prototype.isAlive = function () {
  21376. return this._alive;
  21377. };
  21378. ParticleSystem.prototype.isStarted = function () {
  21379. return this._started;
  21380. };
  21381. ParticleSystem.prototype.start = function () {
  21382. this._started = true;
  21383. this._stopped = false;
  21384. this._actualFrame = 0;
  21385. };
  21386. ParticleSystem.prototype.stop = function () {
  21387. this._stopped = true;
  21388. };
  21389. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21390. var offset = index * 11;
  21391. this._vertices[offset] = particle.position.x;
  21392. this._vertices[offset + 1] = particle.position.y;
  21393. this._vertices[offset + 2] = particle.position.z;
  21394. this._vertices[offset + 3] = particle.color.r;
  21395. this._vertices[offset + 4] = particle.color.g;
  21396. this._vertices[offset + 5] = particle.color.b;
  21397. this._vertices[offset + 6] = particle.color.a;
  21398. this._vertices[offset + 7] = particle.angle;
  21399. this._vertices[offset + 8] = particle.size;
  21400. this._vertices[offset + 9] = offsetX;
  21401. this._vertices[offset + 10] = offsetY;
  21402. };
  21403. ParticleSystem.prototype._update = function (newParticles) {
  21404. // Update current
  21405. this._alive = this.particles.length > 0;
  21406. this.updateFunction(this.particles);
  21407. // Add new ones
  21408. var worldMatrix;
  21409. if (this.emitter.position) {
  21410. worldMatrix = this.emitter.getWorldMatrix();
  21411. }
  21412. else {
  21413. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21414. }
  21415. for (var index = 0; index < newParticles; index++) {
  21416. if (this.particles.length === this._capacity) {
  21417. break;
  21418. }
  21419. if (this._stockParticles.length !== 0) {
  21420. var particle = this._stockParticles.pop();
  21421. particle.age = 0;
  21422. }
  21423. else {
  21424. particle = new BABYLON.Particle();
  21425. }
  21426. this.particles.push(particle);
  21427. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21428. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21429. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21430. particle.size = randomNumber(this.minSize, this.maxSize);
  21431. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21432. this.startPositionFunction(worldMatrix, particle.position);
  21433. var step = randomNumber(0, 1.0);
  21434. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21435. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21436. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21437. }
  21438. };
  21439. ParticleSystem.prototype._getEffect = function () {
  21440. if (this._customEffect) {
  21441. return this._customEffect;
  21442. }
  21443. ;
  21444. var defines = [];
  21445. if (this._scene.clipPlane) {
  21446. defines.push("#define CLIPPLANE");
  21447. }
  21448. // Effect
  21449. var join = defines.join("\n");
  21450. if (this._cachedDefines !== join) {
  21451. this._cachedDefines = join;
  21452. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21453. }
  21454. return this._effect;
  21455. };
  21456. ParticleSystem.prototype.animate = function () {
  21457. if (!this._started)
  21458. return;
  21459. var effect = this._getEffect();
  21460. // Check
  21461. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21462. return;
  21463. if (this._currentRenderId === this._scene.getRenderId()) {
  21464. return;
  21465. }
  21466. this._currentRenderId = this._scene.getRenderId();
  21467. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21468. // determine the number of particles we need to create
  21469. var emitCout;
  21470. if (this.manualEmitCount > -1) {
  21471. emitCout = this.manualEmitCount;
  21472. this.manualEmitCount = 0;
  21473. }
  21474. else {
  21475. emitCout = this.emitRate;
  21476. }
  21477. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21478. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21479. if (this._newPartsExcess > 1.0) {
  21480. newParticles += this._newPartsExcess >> 0;
  21481. this._newPartsExcess -= this._newPartsExcess >> 0;
  21482. }
  21483. this._alive = false;
  21484. if (!this._stopped) {
  21485. this._actualFrame += this._scaledUpdateSpeed;
  21486. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21487. this.stop();
  21488. }
  21489. else {
  21490. newParticles = 0;
  21491. }
  21492. this._update(newParticles);
  21493. // Stopped?
  21494. if (this._stopped) {
  21495. if (!this._alive) {
  21496. this._started = false;
  21497. if (this.disposeOnStop) {
  21498. this._scene._toBeDisposed.push(this);
  21499. }
  21500. }
  21501. }
  21502. // Update VBO
  21503. var offset = 0;
  21504. for (var index = 0; index < this.particles.length; index++) {
  21505. var particle = this.particles[index];
  21506. this._appendParticleVertex(offset++, particle, 0, 0);
  21507. this._appendParticleVertex(offset++, particle, 1, 0);
  21508. this._appendParticleVertex(offset++, particle, 1, 1);
  21509. this._appendParticleVertex(offset++, particle, 0, 1);
  21510. }
  21511. var engine = this._scene.getEngine();
  21512. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21513. };
  21514. ParticleSystem.prototype.render = function () {
  21515. var effect = this._getEffect();
  21516. // Check
  21517. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21518. return 0;
  21519. var engine = this._scene.getEngine();
  21520. // Render
  21521. engine.enableEffect(effect);
  21522. engine.setState(false);
  21523. var viewMatrix = this._scene.getViewMatrix();
  21524. effect.setTexture("diffuseSampler", this.particleTexture);
  21525. effect.setMatrix("view", viewMatrix);
  21526. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21527. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21528. if (this._scene.clipPlane) {
  21529. var clipPlane = this._scene.clipPlane;
  21530. var invView = viewMatrix.clone();
  21531. invView.invert();
  21532. effect.setMatrix("invView", invView);
  21533. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21534. }
  21535. // VBOs
  21536. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21537. // Draw order
  21538. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21539. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21540. }
  21541. else {
  21542. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21543. }
  21544. if (this.forceDepthWrite) {
  21545. engine.setDepthWrite(true);
  21546. }
  21547. engine.draw(true, 0, this.particles.length * 6);
  21548. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21549. return this.particles.length;
  21550. };
  21551. ParticleSystem.prototype.dispose = function () {
  21552. if (this._vertexBuffer) {
  21553. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21554. this._vertexBuffer = null;
  21555. }
  21556. if (this._indexBuffer) {
  21557. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21558. this._indexBuffer = null;
  21559. }
  21560. if (this.particleTexture) {
  21561. this.particleTexture.dispose();
  21562. this.particleTexture = null;
  21563. }
  21564. // Remove from scene
  21565. var index = this._scene.particleSystems.indexOf(this);
  21566. this._scene.particleSystems.splice(index, 1);
  21567. // Callback
  21568. if (this.onDispose) {
  21569. this.onDispose();
  21570. }
  21571. };
  21572. // Clone
  21573. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21574. var result = new ParticleSystem(name, this._capacity, this._scene);
  21575. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21576. if (newEmitter === undefined) {
  21577. newEmitter = this.emitter;
  21578. }
  21579. result.emitter = newEmitter;
  21580. if (this.particleTexture) {
  21581. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21582. }
  21583. result.start();
  21584. return result;
  21585. };
  21586. // Statics
  21587. ParticleSystem.BLENDMODE_ONEONE = 0;
  21588. ParticleSystem.BLENDMODE_STANDARD = 1;
  21589. return ParticleSystem;
  21590. })();
  21591. BABYLON.ParticleSystem = ParticleSystem;
  21592. })(BABYLON || (BABYLON = {}));
  21593. var BABYLON;
  21594. (function (BABYLON) {
  21595. var Animation = (function () {
  21596. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21597. this.name = name;
  21598. this.targetProperty = targetProperty;
  21599. this.framePerSecond = framePerSecond;
  21600. this.dataType = dataType;
  21601. this.loopMode = loopMode;
  21602. this._offsetsCache = {};
  21603. this._highLimitsCache = {};
  21604. this._stopped = false;
  21605. this.allowMatricesInterpolation = false;
  21606. this.targetPropertyPath = targetProperty.split(".");
  21607. this.dataType = dataType;
  21608. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21609. }
  21610. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21611. var dataType = undefined;
  21612. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21613. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21614. }
  21615. else if (from instanceof BABYLON.Quaternion) {
  21616. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21617. }
  21618. else if (from instanceof BABYLON.Vector3) {
  21619. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21620. }
  21621. else if (from instanceof BABYLON.Vector2) {
  21622. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21623. }
  21624. else if (from instanceof BABYLON.Color3) {
  21625. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21626. }
  21627. if (dataType == undefined) {
  21628. return null;
  21629. }
  21630. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21631. var keys = [];
  21632. keys.push({ frame: 0, value: from });
  21633. keys.push({ frame: totalFrame, value: to });
  21634. animation.setKeys(keys);
  21635. if (easingFunction !== undefined) {
  21636. animation.setEasingFunction(easingFunction);
  21637. }
  21638. mesh.animations.push(animation);
  21639. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21640. };
  21641. // Methods
  21642. Animation.prototype.reset = function () {
  21643. this._offsetsCache = {};
  21644. this._highLimitsCache = {};
  21645. this.currentFrame = 0;
  21646. };
  21647. Animation.prototype.isStopped = function () {
  21648. return this._stopped;
  21649. };
  21650. Animation.prototype.getKeys = function () {
  21651. return this._keys;
  21652. };
  21653. Animation.prototype.getEasingFunction = function () {
  21654. return this._easingFunction;
  21655. };
  21656. Animation.prototype.setEasingFunction = function (easingFunction) {
  21657. this._easingFunction = easingFunction;
  21658. };
  21659. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21660. return startValue + (endValue - startValue) * gradient;
  21661. };
  21662. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21663. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21664. };
  21665. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21666. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21667. };
  21668. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21669. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21670. };
  21671. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21672. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21673. };
  21674. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21675. var startScale = new BABYLON.Vector3(0, 0, 0);
  21676. var startRotation = new BABYLON.Quaternion();
  21677. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21678. startValue.decompose(startScale, startRotation, startTranslation);
  21679. var endScale = new BABYLON.Vector3(0, 0, 0);
  21680. var endRotation = new BABYLON.Quaternion();
  21681. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21682. endValue.decompose(endScale, endRotation, endTranslation);
  21683. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21684. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21685. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21686. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21687. return result;
  21688. };
  21689. Animation.prototype.clone = function () {
  21690. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21691. clone.setKeys(this._keys);
  21692. return clone;
  21693. };
  21694. Animation.prototype.setKeys = function (values) {
  21695. this._keys = values.slice(0);
  21696. this._offsetsCache = {};
  21697. this._highLimitsCache = {};
  21698. };
  21699. Animation.prototype._getKeyValue = function (value) {
  21700. if (typeof value === "function") {
  21701. return value();
  21702. }
  21703. return value;
  21704. };
  21705. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21706. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21707. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21708. }
  21709. this.currentFrame = currentFrame;
  21710. // Try to get a hash to find the right key
  21711. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  21712. if (this._keys[startKey].frame >= currentFrame) {
  21713. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21714. startKey--;
  21715. }
  21716. }
  21717. for (var key = startKey; key < this._keys.length; key++) {
  21718. if (this._keys[key + 1].frame >= currentFrame) {
  21719. var startValue = this._getKeyValue(this._keys[key].value);
  21720. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21721. // gradient : percent of currentFrame between the frame inf and the frame sup
  21722. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21723. // check for easingFunction and correction of gradient
  21724. if (this._easingFunction != null) {
  21725. gradient = this._easingFunction.ease(gradient);
  21726. }
  21727. switch (this.dataType) {
  21728. // Float
  21729. case Animation.ANIMATIONTYPE_FLOAT:
  21730. switch (loopMode) {
  21731. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21732. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21733. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21734. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21735. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21736. }
  21737. break;
  21738. // Quaternion
  21739. case Animation.ANIMATIONTYPE_QUATERNION:
  21740. var quaternion = null;
  21741. switch (loopMode) {
  21742. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21743. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21744. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21745. break;
  21746. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21747. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21748. break;
  21749. }
  21750. return quaternion;
  21751. // Vector3
  21752. case Animation.ANIMATIONTYPE_VECTOR3:
  21753. switch (loopMode) {
  21754. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21755. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21756. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21757. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21758. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21759. }
  21760. // Vector2
  21761. case Animation.ANIMATIONTYPE_VECTOR2:
  21762. switch (loopMode) {
  21763. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21764. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21765. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21766. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21767. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21768. }
  21769. // Color3
  21770. case Animation.ANIMATIONTYPE_COLOR3:
  21771. switch (loopMode) {
  21772. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21773. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21774. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21775. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21776. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21777. }
  21778. // Matrix
  21779. case Animation.ANIMATIONTYPE_MATRIX:
  21780. switch (loopMode) {
  21781. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21782. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21783. if (this.allowMatricesInterpolation) {
  21784. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21785. }
  21786. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21787. return startValue;
  21788. }
  21789. default:
  21790. break;
  21791. }
  21792. break;
  21793. }
  21794. }
  21795. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21796. };
  21797. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21798. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21799. this._stopped = true;
  21800. return false;
  21801. }
  21802. var returnValue = true;
  21803. // Adding a start key at frame 0 if missing
  21804. if (this._keys[0].frame !== 0) {
  21805. var newKey = { frame: 0, value: this._keys[0].value };
  21806. this._keys.splice(0, 0, newKey);
  21807. }
  21808. // Check limits
  21809. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21810. from = this._keys[0].frame;
  21811. }
  21812. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21813. to = this._keys[this._keys.length - 1].frame;
  21814. }
  21815. // Compute ratio
  21816. var range = to - from;
  21817. var offsetValue;
  21818. // ratio represents the frame delta between from and to
  21819. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21820. var highLimitValue = 0;
  21821. if (ratio > range && !loop) {
  21822. returnValue = false;
  21823. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21824. }
  21825. else {
  21826. // Get max value if required
  21827. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21828. var keyOffset = to.toString() + from.toString();
  21829. if (!this._offsetsCache[keyOffset]) {
  21830. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21831. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21832. switch (this.dataType) {
  21833. // Float
  21834. case Animation.ANIMATIONTYPE_FLOAT:
  21835. this._offsetsCache[keyOffset] = toValue - fromValue;
  21836. break;
  21837. // Quaternion
  21838. case Animation.ANIMATIONTYPE_QUATERNION:
  21839. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21840. break;
  21841. // Vector3
  21842. case Animation.ANIMATIONTYPE_VECTOR3:
  21843. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21844. // Vector2
  21845. case Animation.ANIMATIONTYPE_VECTOR2:
  21846. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21847. // Color3
  21848. case Animation.ANIMATIONTYPE_COLOR3:
  21849. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21850. default:
  21851. break;
  21852. }
  21853. this._highLimitsCache[keyOffset] = toValue;
  21854. }
  21855. highLimitValue = this._highLimitsCache[keyOffset];
  21856. offsetValue = this._offsetsCache[keyOffset];
  21857. }
  21858. }
  21859. if (offsetValue === undefined) {
  21860. switch (this.dataType) {
  21861. // Float
  21862. case Animation.ANIMATIONTYPE_FLOAT:
  21863. offsetValue = 0;
  21864. break;
  21865. // Quaternion
  21866. case Animation.ANIMATIONTYPE_QUATERNION:
  21867. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21868. break;
  21869. // Vector3
  21870. case Animation.ANIMATIONTYPE_VECTOR3:
  21871. offsetValue = BABYLON.Vector3.Zero();
  21872. break;
  21873. // Vector2
  21874. case Animation.ANIMATIONTYPE_VECTOR2:
  21875. offsetValue = BABYLON.Vector2.Zero();
  21876. break;
  21877. // Color3
  21878. case Animation.ANIMATIONTYPE_COLOR3:
  21879. offsetValue = BABYLON.Color3.Black();
  21880. }
  21881. }
  21882. // Compute value
  21883. var repeatCount = (ratio / range) >> 0;
  21884. var currentFrame = returnValue ? from + ratio % range : to;
  21885. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21886. // Set value
  21887. if (this.targetPropertyPath.length > 1) {
  21888. var property = this._target[this.targetPropertyPath[0]];
  21889. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21890. property = property[this.targetPropertyPath[index]];
  21891. }
  21892. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21893. }
  21894. else {
  21895. this._target[this.targetPropertyPath[0]] = currentValue;
  21896. }
  21897. if (this._target.markAsDirty) {
  21898. this._target.markAsDirty(this.targetProperty);
  21899. }
  21900. if (!returnValue) {
  21901. this._stopped = true;
  21902. }
  21903. return returnValue;
  21904. };
  21905. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21906. get: function () {
  21907. return Animation._ANIMATIONTYPE_FLOAT;
  21908. },
  21909. enumerable: true,
  21910. configurable: true
  21911. });
  21912. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21913. get: function () {
  21914. return Animation._ANIMATIONTYPE_VECTOR3;
  21915. },
  21916. enumerable: true,
  21917. configurable: true
  21918. });
  21919. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21920. get: function () {
  21921. return Animation._ANIMATIONTYPE_VECTOR2;
  21922. },
  21923. enumerable: true,
  21924. configurable: true
  21925. });
  21926. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21927. get: function () {
  21928. return Animation._ANIMATIONTYPE_QUATERNION;
  21929. },
  21930. enumerable: true,
  21931. configurable: true
  21932. });
  21933. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21934. get: function () {
  21935. return Animation._ANIMATIONTYPE_MATRIX;
  21936. },
  21937. enumerable: true,
  21938. configurable: true
  21939. });
  21940. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21941. get: function () {
  21942. return Animation._ANIMATIONTYPE_COLOR3;
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21948. get: function () {
  21949. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21955. get: function () {
  21956. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21957. },
  21958. enumerable: true,
  21959. configurable: true
  21960. });
  21961. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21962. get: function () {
  21963. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21964. },
  21965. enumerable: true,
  21966. configurable: true
  21967. });
  21968. // Statics
  21969. Animation._ANIMATIONTYPE_FLOAT = 0;
  21970. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21971. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21972. Animation._ANIMATIONTYPE_MATRIX = 3;
  21973. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21974. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21975. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21976. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21977. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21978. return Animation;
  21979. })();
  21980. BABYLON.Animation = Animation;
  21981. })(BABYLON || (BABYLON = {}));
  21982. var BABYLON;
  21983. (function (BABYLON) {
  21984. var Animatable = (function () {
  21985. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21986. if (fromFrame === void 0) { fromFrame = 0; }
  21987. if (toFrame === void 0) { toFrame = 100; }
  21988. if (loopAnimation === void 0) { loopAnimation = false; }
  21989. if (speedRatio === void 0) { speedRatio = 1.0; }
  21990. this.target = target;
  21991. this.fromFrame = fromFrame;
  21992. this.toFrame = toFrame;
  21993. this.loopAnimation = loopAnimation;
  21994. this.speedRatio = speedRatio;
  21995. this.onAnimationEnd = onAnimationEnd;
  21996. this._animations = new Array();
  21997. this._paused = false;
  21998. this.animationStarted = false;
  21999. if (animations) {
  22000. this.appendAnimations(target, animations);
  22001. }
  22002. this._scene = scene;
  22003. scene._activeAnimatables.push(this);
  22004. }
  22005. // Methods
  22006. Animatable.prototype.appendAnimations = function (target, animations) {
  22007. for (var index = 0; index < animations.length; index++) {
  22008. var animation = animations[index];
  22009. animation._target = target;
  22010. this._animations.push(animation);
  22011. }
  22012. };
  22013. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22014. var animations = this._animations;
  22015. for (var index = 0; index < animations.length; index++) {
  22016. if (animations[index].targetProperty === property) {
  22017. return animations[index];
  22018. }
  22019. }
  22020. return null;
  22021. };
  22022. Animatable.prototype.reset = function () {
  22023. var animations = this._animations;
  22024. for (var index = 0; index < animations.length; index++) {
  22025. animations[index].reset();
  22026. }
  22027. this._localDelayOffset = null;
  22028. this._pausedDelay = null;
  22029. };
  22030. Animatable.prototype.pause = function () {
  22031. if (this._paused) {
  22032. return;
  22033. }
  22034. this._paused = true;
  22035. };
  22036. Animatable.prototype.restart = function () {
  22037. this._paused = false;
  22038. };
  22039. Animatable.prototype.stop = function () {
  22040. var index = this._scene._activeAnimatables.indexOf(this);
  22041. if (index > -1) {
  22042. this._scene._activeAnimatables.splice(index, 1);
  22043. }
  22044. if (this.onAnimationEnd) {
  22045. this.onAnimationEnd();
  22046. }
  22047. };
  22048. Animatable.prototype._animate = function (delay) {
  22049. if (this._paused) {
  22050. if (!this._pausedDelay) {
  22051. this._pausedDelay = delay;
  22052. }
  22053. return true;
  22054. }
  22055. if (!this._localDelayOffset) {
  22056. this._localDelayOffset = delay;
  22057. }
  22058. else if (this._pausedDelay) {
  22059. this._localDelayOffset += delay - this._pausedDelay;
  22060. this._pausedDelay = null;
  22061. }
  22062. // Animating
  22063. var running = false;
  22064. var animations = this._animations;
  22065. for (var index = 0; index < animations.length; index++) {
  22066. var animation = animations[index];
  22067. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22068. running = running || isRunning;
  22069. }
  22070. if (!running) {
  22071. // Remove from active animatables
  22072. index = this._scene._activeAnimatables.indexOf(this);
  22073. this._scene._activeAnimatables.splice(index, 1);
  22074. }
  22075. if (!running && this.onAnimationEnd) {
  22076. this.onAnimationEnd();
  22077. }
  22078. return running;
  22079. };
  22080. return Animatable;
  22081. })();
  22082. BABYLON.Animatable = Animatable;
  22083. })(BABYLON || (BABYLON = {}));
  22084. var BABYLON;
  22085. (function (BABYLON) {
  22086. var EasingFunction = (function () {
  22087. function EasingFunction() {
  22088. // Properties
  22089. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22090. }
  22091. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22092. get: function () {
  22093. return EasingFunction._EASINGMODE_EASEIN;
  22094. },
  22095. enumerable: true,
  22096. configurable: true
  22097. });
  22098. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22099. get: function () {
  22100. return EasingFunction._EASINGMODE_EASEOUT;
  22101. },
  22102. enumerable: true,
  22103. configurable: true
  22104. });
  22105. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22106. get: function () {
  22107. return EasingFunction._EASINGMODE_EASEINOUT;
  22108. },
  22109. enumerable: true,
  22110. configurable: true
  22111. });
  22112. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22113. var n = Math.min(Math.max(easingMode, 0), 2);
  22114. this._easingMode = n;
  22115. };
  22116. EasingFunction.prototype.getEasingMode = function () {
  22117. return this._easingMode;
  22118. };
  22119. EasingFunction.prototype.easeInCore = function (gradient) {
  22120. throw new Error('You must implement this method');
  22121. };
  22122. EasingFunction.prototype.ease = function (gradient) {
  22123. switch (this._easingMode) {
  22124. case EasingFunction.EASINGMODE_EASEIN:
  22125. return this.easeInCore(gradient);
  22126. case EasingFunction.EASINGMODE_EASEOUT:
  22127. return (1 - this.easeInCore(1 - gradient));
  22128. }
  22129. if (gradient >= 0.5) {
  22130. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22131. }
  22132. return (this.easeInCore(gradient * 2) * 0.5);
  22133. };
  22134. //Statics
  22135. EasingFunction._EASINGMODE_EASEIN = 0;
  22136. EasingFunction._EASINGMODE_EASEOUT = 1;
  22137. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22138. return EasingFunction;
  22139. })();
  22140. BABYLON.EasingFunction = EasingFunction;
  22141. var CircleEase = (function (_super) {
  22142. __extends(CircleEase, _super);
  22143. function CircleEase() {
  22144. _super.apply(this, arguments);
  22145. }
  22146. CircleEase.prototype.easeInCore = function (gradient) {
  22147. gradient = Math.max(0, Math.min(1, gradient));
  22148. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22149. };
  22150. return CircleEase;
  22151. })(EasingFunction);
  22152. BABYLON.CircleEase = CircleEase;
  22153. var BackEase = (function (_super) {
  22154. __extends(BackEase, _super);
  22155. function BackEase(amplitude) {
  22156. if (amplitude === void 0) { amplitude = 1; }
  22157. _super.call(this);
  22158. this.amplitude = amplitude;
  22159. }
  22160. BackEase.prototype.easeInCore = function (gradient) {
  22161. var num = Math.max(0, this.amplitude);
  22162. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22163. };
  22164. return BackEase;
  22165. })(EasingFunction);
  22166. BABYLON.BackEase = BackEase;
  22167. var BounceEase = (function (_super) {
  22168. __extends(BounceEase, _super);
  22169. function BounceEase(bounces, bounciness) {
  22170. if (bounces === void 0) { bounces = 3; }
  22171. if (bounciness === void 0) { bounciness = 2; }
  22172. _super.call(this);
  22173. this.bounces = bounces;
  22174. this.bounciness = bounciness;
  22175. }
  22176. BounceEase.prototype.easeInCore = function (gradient) {
  22177. var y = Math.max(0.0, this.bounces);
  22178. var bounciness = this.bounciness;
  22179. if (bounciness <= 1.0) {
  22180. bounciness = 1.001;
  22181. }
  22182. var num9 = Math.pow(bounciness, y);
  22183. var num5 = 1.0 - bounciness;
  22184. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22185. var num15 = gradient * num4;
  22186. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22187. var num3 = Math.floor(num65);
  22188. var num13 = num3 + 1.0;
  22189. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22190. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22191. var num7 = (num8 + num12) * 0.5;
  22192. var num6 = gradient - num7;
  22193. var num2 = num7 - num8;
  22194. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22195. };
  22196. return BounceEase;
  22197. })(EasingFunction);
  22198. BABYLON.BounceEase = BounceEase;
  22199. var CubicEase = (function (_super) {
  22200. __extends(CubicEase, _super);
  22201. function CubicEase() {
  22202. _super.apply(this, arguments);
  22203. }
  22204. CubicEase.prototype.easeInCore = function (gradient) {
  22205. return (gradient * gradient * gradient);
  22206. };
  22207. return CubicEase;
  22208. })(EasingFunction);
  22209. BABYLON.CubicEase = CubicEase;
  22210. var ElasticEase = (function (_super) {
  22211. __extends(ElasticEase, _super);
  22212. function ElasticEase(oscillations, springiness) {
  22213. if (oscillations === void 0) { oscillations = 3; }
  22214. if (springiness === void 0) { springiness = 3; }
  22215. _super.call(this);
  22216. this.oscillations = oscillations;
  22217. this.springiness = springiness;
  22218. }
  22219. ElasticEase.prototype.easeInCore = function (gradient) {
  22220. var num2;
  22221. var num3 = Math.max(0.0, this.oscillations);
  22222. var num = Math.max(0.0, this.springiness);
  22223. if (num == 0) {
  22224. num2 = gradient;
  22225. }
  22226. else {
  22227. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22228. }
  22229. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22230. };
  22231. return ElasticEase;
  22232. })(EasingFunction);
  22233. BABYLON.ElasticEase = ElasticEase;
  22234. var ExponentialEase = (function (_super) {
  22235. __extends(ExponentialEase, _super);
  22236. function ExponentialEase(exponent) {
  22237. if (exponent === void 0) { exponent = 2; }
  22238. _super.call(this);
  22239. this.exponent = exponent;
  22240. }
  22241. ExponentialEase.prototype.easeInCore = function (gradient) {
  22242. if (this.exponent <= 0) {
  22243. return gradient;
  22244. }
  22245. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22246. };
  22247. return ExponentialEase;
  22248. })(EasingFunction);
  22249. BABYLON.ExponentialEase = ExponentialEase;
  22250. var PowerEase = (function (_super) {
  22251. __extends(PowerEase, _super);
  22252. function PowerEase(power) {
  22253. if (power === void 0) { power = 2; }
  22254. _super.call(this);
  22255. this.power = power;
  22256. }
  22257. PowerEase.prototype.easeInCore = function (gradient) {
  22258. var y = Math.max(0.0, this.power);
  22259. return Math.pow(gradient, y);
  22260. };
  22261. return PowerEase;
  22262. })(EasingFunction);
  22263. BABYLON.PowerEase = PowerEase;
  22264. var QuadraticEase = (function (_super) {
  22265. __extends(QuadraticEase, _super);
  22266. function QuadraticEase() {
  22267. _super.apply(this, arguments);
  22268. }
  22269. QuadraticEase.prototype.easeInCore = function (gradient) {
  22270. return (gradient * gradient);
  22271. };
  22272. return QuadraticEase;
  22273. })(EasingFunction);
  22274. BABYLON.QuadraticEase = QuadraticEase;
  22275. var QuarticEase = (function (_super) {
  22276. __extends(QuarticEase, _super);
  22277. function QuarticEase() {
  22278. _super.apply(this, arguments);
  22279. }
  22280. QuarticEase.prototype.easeInCore = function (gradient) {
  22281. return (gradient * gradient * gradient * gradient);
  22282. };
  22283. return QuarticEase;
  22284. })(EasingFunction);
  22285. BABYLON.QuarticEase = QuarticEase;
  22286. var QuinticEase = (function (_super) {
  22287. __extends(QuinticEase, _super);
  22288. function QuinticEase() {
  22289. _super.apply(this, arguments);
  22290. }
  22291. QuinticEase.prototype.easeInCore = function (gradient) {
  22292. return (gradient * gradient * gradient * gradient * gradient);
  22293. };
  22294. return QuinticEase;
  22295. })(EasingFunction);
  22296. BABYLON.QuinticEase = QuinticEase;
  22297. var SineEase = (function (_super) {
  22298. __extends(SineEase, _super);
  22299. function SineEase() {
  22300. _super.apply(this, arguments);
  22301. }
  22302. SineEase.prototype.easeInCore = function (gradient) {
  22303. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22304. };
  22305. return SineEase;
  22306. })(EasingFunction);
  22307. BABYLON.SineEase = SineEase;
  22308. var BezierCurveEase = (function (_super) {
  22309. __extends(BezierCurveEase, _super);
  22310. function BezierCurveEase(x1, y1, x2, y2) {
  22311. if (x1 === void 0) { x1 = 0; }
  22312. if (y1 === void 0) { y1 = 0; }
  22313. if (x2 === void 0) { x2 = 1; }
  22314. if (y2 === void 0) { y2 = 1; }
  22315. _super.call(this);
  22316. this.x1 = x1;
  22317. this.y1 = y1;
  22318. this.x2 = x2;
  22319. this.y2 = y2;
  22320. }
  22321. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22322. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22323. };
  22324. return BezierCurveEase;
  22325. })(EasingFunction);
  22326. BABYLON.BezierCurveEase = BezierCurveEase;
  22327. })(BABYLON || (BABYLON = {}));
  22328. var BABYLON;
  22329. (function (BABYLON) {
  22330. var Octree = (function () {
  22331. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22332. if (maxDepth === void 0) { maxDepth = 2; }
  22333. this.maxDepth = maxDepth;
  22334. this.dynamicContent = new Array();
  22335. this._maxBlockCapacity = maxBlockCapacity || 64;
  22336. this._selectionContent = new BABYLON.SmartArray(1024);
  22337. this._creationFunc = creationFunc;
  22338. }
  22339. // Methods
  22340. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22341. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22342. };
  22343. Octree.prototype.addMesh = function (entry) {
  22344. for (var index = 0; index < this.blocks.length; index++) {
  22345. var block = this.blocks[index];
  22346. block.addEntry(entry);
  22347. }
  22348. };
  22349. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22350. this._selectionContent.reset();
  22351. for (var index = 0; index < this.blocks.length; index++) {
  22352. var block = this.blocks[index];
  22353. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22354. }
  22355. if (allowDuplicate) {
  22356. this._selectionContent.concat(this.dynamicContent);
  22357. }
  22358. else {
  22359. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22360. }
  22361. return this._selectionContent;
  22362. };
  22363. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22364. this._selectionContent.reset();
  22365. for (var index = 0; index < this.blocks.length; index++) {
  22366. var block = this.blocks[index];
  22367. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22368. }
  22369. if (allowDuplicate) {
  22370. this._selectionContent.concat(this.dynamicContent);
  22371. }
  22372. else {
  22373. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22374. }
  22375. return this._selectionContent;
  22376. };
  22377. Octree.prototype.intersectsRay = function (ray) {
  22378. this._selectionContent.reset();
  22379. for (var index = 0; index < this.blocks.length; index++) {
  22380. var block = this.blocks[index];
  22381. block.intersectsRay(ray, this._selectionContent);
  22382. }
  22383. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22384. return this._selectionContent;
  22385. };
  22386. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22387. target.blocks = new Array();
  22388. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22389. // Segmenting space
  22390. for (var x = 0; x < 2; x++) {
  22391. for (var y = 0; y < 2; y++) {
  22392. for (var z = 0; z < 2; z++) {
  22393. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22394. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22395. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22396. block.addEntries(entries);
  22397. target.blocks.push(block);
  22398. }
  22399. }
  22400. }
  22401. };
  22402. Octree.CreationFuncForMeshes = function (entry, block) {
  22403. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22404. block.entries.push(entry);
  22405. }
  22406. };
  22407. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22408. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22409. block.entries.push(entry);
  22410. }
  22411. };
  22412. return Octree;
  22413. })();
  22414. BABYLON.Octree = Octree;
  22415. })(BABYLON || (BABYLON = {}));
  22416. var BABYLON;
  22417. (function (BABYLON) {
  22418. var OctreeBlock = (function () {
  22419. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22420. this.entries = new Array();
  22421. this._boundingVectors = new Array();
  22422. this._capacity = capacity;
  22423. this._depth = depth;
  22424. this._maxDepth = maxDepth;
  22425. this._creationFunc = creationFunc;
  22426. this._minPoint = minPoint;
  22427. this._maxPoint = maxPoint;
  22428. this._boundingVectors.push(minPoint.clone());
  22429. this._boundingVectors.push(maxPoint.clone());
  22430. this._boundingVectors.push(minPoint.clone());
  22431. this._boundingVectors[2].x = maxPoint.x;
  22432. this._boundingVectors.push(minPoint.clone());
  22433. this._boundingVectors[3].y = maxPoint.y;
  22434. this._boundingVectors.push(minPoint.clone());
  22435. this._boundingVectors[4].z = maxPoint.z;
  22436. this._boundingVectors.push(maxPoint.clone());
  22437. this._boundingVectors[5].z = minPoint.z;
  22438. this._boundingVectors.push(maxPoint.clone());
  22439. this._boundingVectors[6].x = minPoint.x;
  22440. this._boundingVectors.push(maxPoint.clone());
  22441. this._boundingVectors[7].y = minPoint.y;
  22442. }
  22443. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22444. // Property
  22445. get: function () {
  22446. return this._capacity;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22452. get: function () {
  22453. return this._minPoint;
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22459. get: function () {
  22460. return this._maxPoint;
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. // Methods
  22466. OctreeBlock.prototype.addEntry = function (entry) {
  22467. if (this.blocks) {
  22468. for (var index = 0; index < this.blocks.length; index++) {
  22469. var block = this.blocks[index];
  22470. block.addEntry(entry);
  22471. }
  22472. return;
  22473. }
  22474. this._creationFunc(entry, this);
  22475. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22476. this.createInnerBlocks();
  22477. }
  22478. };
  22479. OctreeBlock.prototype.addEntries = function (entries) {
  22480. for (var index = 0; index < entries.length; index++) {
  22481. var mesh = entries[index];
  22482. this.addEntry(mesh);
  22483. }
  22484. };
  22485. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22486. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22487. if (this.blocks) {
  22488. for (var index = 0; index < this.blocks.length; index++) {
  22489. var block = this.blocks[index];
  22490. block.select(frustumPlanes, selection, allowDuplicate);
  22491. }
  22492. return;
  22493. }
  22494. if (allowDuplicate) {
  22495. selection.concat(this.entries);
  22496. }
  22497. else {
  22498. selection.concatWithNoDuplicate(this.entries);
  22499. }
  22500. }
  22501. };
  22502. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22503. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22504. if (this.blocks) {
  22505. for (var index = 0; index < this.blocks.length; index++) {
  22506. var block = this.blocks[index];
  22507. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22508. }
  22509. return;
  22510. }
  22511. if (allowDuplicate) {
  22512. selection.concat(this.entries);
  22513. }
  22514. else {
  22515. selection.concatWithNoDuplicate(this.entries);
  22516. }
  22517. }
  22518. };
  22519. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22520. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22521. if (this.blocks) {
  22522. for (var index = 0; index < this.blocks.length; index++) {
  22523. var block = this.blocks[index];
  22524. block.intersectsRay(ray, selection);
  22525. }
  22526. return;
  22527. }
  22528. selection.concatWithNoDuplicate(this.entries);
  22529. }
  22530. };
  22531. OctreeBlock.prototype.createInnerBlocks = function () {
  22532. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22533. };
  22534. return OctreeBlock;
  22535. })();
  22536. BABYLON.OctreeBlock = OctreeBlock;
  22537. })(BABYLON || (BABYLON = {}));
  22538. var BABYLON;
  22539. (function (BABYLON) {
  22540. var Bone = (function (_super) {
  22541. __extends(Bone, _super);
  22542. function Bone(name, skeleton, parentBone, matrix) {
  22543. _super.call(this, name, skeleton.getScene());
  22544. this.name = name;
  22545. this.children = new Array();
  22546. this.animations = new Array();
  22547. this._worldTransform = new BABYLON.Matrix();
  22548. this._absoluteTransform = new BABYLON.Matrix();
  22549. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22550. this._skeleton = skeleton;
  22551. this._matrix = matrix;
  22552. this._baseMatrix = matrix;
  22553. skeleton.bones.push(this);
  22554. if (parentBone) {
  22555. this._parent = parentBone;
  22556. parentBone.children.push(this);
  22557. }
  22558. else {
  22559. this._parent = null;
  22560. }
  22561. this._updateDifferenceMatrix();
  22562. }
  22563. // Members
  22564. Bone.prototype.getParent = function () {
  22565. return this._parent;
  22566. };
  22567. Bone.prototype.getLocalMatrix = function () {
  22568. return this._matrix;
  22569. };
  22570. Bone.prototype.getBaseMatrix = function () {
  22571. return this._baseMatrix;
  22572. };
  22573. Bone.prototype.getWorldMatrix = function () {
  22574. return this._worldTransform;
  22575. };
  22576. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22577. return this._invertedAbsoluteTransform;
  22578. };
  22579. Bone.prototype.getAbsoluteMatrix = function () {
  22580. var matrix = this._matrix.clone();
  22581. var parent = this._parent;
  22582. while (parent) {
  22583. matrix = matrix.multiply(parent.getLocalMatrix());
  22584. parent = parent.getParent();
  22585. }
  22586. return matrix;
  22587. };
  22588. // Methods
  22589. Bone.prototype.updateMatrix = function (matrix) {
  22590. this._matrix = matrix;
  22591. this._skeleton._markAsDirty();
  22592. this._updateDifferenceMatrix();
  22593. };
  22594. Bone.prototype._updateDifferenceMatrix = function () {
  22595. if (this._parent) {
  22596. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22597. }
  22598. else {
  22599. this._absoluteTransform.copyFrom(this._matrix);
  22600. }
  22601. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22602. for (var index = 0; index < this.children.length; index++) {
  22603. this.children[index]._updateDifferenceMatrix();
  22604. }
  22605. };
  22606. Bone.prototype.markAsDirty = function () {
  22607. this._currentRenderId++;
  22608. this._skeleton._markAsDirty();
  22609. };
  22610. return Bone;
  22611. })(BABYLON.Node);
  22612. BABYLON.Bone = Bone;
  22613. })(BABYLON || (BABYLON = {}));
  22614. var BABYLON;
  22615. (function (BABYLON) {
  22616. var Skeleton = (function () {
  22617. function Skeleton(name, id, scene) {
  22618. this.name = name;
  22619. this.id = id;
  22620. this.bones = new Array();
  22621. this._isDirty = true;
  22622. this._identity = BABYLON.Matrix.Identity();
  22623. this.bones = [];
  22624. this._scene = scene;
  22625. scene.skeletons.push(this);
  22626. this.prepare();
  22627. //make sure it will recalculate the matrix next time prepare is called.
  22628. this._isDirty = true;
  22629. }
  22630. // Members
  22631. Skeleton.prototype.getTransformMatrices = function () {
  22632. return this._transformMatrices;
  22633. };
  22634. Skeleton.prototype.getScene = function () {
  22635. return this._scene;
  22636. };
  22637. // Methods
  22638. Skeleton.prototype._markAsDirty = function () {
  22639. this._isDirty = true;
  22640. };
  22641. Skeleton.prototype.prepare = function () {
  22642. if (!this._isDirty) {
  22643. return;
  22644. }
  22645. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22646. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22647. }
  22648. for (var index = 0; index < this.bones.length; index++) {
  22649. var bone = this.bones[index];
  22650. var parentBone = bone.getParent();
  22651. if (parentBone) {
  22652. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22653. }
  22654. else {
  22655. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22656. }
  22657. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22658. }
  22659. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22660. this._isDirty = false;
  22661. this._scene._activeBones += this.bones.length;
  22662. };
  22663. Skeleton.prototype.getAnimatables = function () {
  22664. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22665. this._animatables = [];
  22666. for (var index = 0; index < this.bones.length; index++) {
  22667. this._animatables.push(this.bones[index]);
  22668. }
  22669. }
  22670. return this._animatables;
  22671. };
  22672. Skeleton.prototype.clone = function (name, id) {
  22673. var result = new Skeleton(name, id || name, this._scene);
  22674. for (var index = 0; index < this.bones.length; index++) {
  22675. var source = this.bones[index];
  22676. var parentBone = null;
  22677. if (source.getParent()) {
  22678. var parentIndex = this.bones.indexOf(source.getParent());
  22679. parentBone = result.bones[parentIndex];
  22680. }
  22681. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22682. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22683. }
  22684. return result;
  22685. };
  22686. return Skeleton;
  22687. })();
  22688. BABYLON.Skeleton = Skeleton;
  22689. })(BABYLON || (BABYLON = {}));
  22690. var BABYLON;
  22691. (function (BABYLON) {
  22692. var PostProcess = (function () {
  22693. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22695. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22696. this.name = name;
  22697. this.width = -1;
  22698. this.height = -1;
  22699. this._reusable = false;
  22700. this._textures = new BABYLON.SmartArray(2);
  22701. this._currentRenderTextureInd = 0;
  22702. if (camera != null) {
  22703. this._camera = camera;
  22704. this._scene = camera.getScene();
  22705. camera.attachPostProcess(this);
  22706. this._engine = this._scene.getEngine();
  22707. }
  22708. else {
  22709. this._engine = engine;
  22710. }
  22711. this._renderRatio = ratio;
  22712. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22713. this._reusable = reusable || false;
  22714. this._textureType = textureType;
  22715. samplers = samplers || [];
  22716. samplers.push("textureSampler");
  22717. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22718. }
  22719. PostProcess.prototype.isReusable = function () {
  22720. return this._reusable;
  22721. };
  22722. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22723. camera = camera || this._camera;
  22724. var scene = camera.getScene();
  22725. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22726. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22727. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22728. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22729. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22730. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22731. if (this._textures.length > 0) {
  22732. for (var i = 0; i < this._textures.length; i++) {
  22733. this._engine._releaseTexture(this._textures.data[i]);
  22734. }
  22735. this._textures.reset();
  22736. }
  22737. this.width = desiredWidth;
  22738. this.height = desiredHeight;
  22739. 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, type: this._textureType }));
  22740. if (this._reusable) {
  22741. 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, type: this._textureType }));
  22742. }
  22743. if (this.onSizeChanged) {
  22744. this.onSizeChanged();
  22745. }
  22746. }
  22747. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22748. if (this.onActivate) {
  22749. this.onActivate(camera);
  22750. }
  22751. // Clear
  22752. if (this.clearColor) {
  22753. this._engine.clear(this.clearColor, true, true);
  22754. }
  22755. else {
  22756. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22757. }
  22758. if (this._reusable) {
  22759. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22760. }
  22761. };
  22762. PostProcess.prototype.apply = function () {
  22763. // Check
  22764. if (!this._effect.isReady())
  22765. return null;
  22766. // States
  22767. this._engine.enableEffect(this._effect);
  22768. this._engine.setState(false);
  22769. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22770. this._engine.setDepthBuffer(false);
  22771. this._engine.setDepthWrite(false);
  22772. // Texture
  22773. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22774. // Parameters
  22775. if (this.onApply) {
  22776. this.onApply(this._effect);
  22777. }
  22778. return this._effect;
  22779. };
  22780. PostProcess.prototype.dispose = function (camera) {
  22781. camera = camera || this._camera;
  22782. if (this._textures.length > 0) {
  22783. for (var i = 0; i < this._textures.length; i++) {
  22784. this._engine._releaseTexture(this._textures.data[i]);
  22785. }
  22786. this._textures.reset();
  22787. }
  22788. if (!camera) {
  22789. return;
  22790. }
  22791. camera.detachPostProcess(this);
  22792. var index = camera._postProcesses.indexOf(this);
  22793. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22794. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22795. }
  22796. };
  22797. return PostProcess;
  22798. })();
  22799. BABYLON.PostProcess = PostProcess;
  22800. })(BABYLON || (BABYLON = {}));
  22801. var BABYLON;
  22802. (function (BABYLON) {
  22803. var PostProcessManager = (function () {
  22804. function PostProcessManager(scene) {
  22805. this._vertexDeclaration = [2];
  22806. this._vertexStrideSize = 2 * 4;
  22807. this._scene = scene;
  22808. }
  22809. PostProcessManager.prototype._prepareBuffers = function () {
  22810. if (this._vertexBuffer) {
  22811. return;
  22812. }
  22813. // VBO
  22814. var vertices = [];
  22815. vertices.push(1, 1);
  22816. vertices.push(-1, 1);
  22817. vertices.push(-1, -1);
  22818. vertices.push(1, -1);
  22819. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22820. // Indices
  22821. var indices = [];
  22822. indices.push(0);
  22823. indices.push(1);
  22824. indices.push(2);
  22825. indices.push(0);
  22826. indices.push(2);
  22827. indices.push(3);
  22828. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22829. };
  22830. // Methods
  22831. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22832. var postProcesses = this._scene.activeCamera._postProcesses;
  22833. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22834. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22835. return false;
  22836. }
  22837. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22838. return true;
  22839. };
  22840. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22841. var engine = this._scene.getEngine();
  22842. for (var index = 0; index < postProcesses.length; index++) {
  22843. if (index < postProcesses.length - 1) {
  22844. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22845. }
  22846. else {
  22847. if (targetTexture) {
  22848. engine.bindFramebuffer(targetTexture);
  22849. }
  22850. else {
  22851. engine.restoreDefaultFramebuffer();
  22852. }
  22853. }
  22854. var pp = postProcesses[index];
  22855. var effect = pp.apply();
  22856. if (effect) {
  22857. if (pp.onBeforeRender) {
  22858. pp.onBeforeRender(effect);
  22859. }
  22860. // VBOs
  22861. this._prepareBuffers();
  22862. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22863. // Draw order
  22864. engine.draw(true, 0, 6);
  22865. if (pp.onAfterRender) {
  22866. pp.onAfterRender(effect);
  22867. }
  22868. }
  22869. }
  22870. // Restore depth buffer
  22871. engine.setDepthBuffer(true);
  22872. engine.setDepthWrite(true);
  22873. };
  22874. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22875. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22876. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22877. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22878. return;
  22879. }
  22880. var engine = this._scene.getEngine();
  22881. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22882. if (index < postProcessesTakenIndices.length - 1) {
  22883. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22884. }
  22885. else {
  22886. if (targetTexture) {
  22887. engine.bindFramebuffer(targetTexture);
  22888. }
  22889. else {
  22890. engine.restoreDefaultFramebuffer();
  22891. }
  22892. }
  22893. if (doNotPresent) {
  22894. break;
  22895. }
  22896. var pp = postProcesses[postProcessesTakenIndices[index]];
  22897. var effect = pp.apply();
  22898. if (effect) {
  22899. if (pp.onBeforeRender) {
  22900. pp.onBeforeRender(effect);
  22901. }
  22902. // VBOs
  22903. this._prepareBuffers();
  22904. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22905. // Draw order
  22906. engine.draw(true, 0, 6);
  22907. if (pp.onAfterRender) {
  22908. pp.onAfterRender(effect);
  22909. }
  22910. }
  22911. }
  22912. // Restore depth buffer
  22913. engine.setDepthBuffer(true);
  22914. engine.setDepthWrite(true);
  22915. };
  22916. PostProcessManager.prototype.dispose = function () {
  22917. if (this._vertexBuffer) {
  22918. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22919. this._vertexBuffer = null;
  22920. }
  22921. if (this._indexBuffer) {
  22922. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22923. this._indexBuffer = null;
  22924. }
  22925. };
  22926. return PostProcessManager;
  22927. })();
  22928. BABYLON.PostProcessManager = PostProcessManager;
  22929. })(BABYLON || (BABYLON = {}));
  22930. var BABYLON;
  22931. (function (BABYLON) {
  22932. var PassPostProcess = (function (_super) {
  22933. __extends(PassPostProcess, _super);
  22934. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22935. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22936. }
  22937. return PassPostProcess;
  22938. })(BABYLON.PostProcess);
  22939. BABYLON.PassPostProcess = PassPostProcess;
  22940. })(BABYLON || (BABYLON = {}));
  22941. var BABYLON;
  22942. (function (BABYLON) {
  22943. var BlurPostProcess = (function (_super) {
  22944. __extends(BlurPostProcess, _super);
  22945. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22946. var _this = this;
  22947. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22948. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22949. this.direction = direction;
  22950. this.blurWidth = blurWidth;
  22951. this.onApply = function (effect) {
  22952. effect.setFloat2("screenSize", _this.width, _this.height);
  22953. effect.setVector2("direction", _this.direction);
  22954. effect.setFloat("blurWidth", _this.blurWidth);
  22955. };
  22956. }
  22957. return BlurPostProcess;
  22958. })(BABYLON.PostProcess);
  22959. BABYLON.BlurPostProcess = BlurPostProcess;
  22960. })(BABYLON || (BABYLON = {}));
  22961. var BABYLON;
  22962. (function (BABYLON) {
  22963. var RefractionPostProcess = (function (_super) {
  22964. __extends(RefractionPostProcess, _super);
  22965. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22966. var _this = this;
  22967. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22968. this.color = color;
  22969. this.depth = depth;
  22970. this.colorLevel = colorLevel;
  22971. this.onActivate = function (cam) {
  22972. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22973. };
  22974. this.onApply = function (effect) {
  22975. effect.setColor3("baseColor", _this.color);
  22976. effect.setFloat("depth", _this.depth);
  22977. effect.setFloat("colorLevel", _this.colorLevel);
  22978. effect.setTexture("refractionSampler", _this._refRexture);
  22979. };
  22980. }
  22981. // Methods
  22982. RefractionPostProcess.prototype.dispose = function (camera) {
  22983. if (this._refRexture) {
  22984. this._refRexture.dispose();
  22985. }
  22986. _super.prototype.dispose.call(this, camera);
  22987. };
  22988. return RefractionPostProcess;
  22989. })(BABYLON.PostProcess);
  22990. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22991. })(BABYLON || (BABYLON = {}));
  22992. var BABYLON;
  22993. (function (BABYLON) {
  22994. var BlackAndWhitePostProcess = (function (_super) {
  22995. __extends(BlackAndWhitePostProcess, _super);
  22996. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22997. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22998. }
  22999. return BlackAndWhitePostProcess;
  23000. })(BABYLON.PostProcess);
  23001. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23002. })(BABYLON || (BABYLON = {}));
  23003. var BABYLON;
  23004. (function (BABYLON) {
  23005. var ConvolutionPostProcess = (function (_super) {
  23006. __extends(ConvolutionPostProcess, _super);
  23007. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23008. var _this = this;
  23009. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23010. this.kernel = kernel;
  23011. this.onApply = function (effect) {
  23012. effect.setFloat2("screenSize", _this.width, _this.height);
  23013. effect.setArray("kernel", _this.kernel);
  23014. };
  23015. }
  23016. // Statics
  23017. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23018. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23019. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23020. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23021. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23022. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23023. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23024. return ConvolutionPostProcess;
  23025. })(BABYLON.PostProcess);
  23026. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23027. })(BABYLON || (BABYLON = {}));
  23028. var BABYLON;
  23029. (function (BABYLON) {
  23030. var FilterPostProcess = (function (_super) {
  23031. __extends(FilterPostProcess, _super);
  23032. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23033. var _this = this;
  23034. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23035. this.kernelMatrix = kernelMatrix;
  23036. this.onApply = function (effect) {
  23037. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23038. };
  23039. }
  23040. return FilterPostProcess;
  23041. })(BABYLON.PostProcess);
  23042. BABYLON.FilterPostProcess = FilterPostProcess;
  23043. })(BABYLON || (BABYLON = {}));
  23044. var BABYLON;
  23045. (function (BABYLON) {
  23046. var FxaaPostProcess = (function (_super) {
  23047. __extends(FxaaPostProcess, _super);
  23048. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23049. var _this = this;
  23050. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23051. this.onSizeChanged = function () {
  23052. _this.texelWidth = 1.0 / _this.width;
  23053. _this.texelHeight = 1.0 / _this.height;
  23054. };
  23055. this.onApply = function (effect) {
  23056. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23057. };
  23058. }
  23059. return FxaaPostProcess;
  23060. })(BABYLON.PostProcess);
  23061. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23062. })(BABYLON || (BABYLON = {}));
  23063. var BABYLON;
  23064. (function (BABYLON) {
  23065. var StereoscopicInterlacePostProcess = (function (_super) {
  23066. __extends(StereoscopicInterlacePostProcess, _super);
  23067. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23068. var _this = this;
  23069. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23070. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23071. this.onSizeChanged = function () {
  23072. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23073. };
  23074. this.onApply = function (effect) {
  23075. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23076. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23077. };
  23078. }
  23079. return StereoscopicInterlacePostProcess;
  23080. })(BABYLON.PostProcess);
  23081. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23082. })(BABYLON || (BABYLON = {}));
  23083. var BABYLON;
  23084. (function (BABYLON) {
  23085. var LensFlare = (function () {
  23086. function LensFlare(size, position, color, imgUrl, system) {
  23087. this.size = size;
  23088. this.position = position;
  23089. this.dispose = function () {
  23090. if (this.texture) {
  23091. this.texture.dispose();
  23092. }
  23093. // Remove from scene
  23094. var index = this._system.lensFlares.indexOf(this);
  23095. this._system.lensFlares.splice(index, 1);
  23096. };
  23097. this.color = color || new BABYLON.Color3(1, 1, 1);
  23098. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23099. this._system = system;
  23100. system.lensFlares.push(this);
  23101. }
  23102. return LensFlare;
  23103. })();
  23104. BABYLON.LensFlare = LensFlare;
  23105. })(BABYLON || (BABYLON = {}));
  23106. var BABYLON;
  23107. (function (BABYLON) {
  23108. var LensFlareSystem = (function () {
  23109. function LensFlareSystem(name, emitter, scene) {
  23110. this.name = name;
  23111. this.lensFlares = new Array();
  23112. this.borderLimit = 300;
  23113. this._vertexDeclaration = [2];
  23114. this._vertexStrideSize = 2 * 4;
  23115. this._isEnabled = true;
  23116. this._scene = scene;
  23117. this._emitter = emitter;
  23118. scene.lensFlareSystems.push(this);
  23119. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23120. // VBO
  23121. var vertices = [];
  23122. vertices.push(1, 1);
  23123. vertices.push(-1, 1);
  23124. vertices.push(-1, -1);
  23125. vertices.push(1, -1);
  23126. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23127. // Indices
  23128. var indices = [];
  23129. indices.push(0);
  23130. indices.push(1);
  23131. indices.push(2);
  23132. indices.push(0);
  23133. indices.push(2);
  23134. indices.push(3);
  23135. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23136. // Effects
  23137. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23138. }
  23139. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23140. get: function () {
  23141. return this._isEnabled;
  23142. },
  23143. set: function (value) {
  23144. this._isEnabled = value;
  23145. },
  23146. enumerable: true,
  23147. configurable: true
  23148. });
  23149. LensFlareSystem.prototype.getScene = function () {
  23150. return this._scene;
  23151. };
  23152. LensFlareSystem.prototype.getEmitter = function () {
  23153. return this._emitter;
  23154. };
  23155. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23156. this._emitter = newEmitter;
  23157. };
  23158. LensFlareSystem.prototype.getEmitterPosition = function () {
  23159. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23160. };
  23161. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23162. var position = this.getEmitterPosition();
  23163. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23164. this._positionX = position.x;
  23165. this._positionY = position.y;
  23166. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23167. if (position.z > 0) {
  23168. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23169. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23170. return true;
  23171. }
  23172. }
  23173. return false;
  23174. };
  23175. LensFlareSystem.prototype._isVisible = function () {
  23176. if (!this._isEnabled) {
  23177. return false;
  23178. }
  23179. var emitterPosition = this.getEmitterPosition();
  23180. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23181. var distance = direction.length();
  23182. direction.normalize();
  23183. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23184. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23185. return !pickInfo.hit || pickInfo.distance > distance;
  23186. };
  23187. LensFlareSystem.prototype.render = function () {
  23188. if (!this._effect.isReady())
  23189. return false;
  23190. var engine = this._scene.getEngine();
  23191. var viewport = this._scene.activeCamera.viewport;
  23192. var globalViewport = viewport.toGlobal(engine);
  23193. // Position
  23194. if (!this.computeEffectivePosition(globalViewport)) {
  23195. return false;
  23196. }
  23197. // Visibility
  23198. if (!this._isVisible()) {
  23199. return false;
  23200. }
  23201. // Intensity
  23202. var awayX;
  23203. var awayY;
  23204. if (this._positionX < this.borderLimit + globalViewport.x) {
  23205. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23206. }
  23207. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23208. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23209. }
  23210. else {
  23211. awayX = 0;
  23212. }
  23213. if (this._positionY < this.borderLimit + globalViewport.y) {
  23214. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23215. }
  23216. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23217. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23218. }
  23219. else {
  23220. awayY = 0;
  23221. }
  23222. var away = (awayX > awayY) ? awayX : awayY;
  23223. if (away > this.borderLimit) {
  23224. away = this.borderLimit;
  23225. }
  23226. var intensity = 1.0 - (away / this.borderLimit);
  23227. if (intensity < 0) {
  23228. return false;
  23229. }
  23230. if (intensity > 1.0) {
  23231. intensity = 1.0;
  23232. }
  23233. // Position
  23234. var centerX = globalViewport.x + globalViewport.width / 2;
  23235. var centerY = globalViewport.y + globalViewport.height / 2;
  23236. var distX = centerX - this._positionX;
  23237. var distY = centerY - this._positionY;
  23238. // Effects
  23239. engine.enableEffect(this._effect);
  23240. engine.setState(false);
  23241. engine.setDepthBuffer(false);
  23242. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23243. // VBOs
  23244. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23245. // Flares
  23246. for (var index = 0; index < this.lensFlares.length; index++) {
  23247. var flare = this.lensFlares[index];
  23248. var x = centerX - (distX * flare.position);
  23249. var y = centerY - (distY * flare.position);
  23250. var cw = flare.size;
  23251. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23252. var cx = 2 * (x / globalViewport.width) - 1.0;
  23253. var cy = 1.0 - 2 * (y / globalViewport.height);
  23254. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23255. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23256. // Texture
  23257. this._effect.setTexture("textureSampler", flare.texture);
  23258. // Color
  23259. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23260. // Draw order
  23261. engine.draw(true, 0, 6);
  23262. }
  23263. engine.setDepthBuffer(true);
  23264. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23265. return true;
  23266. };
  23267. LensFlareSystem.prototype.dispose = function () {
  23268. if (this._vertexBuffer) {
  23269. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23270. this._vertexBuffer = null;
  23271. }
  23272. if (this._indexBuffer) {
  23273. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23274. this._indexBuffer = null;
  23275. }
  23276. while (this.lensFlares.length) {
  23277. this.lensFlares[0].dispose();
  23278. }
  23279. // Remove from scene
  23280. var index = this._scene.lensFlareSystems.indexOf(this);
  23281. this._scene.lensFlareSystems.splice(index, 1);
  23282. };
  23283. return LensFlareSystem;
  23284. })();
  23285. BABYLON.LensFlareSystem = LensFlareSystem;
  23286. })(BABYLON || (BABYLON = {}));
  23287. var BABYLON;
  23288. (function (BABYLON) {
  23289. var CannonJSPlugin = (function () {
  23290. function CannonJSPlugin() {
  23291. this._registeredMeshes = [];
  23292. this._physicsMaterials = [];
  23293. this.updateBodyPosition = function (mesh) {
  23294. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23295. var registeredMesh = this._registeredMeshes[index];
  23296. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23297. var body = registeredMesh.body;
  23298. var center = mesh.getBoundingInfo().boundingBox.center;
  23299. body.position.set(center.x, center.z, center.y);
  23300. body.quaternion.x = mesh.rotationQuaternion.x;
  23301. body.quaternion.z = mesh.rotationQuaternion.y;
  23302. body.quaternion.y = mesh.rotationQuaternion.z;
  23303. body.quaternion.w = -mesh.rotationQuaternion.w;
  23304. return;
  23305. }
  23306. }
  23307. };
  23308. }
  23309. CannonJSPlugin.prototype.initialize = function (iterations) {
  23310. if (iterations === void 0) { iterations = 10; }
  23311. this._world = new CANNON.World();
  23312. this._world.broadphase = new CANNON.NaiveBroadphase();
  23313. this._world.solver.iterations = iterations;
  23314. };
  23315. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23316. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23317. };
  23318. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23319. this._world.step(delta);
  23320. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23321. var registeredMesh = this._registeredMeshes[index];
  23322. if (registeredMesh.isChild) {
  23323. continue;
  23324. }
  23325. // Body position
  23326. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23327. var deltaPos = registeredMesh.delta;
  23328. if (deltaPos) {
  23329. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23330. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23331. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23332. }
  23333. else {
  23334. registeredMesh.mesh.position.x = bodyX;
  23335. registeredMesh.mesh.position.y = bodyZ;
  23336. registeredMesh.mesh.position.z = bodyY;
  23337. }
  23338. if (!registeredMesh.mesh.rotationQuaternion) {
  23339. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23340. }
  23341. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23342. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23343. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23344. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23345. }
  23346. };
  23347. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23348. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23349. };
  23350. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23351. this.unregisterMesh(mesh);
  23352. mesh.computeWorldMatrix(true);
  23353. switch (impostor) {
  23354. case BABYLON.PhysicsEngine.SphereImpostor:
  23355. var bbox = mesh.getBoundingInfo().boundingBox;
  23356. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23357. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23358. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23359. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23360. case BABYLON.PhysicsEngine.BoxImpostor:
  23361. bbox = mesh.getBoundingInfo().boundingBox;
  23362. var min = bbox.minimumWorld;
  23363. var max = bbox.maximumWorld;
  23364. var box = max.subtract(min).scale(0.5);
  23365. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23366. case BABYLON.PhysicsEngine.PlaneImpostor:
  23367. return this._createPlane(mesh, options);
  23368. case BABYLON.PhysicsEngine.MeshImpostor:
  23369. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23370. var rawFaces = mesh.getIndices();
  23371. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23372. }
  23373. return null;
  23374. };
  23375. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23376. var shape = new CANNON.Sphere(radius);
  23377. if (!options) {
  23378. return shape;
  23379. }
  23380. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23381. };
  23382. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23383. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23384. if (!options) {
  23385. return shape;
  23386. }
  23387. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23388. };
  23389. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23390. var shape = new CANNON.Plane();
  23391. if (!options) {
  23392. return shape;
  23393. }
  23394. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23395. };
  23396. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23397. var verts = [], faces = [];
  23398. mesh.computeWorldMatrix(true);
  23399. // Get vertices
  23400. for (var i = 0; i < rawVerts.length; i += 3) {
  23401. var transformed = BABYLON.Vector3.Zero();
  23402. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23403. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23404. }
  23405. // Get faces
  23406. for (var j = 0; j < rawFaces.length; j += 3) {
  23407. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23408. }
  23409. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23410. if (!options) {
  23411. return shape;
  23412. }
  23413. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23414. };
  23415. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23416. var index;
  23417. var mat;
  23418. for (index = 0; index < this._physicsMaterials.length; index++) {
  23419. mat = this._physicsMaterials[index];
  23420. if (mat.friction === friction && mat.restitution === restitution) {
  23421. return mat;
  23422. }
  23423. }
  23424. var currentMat = new CANNON.Material();
  23425. currentMat.friction = friction;
  23426. currentMat.restitution = restitution;
  23427. this._physicsMaterials.push(currentMat);
  23428. for (index = 0; index < this._physicsMaterials.length; index++) {
  23429. mat = this._physicsMaterials[index];
  23430. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23431. contactMaterial.contactEquationStiffness = 1e10;
  23432. contactMaterial.contactEquationRegularizationTime = 10;
  23433. this._world.addContactMaterial(contactMaterial);
  23434. }
  23435. return currentMat;
  23436. };
  23437. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23438. var initialRotation = null;
  23439. if (mesh.rotationQuaternion) {
  23440. initialRotation = mesh.rotationQuaternion.clone();
  23441. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23442. }
  23443. // The delta between the mesh position and the mesh bounding box center
  23444. var bbox = mesh.getBoundingInfo().boundingBox;
  23445. var deltaPosition = mesh.position.subtract(bbox.center);
  23446. var material = this._addMaterial(friction, restitution);
  23447. var body = new CANNON.RigidBody(mass, shape, material);
  23448. if (initialRotation) {
  23449. body.quaternion.x = initialRotation.x;
  23450. body.quaternion.z = initialRotation.y;
  23451. body.quaternion.y = initialRotation.z;
  23452. body.quaternion.w = -initialRotation.w;
  23453. }
  23454. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23455. this._world.add(body);
  23456. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23457. return body;
  23458. };
  23459. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23460. var compoundShape = new CANNON.Compound();
  23461. for (var index = 0; index < parts.length; index++) {
  23462. var mesh = parts[index].mesh;
  23463. var shape = this.registerMesh(mesh, parts[index].impostor);
  23464. if (index == 0) {
  23465. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23466. }
  23467. else {
  23468. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23469. }
  23470. }
  23471. var initialMesh = parts[0].mesh;
  23472. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23473. body.parts = parts;
  23474. return body;
  23475. };
  23476. CannonJSPlugin.prototype._unbindBody = function (body) {
  23477. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23478. var registeredMesh = this._registeredMeshes[index];
  23479. if (registeredMesh.body === body) {
  23480. registeredMesh.body = null;
  23481. registeredMesh.delta = 0;
  23482. }
  23483. }
  23484. };
  23485. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23486. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23487. var registeredMesh = this._registeredMeshes[index];
  23488. if (registeredMesh.mesh === mesh) {
  23489. // Remove body
  23490. if (registeredMesh.body) {
  23491. this._world.remove(registeredMesh.body);
  23492. this._unbindBody(registeredMesh.body);
  23493. }
  23494. this._registeredMeshes.splice(index, 1);
  23495. return;
  23496. }
  23497. }
  23498. };
  23499. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23500. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23501. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23502. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23503. var registeredMesh = this._registeredMeshes[index];
  23504. if (registeredMesh.mesh === mesh) {
  23505. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23506. return;
  23507. }
  23508. }
  23509. };
  23510. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23511. var body1 = null, body2 = null;
  23512. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23513. var registeredMesh = this._registeredMeshes[index];
  23514. if (registeredMesh.mesh === mesh1) {
  23515. body1 = registeredMesh.body;
  23516. }
  23517. else if (registeredMesh.mesh === mesh2) {
  23518. body2 = registeredMesh.body;
  23519. }
  23520. }
  23521. if (!body1 || !body2) {
  23522. return false;
  23523. }
  23524. 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));
  23525. this._world.addConstraint(constraint);
  23526. return true;
  23527. };
  23528. CannonJSPlugin.prototype.dispose = function () {
  23529. while (this._registeredMeshes.length) {
  23530. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23531. }
  23532. };
  23533. CannonJSPlugin.prototype.isSupported = function () {
  23534. return window.CANNON !== undefined;
  23535. };
  23536. return CannonJSPlugin;
  23537. })();
  23538. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23539. })(BABYLON || (BABYLON = {}));
  23540. var BABYLON;
  23541. (function (BABYLON) {
  23542. var OimoJSPlugin = (function () {
  23543. function OimoJSPlugin() {
  23544. this._registeredMeshes = [];
  23545. /**
  23546. * Update the body position according to the mesh position
  23547. * @param mesh
  23548. */
  23549. this.updateBodyPosition = function (mesh) {
  23550. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23551. var registeredMesh = this._registeredMeshes[index];
  23552. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23553. var body = registeredMesh.body.body;
  23554. mesh.computeWorldMatrix(true);
  23555. var center = mesh.getBoundingInfo().boundingBox.center;
  23556. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23557. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23558. body.sleeping = false;
  23559. return;
  23560. }
  23561. // Case where the parent has been updated
  23562. if (registeredMesh.mesh.parent === mesh) {
  23563. mesh.computeWorldMatrix(true);
  23564. registeredMesh.mesh.computeWorldMatrix(true);
  23565. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23566. var absoluteRotation = mesh.rotation;
  23567. body = registeredMesh.body.body;
  23568. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23569. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23570. body.sleeping = false;
  23571. return;
  23572. }
  23573. }
  23574. };
  23575. }
  23576. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23577. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23578. };
  23579. OimoJSPlugin.prototype.initialize = function (iterations) {
  23580. this._world = new OIMO.World();
  23581. this._world.clear();
  23582. };
  23583. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23584. this._world.gravity = gravity;
  23585. };
  23586. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23587. var body = null;
  23588. this.unregisterMesh(mesh);
  23589. mesh.computeWorldMatrix(true);
  23590. var initialRotation = null;
  23591. if (mesh.rotationQuaternion) {
  23592. initialRotation = mesh.rotationQuaternion.clone();
  23593. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23594. mesh.computeWorldMatrix(true);
  23595. }
  23596. var bbox = mesh.getBoundingInfo().boundingBox;
  23597. // The delta between the mesh position and the mesh bounding box center
  23598. var deltaPosition = mesh.position.subtract(bbox.center);
  23599. // Transform delta position with the rotation
  23600. if (initialRotation) {
  23601. var m = new BABYLON.Matrix();
  23602. initialRotation.toRotationMatrix(m);
  23603. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23604. }
  23605. // register mesh
  23606. switch (impostor) {
  23607. case BABYLON.PhysicsEngine.SphereImpostor:
  23608. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23609. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23610. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23611. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23612. body = new OIMO.Body({
  23613. type: 'sphere',
  23614. size: [size],
  23615. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23616. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23617. move: options.mass != 0,
  23618. config: [options.mass, options.friction, options.restitution],
  23619. world: this._world
  23620. });
  23621. break;
  23622. case BABYLON.PhysicsEngine.PlaneImpostor:
  23623. //Oimo "fakes" a cylinder as a box, so why don't we!
  23624. case BABYLON.PhysicsEngine.CylinderImpostor:
  23625. case BABYLON.PhysicsEngine.BoxImpostor:
  23626. var min = bbox.minimumWorld;
  23627. var max = bbox.maximumWorld;
  23628. var box = max.subtract(min);
  23629. var sizeX = this._checkWithEpsilon(box.x);
  23630. var sizeY = this._checkWithEpsilon(box.y);
  23631. var sizeZ = this._checkWithEpsilon(box.z);
  23632. body = new OIMO.Body({
  23633. type: 'box',
  23634. size: [sizeX, sizeY, sizeZ],
  23635. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23636. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23637. move: options.mass != 0,
  23638. config: [options.mass, options.friction, options.restitution],
  23639. world: this._world
  23640. });
  23641. break;
  23642. }
  23643. //If quaternion was set as the rotation of the object
  23644. if (initialRotation) {
  23645. //We have to access the rigid body's properties to set the quaternion.
  23646. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23647. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23648. //update the internal rotation matrix
  23649. body.body.syncShapes();
  23650. }
  23651. this._registeredMeshes.push({
  23652. mesh: mesh,
  23653. body: body,
  23654. delta: deltaPosition
  23655. });
  23656. return body;
  23657. };
  23658. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23659. var types = [], sizes = [], positions = [], rotations = [];
  23660. var initialMesh = parts[0].mesh;
  23661. for (var index = 0; index < parts.length; index++) {
  23662. var part = parts[index];
  23663. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23664. types.push(bodyParameters.type);
  23665. sizes.push.apply(sizes, bodyParameters.size);
  23666. positions.push.apply(positions, bodyParameters.pos);
  23667. rotations.push.apply(rotations, bodyParameters.rot);
  23668. }
  23669. var body = new OIMO.Body({
  23670. type: types,
  23671. size: sizes,
  23672. pos: positions,
  23673. rot: rotations,
  23674. move: options.mass != 0,
  23675. config: [options.mass, options.friction, options.restitution],
  23676. world: this._world
  23677. });
  23678. this._registeredMeshes.push({
  23679. mesh: initialMesh,
  23680. body: body
  23681. });
  23682. return body;
  23683. };
  23684. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23685. var bodyParameters = null;
  23686. var mesh = part.mesh;
  23687. // We need the bounding box/sphere info to compute the physics body
  23688. mesh.computeWorldMatrix();
  23689. switch (part.impostor) {
  23690. case BABYLON.PhysicsEngine.SphereImpostor:
  23691. var bbox = mesh.getBoundingInfo().boundingBox;
  23692. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23693. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23694. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23695. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23696. bodyParameters = {
  23697. type: 'sphere',
  23698. /* bug with oimo : sphere needs 3 sizes in this case */
  23699. size: [size, -1, -1],
  23700. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23701. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23702. };
  23703. break;
  23704. case BABYLON.PhysicsEngine.PlaneImpostor:
  23705. case BABYLON.PhysicsEngine.BoxImpostor:
  23706. bbox = mesh.getBoundingInfo().boundingBox;
  23707. var min = bbox.minimumWorld;
  23708. var max = bbox.maximumWorld;
  23709. var box = max.subtract(min);
  23710. var sizeX = this._checkWithEpsilon(box.x);
  23711. var sizeY = this._checkWithEpsilon(box.y);
  23712. var sizeZ = this._checkWithEpsilon(box.z);
  23713. var relativePosition = mesh.position;
  23714. bodyParameters = {
  23715. type: 'box',
  23716. size: [sizeX, sizeY, sizeZ],
  23717. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23718. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23719. };
  23720. break;
  23721. }
  23722. return bodyParameters;
  23723. };
  23724. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23725. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23726. var registeredMesh = this._registeredMeshes[index];
  23727. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23728. if (registeredMesh.body) {
  23729. this._world.removeRigidBody(registeredMesh.body.body);
  23730. this._unbindBody(registeredMesh.body);
  23731. }
  23732. this._registeredMeshes.splice(index, 1);
  23733. return;
  23734. }
  23735. }
  23736. };
  23737. OimoJSPlugin.prototype._unbindBody = function (body) {
  23738. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23739. var registeredMesh = this._registeredMeshes[index];
  23740. if (registeredMesh.body === body) {
  23741. registeredMesh.body = null;
  23742. }
  23743. }
  23744. };
  23745. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23746. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23747. var registeredMesh = this._registeredMeshes[index];
  23748. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23749. // Get object mass to have a behaviour similar to cannon.js
  23750. var mass = registeredMesh.body.body.massInfo.mass;
  23751. // The force is scaled with the mass of object
  23752. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23753. return;
  23754. }
  23755. }
  23756. };
  23757. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23758. var body1 = null, body2 = null;
  23759. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23760. var registeredMesh = this._registeredMeshes[index];
  23761. if (registeredMesh.mesh === mesh1) {
  23762. body1 = registeredMesh.body.body;
  23763. }
  23764. else if (registeredMesh.mesh === mesh2) {
  23765. body2 = registeredMesh.body.body;
  23766. }
  23767. }
  23768. if (!body1 || !body2) {
  23769. return false;
  23770. }
  23771. if (!options) {
  23772. options = {};
  23773. }
  23774. new OIMO.Link({
  23775. type: options.type,
  23776. body1: body1,
  23777. body2: body2,
  23778. min: options.min,
  23779. max: options.max,
  23780. axe1: options.axe1,
  23781. axe2: options.axe2,
  23782. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23783. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23784. collision: options.collision,
  23785. spring: options.spring,
  23786. world: this._world
  23787. });
  23788. return true;
  23789. };
  23790. OimoJSPlugin.prototype.dispose = function () {
  23791. this._world.clear();
  23792. while (this._registeredMeshes.length) {
  23793. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23794. }
  23795. };
  23796. OimoJSPlugin.prototype.isSupported = function () {
  23797. return OIMO !== undefined;
  23798. };
  23799. OimoJSPlugin.prototype._getLastShape = function (body) {
  23800. var lastShape = body.shapes;
  23801. while (lastShape.next) {
  23802. lastShape = lastShape.next;
  23803. }
  23804. return lastShape;
  23805. };
  23806. OimoJSPlugin.prototype.runOneStep = function (time) {
  23807. this._world.step();
  23808. // Update the position of all registered meshes
  23809. var i = this._registeredMeshes.length;
  23810. var m;
  23811. while (i--) {
  23812. var body = this._registeredMeshes[i].body.body;
  23813. var mesh = this._registeredMeshes[i].mesh;
  23814. var delta = this._registeredMeshes[i].delta;
  23815. if (!body.sleeping) {
  23816. if (body.shapes.next) {
  23817. var parentShape = this._getLastShape(body);
  23818. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23819. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23820. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23821. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23822. if (!mesh.rotationQuaternion) {
  23823. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23824. }
  23825. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23826. mesh.computeWorldMatrix();
  23827. }
  23828. else {
  23829. m = body.getMatrix();
  23830. mtx = BABYLON.Matrix.FromArray(m);
  23831. // Body position
  23832. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23833. if (!delta) {
  23834. mesh.position.x = bodyX;
  23835. mesh.position.y = bodyY;
  23836. mesh.position.z = bodyZ;
  23837. }
  23838. else {
  23839. mesh.position.x = bodyX + delta.x;
  23840. mesh.position.y = bodyY + delta.y;
  23841. mesh.position.z = bodyZ + delta.z;
  23842. }
  23843. if (!mesh.rotationQuaternion) {
  23844. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23845. }
  23846. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23847. mesh.computeWorldMatrix();
  23848. }
  23849. }
  23850. }
  23851. };
  23852. return OimoJSPlugin;
  23853. })();
  23854. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23855. })(BABYLON || (BABYLON = {}));
  23856. var BABYLON;
  23857. (function (BABYLON) {
  23858. var PhysicsEngine = (function () {
  23859. function PhysicsEngine(plugin) {
  23860. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23861. }
  23862. PhysicsEngine.prototype._initialize = function (gravity) {
  23863. this._currentPlugin.initialize();
  23864. this._setGravity(gravity);
  23865. };
  23866. PhysicsEngine.prototype._runOneStep = function (delta) {
  23867. if (delta > 0.1) {
  23868. delta = 0.1;
  23869. }
  23870. else if (delta <= 0) {
  23871. delta = 1.0 / 60.0;
  23872. }
  23873. this._currentPlugin.runOneStep(delta);
  23874. };
  23875. PhysicsEngine.prototype._setGravity = function (gravity) {
  23876. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23877. this._currentPlugin.setGravity(this.gravity);
  23878. };
  23879. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23880. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23881. };
  23882. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23883. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23884. };
  23885. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23886. this._currentPlugin.unregisterMesh(mesh);
  23887. };
  23888. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23889. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23890. };
  23891. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23892. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23893. };
  23894. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23895. this._currentPlugin.updateBodyPosition(mesh);
  23896. };
  23897. PhysicsEngine.prototype.dispose = function () {
  23898. this._currentPlugin.dispose();
  23899. };
  23900. PhysicsEngine.prototype.isSupported = function () {
  23901. return this._currentPlugin.isSupported();
  23902. };
  23903. // Statics
  23904. PhysicsEngine.NoImpostor = 0;
  23905. PhysicsEngine.SphereImpostor = 1;
  23906. PhysicsEngine.BoxImpostor = 2;
  23907. PhysicsEngine.PlaneImpostor = 3;
  23908. PhysicsEngine.MeshImpostor = 4;
  23909. PhysicsEngine.CapsuleImpostor = 5;
  23910. PhysicsEngine.ConeImpostor = 6;
  23911. PhysicsEngine.CylinderImpostor = 7;
  23912. PhysicsEngine.ConvexHullImpostor = 8;
  23913. PhysicsEngine.Epsilon = 0.001;
  23914. return PhysicsEngine;
  23915. })();
  23916. BABYLON.PhysicsEngine = PhysicsEngine;
  23917. })(BABYLON || (BABYLON = {}));
  23918. var BABYLON;
  23919. (function (BABYLON) {
  23920. var serializeLight = function (light) {
  23921. var serializationObject = {};
  23922. serializationObject.name = light.name;
  23923. serializationObject.id = light.id;
  23924. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23925. if (light instanceof BABYLON.PointLight) {
  23926. serializationObject.type = 0;
  23927. serializationObject.position = (light).position.asArray();
  23928. }
  23929. else if (light instanceof BABYLON.DirectionalLight) {
  23930. serializationObject.type = 1;
  23931. var directionalLight = light;
  23932. serializationObject.position = directionalLight.position.asArray();
  23933. serializationObject.direction = directionalLight.direction.asArray();
  23934. }
  23935. else if (light instanceof BABYLON.SpotLight) {
  23936. serializationObject.type = 2;
  23937. var spotLight = light;
  23938. serializationObject.position = spotLight.position.asArray();
  23939. serializationObject.direction = spotLight.position.asArray();
  23940. serializationObject.angle = spotLight.angle;
  23941. serializationObject.exponent = spotLight.exponent;
  23942. }
  23943. else if (light instanceof BABYLON.HemisphericLight) {
  23944. serializationObject.type = 3;
  23945. var hemisphericLight = light;
  23946. serializationObject.direction = hemisphericLight.direction.asArray();
  23947. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23948. }
  23949. if (light.intensity) {
  23950. serializationObject.intensity = light.intensity;
  23951. }
  23952. serializationObject.range = light.range;
  23953. serializationObject.diffuse = light.diffuse.asArray();
  23954. serializationObject.specular = light.specular.asArray();
  23955. return serializationObject;
  23956. };
  23957. var serializeFresnelParameter = function (fresnelParameter) {
  23958. var serializationObject = {};
  23959. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23960. serializationObject.leftColor = fresnelParameter.leftColor;
  23961. serializationObject.rightColor = fresnelParameter.rightColor;
  23962. serializationObject.bias = fresnelParameter.bias;
  23963. serializationObject.power = fresnelParameter.power;
  23964. return serializationObject;
  23965. };
  23966. var serializeAnimation;
  23967. var appendAnimations = function (source, destination) {
  23968. if (source.animations) {
  23969. destination.animations = [];
  23970. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23971. var animation = source.animations[animationIndex];
  23972. destination.animations.push(serializeAnimation(animation));
  23973. }
  23974. }
  23975. };
  23976. var serializeCamera = function (camera) {
  23977. var serializationObject = {};
  23978. serializationObject.name = camera.name;
  23979. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23980. serializationObject.id = camera.id;
  23981. serializationObject.position = camera.position.asArray();
  23982. // Parent
  23983. if (camera.parent) {
  23984. serializationObject.parentId = camera.parent.id;
  23985. }
  23986. serializationObject.fov = camera.fov;
  23987. serializationObject.minZ = camera.minZ;
  23988. serializationObject.maxZ = camera.maxZ;
  23989. serializationObject.inertia = camera.inertia;
  23990. //setting the type
  23991. if (camera instanceof BABYLON.FreeCamera) {
  23992. serializationObject.type = "FreeCamera";
  23993. }
  23994. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23995. serializationObject.type = "ArcRotateCamera";
  23996. }
  23997. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23998. serializationObject.type = "AnaglyphArcRotateCamera";
  23999. }
  24000. else if (camera instanceof BABYLON.GamepadCamera) {
  24001. serializationObject.type = "GamepadCamera";
  24002. }
  24003. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24004. serializationObject.type = "AnaglyphFreeCamera";
  24005. }
  24006. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24007. serializationObject.type = "DeviceOrientationCamera";
  24008. }
  24009. else if (camera instanceof BABYLON.FollowCamera) {
  24010. serializationObject.type = "FollowCamera";
  24011. }
  24012. else if (camera instanceof BABYLON.TouchCamera) {
  24013. serializationObject.type = "TouchCamera";
  24014. }
  24015. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24016. serializationObject.type = "VirtualJoysticksCamera";
  24017. }
  24018. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24019. serializationObject.type = "WebVRFreeCamera";
  24020. }
  24021. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24022. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24023. }
  24024. //special properties of specific cameras
  24025. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24026. var arcCamera = camera;
  24027. serializationObject.alpha = arcCamera.alpha;
  24028. serializationObject.beta = arcCamera.beta;
  24029. serializationObject.radius = arcCamera.radius;
  24030. if (arcCamera.target && arcCamera.target.id) {
  24031. serializationObject.lockedTargetId = arcCamera.target.id;
  24032. }
  24033. }
  24034. else if (camera instanceof BABYLON.FollowCamera) {
  24035. var followCam = camera;
  24036. serializationObject.radius = followCam.radius;
  24037. serializationObject.heightOffset = followCam.heightOffset;
  24038. serializationObject.rotationOffset = followCam.rotationOffset;
  24039. }
  24040. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24041. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  24042. if (camera['_interaxialDistance'] !== undefined) {
  24043. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24044. }
  24045. }
  24046. //general properties that not all cameras have. The [] is due to typescript's type safety
  24047. if (camera['speed'] !== undefined) {
  24048. serializationObject.speed = camera['speed'];
  24049. }
  24050. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24051. serializationObject.target = camera['target'].asArray();
  24052. }
  24053. // Target
  24054. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24055. serializationObject.rotation = camera['rotation'].asArray();
  24056. }
  24057. // Locked target
  24058. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24059. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24060. }
  24061. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24062. serializationObject.applyGravity = camera['applyGravity'] || false;
  24063. if (camera['ellipsoid']) {
  24064. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24065. }
  24066. // Animations
  24067. appendAnimations(camera, serializationObject);
  24068. // Layer mask
  24069. serializationObject.layerMask = camera.layerMask;
  24070. return serializationObject;
  24071. };
  24072. serializeAnimation = function (animation) {
  24073. var serializationObject = {};
  24074. serializationObject.name = animation.name;
  24075. serializationObject.property = animation.targetProperty;
  24076. serializationObject.framePerSecond = animation.framePerSecond;
  24077. serializationObject.dataType = animation.dataType;
  24078. serializationObject.loopBehavior = animation.loopMode;
  24079. var dataType = animation.dataType;
  24080. serializationObject.keys = [];
  24081. var keys = animation.getKeys();
  24082. for (var index = 0; index < keys.length; index++) {
  24083. var animationKey = keys[index];
  24084. var key = {};
  24085. key.frame = animationKey.frame;
  24086. switch (dataType) {
  24087. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24088. key.values = [animationKey.value];
  24089. break;
  24090. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24091. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24092. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24093. key.values = animationKey.value.asArray();
  24094. break;
  24095. }
  24096. serializationObject.keys.push(key);
  24097. }
  24098. return serializationObject;
  24099. };
  24100. var serializeMultiMaterial = function (material) {
  24101. var serializationObject = {};
  24102. serializationObject.name = material.name;
  24103. serializationObject.id = material.id;
  24104. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24105. serializationObject.materials = [];
  24106. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24107. var subMat = material.subMaterials[matIndex];
  24108. if (subMat) {
  24109. serializationObject.materials.push(subMat.id);
  24110. }
  24111. else {
  24112. serializationObject.materials.push(null);
  24113. }
  24114. }
  24115. return serializationObject;
  24116. };
  24117. var serializeTexture;
  24118. var serializeMaterial = function (material) {
  24119. var serializationObject = {};
  24120. serializationObject.name = material.name;
  24121. serializationObject.ambient = material.ambientColor.asArray();
  24122. serializationObject.diffuse = material.diffuseColor.asArray();
  24123. serializationObject.specular = material.specularColor.asArray();
  24124. serializationObject.specularPower = material.specularPower;
  24125. serializationObject.emissive = material.emissiveColor.asArray();
  24126. serializationObject.alpha = material.alpha;
  24127. serializationObject.id = material.id;
  24128. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24129. serializationObject.backFaceCulling = material.backFaceCulling;
  24130. if (material.diffuseTexture) {
  24131. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24132. }
  24133. if (material.diffuseFresnelParameters) {
  24134. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24135. }
  24136. if (material.ambientTexture) {
  24137. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24138. }
  24139. if (material.opacityTexture) {
  24140. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24141. }
  24142. if (material.opacityFresnelParameters) {
  24143. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24144. }
  24145. if (material.reflectionTexture) {
  24146. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24147. }
  24148. if (material.reflectionFresnelParameters) {
  24149. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24150. }
  24151. if (material.emissiveTexture) {
  24152. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24153. }
  24154. if (material.emissiveFresnelParameters) {
  24155. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24156. }
  24157. if (material.specularTexture) {
  24158. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24159. }
  24160. if (material.bumpTexture) {
  24161. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24162. }
  24163. return serializationObject;
  24164. };
  24165. serializeTexture = function (texture) {
  24166. var serializationObject = {};
  24167. if (!texture.name) {
  24168. return null;
  24169. }
  24170. if (texture instanceof BABYLON.CubeTexture) {
  24171. serializationObject.name = texture.name;
  24172. serializationObject.hasAlpha = texture.hasAlpha;
  24173. serializationObject.isCube = true;
  24174. serializationObject.level = texture.level;
  24175. serializationObject.coordinatesMode = texture.coordinatesMode;
  24176. return serializationObject;
  24177. }
  24178. var index;
  24179. if (texture instanceof BABYLON.MirrorTexture) {
  24180. var mirrorTexture = texture;
  24181. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24182. serializationObject.renderList = [];
  24183. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24184. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24185. }
  24186. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24187. }
  24188. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24189. var renderTargetTexture = texture;
  24190. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24191. serializationObject.renderList = [];
  24192. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24193. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24194. }
  24195. }
  24196. var regularTexture = texture;
  24197. serializationObject.name = texture.name;
  24198. serializationObject.hasAlpha = texture.hasAlpha;
  24199. serializationObject.level = texture.level;
  24200. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24201. serializationObject.coordinatesMode = texture.coordinatesMode;
  24202. serializationObject.uOffset = regularTexture.uOffset;
  24203. serializationObject.vOffset = regularTexture.vOffset;
  24204. serializationObject.uScale = regularTexture.uScale;
  24205. serializationObject.vScale = regularTexture.vScale;
  24206. serializationObject.uAng = regularTexture.uAng;
  24207. serializationObject.vAng = regularTexture.vAng;
  24208. serializationObject.wAng = regularTexture.wAng;
  24209. serializationObject.wrapU = texture.wrapU;
  24210. serializationObject.wrapV = texture.wrapV;
  24211. // Animations
  24212. appendAnimations(texture, serializationObject);
  24213. return serializationObject;
  24214. };
  24215. var serializeSkeleton = function (skeleton) {
  24216. var serializationObject = {};
  24217. serializationObject.name = skeleton.name;
  24218. serializationObject.id = skeleton.id;
  24219. serializationObject.bones = [];
  24220. for (var index = 0; index < skeleton.bones.length; index++) {
  24221. var bone = skeleton.bones[index];
  24222. var serializedBone = {
  24223. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24224. name: bone.name,
  24225. matrix: bone.getLocalMatrix().toArray()
  24226. };
  24227. serializationObject.bones.push(serializedBone);
  24228. if (bone.animations && bone.animations.length > 0) {
  24229. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24230. }
  24231. }
  24232. return serializationObject;
  24233. };
  24234. var serializeParticleSystem = function (particleSystem) {
  24235. var serializationObject = {};
  24236. serializationObject.emitterId = particleSystem.emitter.id;
  24237. serializationObject.capacity = particleSystem.getCapacity();
  24238. if (particleSystem.particleTexture) {
  24239. serializationObject.textureName = particleSystem.particleTexture.name;
  24240. }
  24241. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24242. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24243. serializationObject.minSize = particleSystem.minSize;
  24244. serializationObject.maxSize = particleSystem.maxSize;
  24245. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24246. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24247. serializationObject.emitRate = particleSystem.emitRate;
  24248. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24249. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24250. serializationObject.gravity = particleSystem.gravity.asArray();
  24251. serializationObject.direction1 = particleSystem.direction1.asArray();
  24252. serializationObject.direction2 = particleSystem.direction2.asArray();
  24253. serializationObject.color1 = particleSystem.color1.asArray();
  24254. serializationObject.color2 = particleSystem.color2.asArray();
  24255. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24256. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24257. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24258. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24259. serializationObject.blendMode = particleSystem.blendMode;
  24260. return serializationObject;
  24261. };
  24262. var serializeLensFlareSystem = function (lensFlareSystem) {
  24263. var serializationObject = {};
  24264. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24265. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24266. serializationObject.flares = [];
  24267. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24268. var flare = lensFlareSystem.lensFlares[index];
  24269. serializationObject.flares.push({
  24270. size: flare.size,
  24271. position: flare.position,
  24272. color: flare.color.asArray(),
  24273. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24274. });
  24275. }
  24276. return serializationObject;
  24277. };
  24278. var serializeShadowGenerator = function (light) {
  24279. var serializationObject = {};
  24280. var shadowGenerator = light.getShadowGenerator();
  24281. serializationObject.lightId = light.id;
  24282. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24283. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24284. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24285. serializationObject.renderList = [];
  24286. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24287. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24288. serializationObject.renderList.push(mesh.id);
  24289. }
  24290. return serializationObject;
  24291. };
  24292. var serializedGeometries = [];
  24293. var serializeVertexData;
  24294. var serializeTorusKnot;
  24295. var serializePlane;
  24296. var serializeGround;
  24297. var serializeTorus;
  24298. var serializeCylinder;
  24299. var serializeSphere;
  24300. var serializeBox;
  24301. var serializeGeometry = function (geometry, serializationGeometries) {
  24302. if (serializedGeometries[geometry.id]) {
  24303. return;
  24304. }
  24305. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24306. serializationGeometries.boxes.push(serializeBox(geometry));
  24307. }
  24308. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24309. serializationGeometries.spheres.push(serializeSphere(geometry));
  24310. }
  24311. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24312. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24313. }
  24314. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24315. serializationGeometries.toruses.push(serializeTorus(geometry));
  24316. }
  24317. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24318. serializationGeometries.grounds.push(serializeGround(geometry));
  24319. }
  24320. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24321. serializationGeometries.planes.push(serializePlane(geometry));
  24322. }
  24323. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24324. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24325. }
  24326. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24327. throw new Error("Unknown primitive type");
  24328. }
  24329. else {
  24330. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24331. }
  24332. serializedGeometries[geometry.id] = true;
  24333. };
  24334. var serializeGeometryBase = function (geometry) {
  24335. var serializationObject = {};
  24336. serializationObject.id = geometry.id;
  24337. if (BABYLON.Tags.HasTags(geometry)) {
  24338. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24339. }
  24340. return serializationObject;
  24341. };
  24342. serializeVertexData = function (vertexData) {
  24343. var serializationObject = serializeGeometryBase(vertexData);
  24344. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24345. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24346. }
  24347. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24348. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24349. }
  24350. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24351. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24352. }
  24353. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24354. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24355. }
  24356. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24357. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24358. }
  24359. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24360. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24361. }
  24362. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24363. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24364. }
  24365. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24366. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24367. }
  24368. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24369. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24370. }
  24371. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24372. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24373. serializationObject.matricesIndices._isExpanded = true;
  24374. }
  24375. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24376. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24377. }
  24378. serializationObject.indices = vertexData.getIndices();
  24379. return serializationObject;
  24380. };
  24381. var serializePrimitive = function (primitive) {
  24382. var serializationObject = serializeGeometryBase(primitive);
  24383. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24384. return serializationObject;
  24385. };
  24386. serializeBox = function (box) {
  24387. var serializationObject = serializePrimitive(box);
  24388. serializationObject.size = box.size;
  24389. return serializationObject;
  24390. };
  24391. serializeSphere = function (sphere) {
  24392. var serializationObject = serializePrimitive(sphere);
  24393. serializationObject.segments = sphere.segments;
  24394. serializationObject.diameter = sphere.diameter;
  24395. return serializationObject;
  24396. };
  24397. serializeCylinder = function (cylinder) {
  24398. var serializationObject = serializePrimitive(cylinder);
  24399. serializationObject.height = cylinder.height;
  24400. serializationObject.diameterTop = cylinder.diameterTop;
  24401. serializationObject.diameterBottom = cylinder.diameterBottom;
  24402. serializationObject.tessellation = cylinder.tessellation;
  24403. return serializationObject;
  24404. };
  24405. serializeTorus = function (torus) {
  24406. var serializationObject = serializePrimitive(torus);
  24407. serializationObject.diameter = torus.diameter;
  24408. serializationObject.thickness = torus.thickness;
  24409. serializationObject.tessellation = torus.tessellation;
  24410. return serializationObject;
  24411. };
  24412. serializeGround = function (ground) {
  24413. var serializationObject = serializePrimitive(ground);
  24414. serializationObject.width = ground.width;
  24415. serializationObject.height = ground.height;
  24416. serializationObject.subdivisions = ground.subdivisions;
  24417. return serializationObject;
  24418. };
  24419. serializePlane = function (plane) {
  24420. var serializationObject = serializePrimitive(plane);
  24421. serializationObject.size = plane.size;
  24422. return serializationObject;
  24423. };
  24424. serializeTorusKnot = function (torusKnot) {
  24425. var serializationObject = serializePrimitive(torusKnot);
  24426. serializationObject.radius = torusKnot.radius;
  24427. serializationObject.tube = torusKnot.tube;
  24428. serializationObject.radialSegments = torusKnot.radialSegments;
  24429. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24430. serializationObject.p = torusKnot.p;
  24431. serializationObject.q = torusKnot.q;
  24432. return serializationObject;
  24433. };
  24434. var serializeMesh = function (mesh, serializationScene) {
  24435. var serializationObject = {};
  24436. serializationObject.name = mesh.name;
  24437. serializationObject.id = mesh.id;
  24438. if (BABYLON.Tags.HasTags(mesh)) {
  24439. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24440. }
  24441. serializationObject.position = mesh.position.asArray();
  24442. if (mesh.rotationQuaternion) {
  24443. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24444. }
  24445. else if (mesh.rotation) {
  24446. serializationObject.rotation = mesh.rotation.asArray();
  24447. }
  24448. serializationObject.scaling = mesh.scaling.asArray();
  24449. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24450. serializationObject.isEnabled = mesh.isEnabled();
  24451. serializationObject.isVisible = mesh.isVisible;
  24452. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24453. serializationObject.pickable = mesh.isPickable;
  24454. serializationObject.receiveShadows = mesh.receiveShadows;
  24455. serializationObject.billboardMode = mesh.billboardMode;
  24456. serializationObject.visibility = mesh.visibility;
  24457. serializationObject.checkCollisions = mesh.checkCollisions;
  24458. // Parent
  24459. if (mesh.parent) {
  24460. serializationObject.parentId = mesh.parent.id;
  24461. }
  24462. // Geometry
  24463. var geometry = mesh._geometry;
  24464. if (geometry) {
  24465. var geometryId = geometry.id;
  24466. serializationObject.geometryId = geometryId;
  24467. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24468. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  24469. serializeGeometry(geometry, serializationScene.geometries);
  24470. }
  24471. // SubMeshes
  24472. serializationObject.subMeshes = [];
  24473. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24474. var subMesh = mesh.subMeshes[subIndex];
  24475. serializationObject.subMeshes.push({
  24476. materialIndex: subMesh.materialIndex,
  24477. verticesStart: subMesh.verticesStart,
  24478. verticesCount: subMesh.verticesCount,
  24479. indexStart: subMesh.indexStart,
  24480. indexCount: subMesh.indexCount
  24481. });
  24482. }
  24483. }
  24484. // Material
  24485. if (mesh.material) {
  24486. serializationObject.materialId = mesh.material.id;
  24487. }
  24488. else {
  24489. mesh.material = null;
  24490. }
  24491. // Skeleton
  24492. if (mesh.skeleton) {
  24493. serializationObject.skeletonId = mesh.skeleton.id;
  24494. }
  24495. // Physics
  24496. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24497. serializationObject.physicsMass = mesh.getPhysicsMass();
  24498. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24499. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24500. switch (mesh.getPhysicsImpostor()) {
  24501. case BABYLON.PhysicsEngine.BoxImpostor:
  24502. serializationObject.physicsImpostor = 1;
  24503. break;
  24504. case BABYLON.PhysicsEngine.SphereImpostor:
  24505. serializationObject.physicsImpostor = 2;
  24506. break;
  24507. }
  24508. }
  24509. // Instances
  24510. serializationObject.instances = [];
  24511. for (var index = 0; index < mesh.instances.length; index++) {
  24512. var instance = mesh.instances[index];
  24513. var serializationInstance = {
  24514. name: instance.name,
  24515. position: instance.position,
  24516. rotation: instance.rotation,
  24517. rotationQuaternion: instance.rotationQuaternion,
  24518. scaling: instance.scaling
  24519. };
  24520. serializationObject.instances.push(serializationInstance);
  24521. // Animations
  24522. appendAnimations(instance, serializationInstance);
  24523. }
  24524. // Animations
  24525. appendAnimations(mesh, serializationObject);
  24526. // Layer mask
  24527. serializationObject.layerMask = mesh.layerMask;
  24528. return serializationObject;
  24529. };
  24530. var finalizeSingleMesh = function (mesh, serializationObject) {
  24531. //only works if the mesh is already loaded
  24532. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24533. //serialize material
  24534. if (mesh.material) {
  24535. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24536. serializationObject.materials = serializationObject.materials || [];
  24537. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24538. serializationObject.materials.push(serializeMaterial(mesh.material));
  24539. }
  24540. }
  24541. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24542. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24543. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24544. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24545. }
  24546. }
  24547. }
  24548. //serialize geometry
  24549. var geometry = mesh._geometry;
  24550. if (geometry) {
  24551. if (!serializationObject.geometries) {
  24552. serializationObject.geometries = {};
  24553. serializationObject.geometries.boxes = [];
  24554. serializationObject.geometries.spheres = [];
  24555. serializationObject.geometries.cylinders = [];
  24556. serializationObject.geometries.toruses = [];
  24557. serializationObject.geometries.grounds = [];
  24558. serializationObject.geometries.planes = [];
  24559. serializationObject.geometries.torusKnots = [];
  24560. serializationObject.geometries.vertexData = [];
  24561. }
  24562. serializeGeometry(geometry, serializationObject.geometries);
  24563. }
  24564. // Skeletons
  24565. if (mesh.skeleton) {
  24566. serializationObject.skeletons = serializationObject.skeletons || [];
  24567. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24568. }
  24569. //serialize the actual mesh
  24570. serializationObject.meshes = serializationObject.meshes || [];
  24571. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24572. }
  24573. };
  24574. var SceneSerializer = (function () {
  24575. function SceneSerializer() {
  24576. }
  24577. SceneSerializer.Serialize = function (scene) {
  24578. var serializationObject = {};
  24579. // Scene
  24580. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24581. serializationObject.autoClear = scene.autoClear;
  24582. serializationObject.clearColor = scene.clearColor.asArray();
  24583. serializationObject.ambientColor = scene.ambientColor.asArray();
  24584. serializationObject.gravity = scene.gravity.asArray();
  24585. // Fog
  24586. if (scene.fogMode && scene.fogMode !== 0) {
  24587. serializationObject.fogMode = scene.fogMode;
  24588. serializationObject.fogColor = scene.fogColor.asArray();
  24589. serializationObject.fogStart = scene.fogStart;
  24590. serializationObject.fogEnd = scene.fogEnd;
  24591. serializationObject.fogDensity = scene.fogDensity;
  24592. }
  24593. // Lights
  24594. serializationObject.lights = [];
  24595. var index;
  24596. var light;
  24597. for (index = 0; index < scene.lights.length; index++) {
  24598. light = scene.lights[index];
  24599. serializationObject.lights.push(serializeLight(light));
  24600. }
  24601. // Cameras
  24602. serializationObject.cameras = [];
  24603. for (index = 0; index < scene.cameras.length; index++) {
  24604. var camera = scene.cameras[index];
  24605. serializationObject.cameras.push(serializeCamera(camera));
  24606. }
  24607. if (scene.activeCamera) {
  24608. serializationObject.activeCameraID = scene.activeCamera.id;
  24609. }
  24610. // Materials
  24611. serializationObject.materials = [];
  24612. serializationObject.multiMaterials = [];
  24613. var material;
  24614. for (index = 0; index < scene.materials.length; index++) {
  24615. material = scene.materials[index];
  24616. serializationObject.materials.push(serializeMaterial(material));
  24617. }
  24618. // MultiMaterials
  24619. serializationObject.multiMaterials = [];
  24620. for (index = 0; index < scene.multiMaterials.length; index++) {
  24621. var multiMaterial = scene.multiMaterials[index];
  24622. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  24623. }
  24624. for (index = 0; index < scene.materials.length; index++) {
  24625. material = scene.materials[index];
  24626. if (material instanceof BABYLON.StandardMaterial) {
  24627. serializationObject.materials.push(serializeMaterial(material));
  24628. }
  24629. else if (material instanceof BABYLON.MultiMaterial) {
  24630. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24631. }
  24632. }
  24633. // Skeletons
  24634. serializationObject.skeletons = [];
  24635. for (index = 0; index < scene.skeletons.length; index++) {
  24636. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24637. }
  24638. // Geometries
  24639. serializationObject.geometries = {};
  24640. serializationObject.geometries.boxes = [];
  24641. serializationObject.geometries.spheres = [];
  24642. serializationObject.geometries.cylinders = [];
  24643. serializationObject.geometries.toruses = [];
  24644. serializationObject.geometries.grounds = [];
  24645. serializationObject.geometries.planes = [];
  24646. serializationObject.geometries.torusKnots = [];
  24647. serializationObject.geometries.vertexData = [];
  24648. serializedGeometries = [];
  24649. var geometries = scene.getGeometries();
  24650. for (index = 0; index < geometries.length; index++) {
  24651. var geometry = geometries[index];
  24652. if (geometry.isReady()) {
  24653. serializeGeometry(geometry, serializationObject.geometries);
  24654. }
  24655. }
  24656. // Meshes
  24657. serializationObject.meshes = [];
  24658. for (index = 0; index < scene.meshes.length; index++) {
  24659. var abstractMesh = scene.meshes[index];
  24660. if (abstractMesh instanceof BABYLON.Mesh) {
  24661. var mesh = abstractMesh;
  24662. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24663. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24664. }
  24665. }
  24666. }
  24667. // Particles Systems
  24668. serializationObject.particleSystems = [];
  24669. for (index = 0; index < scene.particleSystems.length; index++) {
  24670. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24671. }
  24672. // Lens flares
  24673. serializationObject.lensFlareSystems = [];
  24674. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24675. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24676. }
  24677. // Shadows
  24678. serializationObject.shadowGenerators = [];
  24679. for (index = 0; index < scene.lights.length; index++) {
  24680. light = scene.lights[index];
  24681. if (light.getShadowGenerator()) {
  24682. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24683. }
  24684. }
  24685. return serializationObject;
  24686. };
  24687. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24688. if (withParents === void 0) { withParents = false; }
  24689. if (withChildren === void 0) { withChildren = false; }
  24690. var serializationObject = {};
  24691. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24692. if (withParents || withChildren) {
  24693. //deliberate for loop! not for each, appended should be processed as well.
  24694. for (var i = 0; i < toSerialize.length; ++i) {
  24695. if (withChildren) {
  24696. toSerialize[i].getDescendants().forEach(function (node) {
  24697. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24698. toSerialize.push(node);
  24699. }
  24700. });
  24701. }
  24702. //make sure the array doesn't contain the object already
  24703. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24704. toSerialize.push(toSerialize[i].parent);
  24705. }
  24706. }
  24707. }
  24708. toSerialize.forEach(function (mesh) {
  24709. finalizeSingleMesh(mesh, serializationObject);
  24710. });
  24711. return serializationObject;
  24712. };
  24713. return SceneSerializer;
  24714. })();
  24715. BABYLON.SceneSerializer = SceneSerializer;
  24716. })(BABYLON || (BABYLON = {}));
  24717. var BABYLON;
  24718. (function (BABYLON) {
  24719. // Unique ID when we import meshes from Babylon to CSG
  24720. var currentCSGMeshId = 0;
  24721. // # class Vertex
  24722. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24723. // one to provide additional features like texture coordinates and vertex
  24724. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24725. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24726. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24727. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24728. // is not used anywhere else.
  24729. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24730. var Vertex = (function () {
  24731. function Vertex(pos, normal, uv) {
  24732. this.pos = pos;
  24733. this.normal = normal;
  24734. this.uv = uv;
  24735. }
  24736. Vertex.prototype.clone = function () {
  24737. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24738. };
  24739. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24740. // orientation of a polygon is flipped.
  24741. Vertex.prototype.flip = function () {
  24742. this.normal = this.normal.scale(-1);
  24743. };
  24744. // Create a new vertex between this vertex and `other` by linearly
  24745. // interpolating all properties using a parameter of `t`. Subclasses should
  24746. // override this to interpolate additional properties.
  24747. Vertex.prototype.interpolate = function (other, t) {
  24748. 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));
  24749. };
  24750. return Vertex;
  24751. })();
  24752. // # class Plane
  24753. // Represents a plane in 3D space.
  24754. var Plane = (function () {
  24755. function Plane(normal, w) {
  24756. this.normal = normal;
  24757. this.w = w;
  24758. }
  24759. Plane.FromPoints = function (a, b, c) {
  24760. var v0 = c.subtract(a);
  24761. var v1 = b.subtract(a);
  24762. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24763. return null;
  24764. }
  24765. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24766. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24767. };
  24768. Plane.prototype.clone = function () {
  24769. return new Plane(this.normal.clone(), this.w);
  24770. };
  24771. Plane.prototype.flip = function () {
  24772. this.normal.scaleInPlace(-1);
  24773. this.w = -this.w;
  24774. };
  24775. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24776. // fragments in the appropriate lists. Coplanar polygons go into either
  24777. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24778. // respect to this plane. Polygons in front or in back of this plane go into
  24779. // either `front` or `back`.
  24780. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24781. var COPLANAR = 0;
  24782. var FRONT = 1;
  24783. var BACK = 2;
  24784. var SPANNING = 3;
  24785. // Classify each point as well as the entire polygon into one of the above
  24786. // four classes.
  24787. var polygonType = 0;
  24788. var types = [];
  24789. for (var i = 0; i < polygon.vertices.length; i++) {
  24790. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24791. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24792. polygonType |= type;
  24793. types.push(type);
  24794. }
  24795. // Put the polygon in the correct list, splitting it when necessary.
  24796. switch (polygonType) {
  24797. case COPLANAR:
  24798. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24799. break;
  24800. case FRONT:
  24801. front.push(polygon);
  24802. break;
  24803. case BACK:
  24804. back.push(polygon);
  24805. break;
  24806. case SPANNING:
  24807. var f = [], b = [];
  24808. for (i = 0; i < polygon.vertices.length; i++) {
  24809. var j = (i + 1) % polygon.vertices.length;
  24810. var ti = types[i], tj = types[j];
  24811. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24812. if (ti != BACK)
  24813. f.push(vi);
  24814. if (ti != FRONT)
  24815. b.push(ti != BACK ? vi.clone() : vi);
  24816. if ((ti | tj) == SPANNING) {
  24817. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24818. var v = vi.interpolate(vj, t);
  24819. f.push(v);
  24820. b.push(v.clone());
  24821. }
  24822. }
  24823. if (f.length >= 3) {
  24824. var poly = new Polygon(f, polygon.shared);
  24825. if (poly.plane)
  24826. front.push(poly);
  24827. }
  24828. if (b.length >= 3) {
  24829. poly = new Polygon(b, polygon.shared);
  24830. if (poly.plane)
  24831. back.push(poly);
  24832. }
  24833. break;
  24834. }
  24835. };
  24836. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24837. // point is on the plane.
  24838. Plane.EPSILON = 1e-5;
  24839. return Plane;
  24840. })();
  24841. // # class Polygon
  24842. // Represents a convex polygon. The vertices used to initialize a polygon must
  24843. // be coplanar and form a convex loop.
  24844. //
  24845. // Each convex polygon has a `shared` property, which is shared between all
  24846. // polygons that are clones of each other or were split from the same polygon.
  24847. // This can be used to define per-polygon properties (such as surface color).
  24848. var Polygon = (function () {
  24849. function Polygon(vertices, shared) {
  24850. this.vertices = vertices;
  24851. this.shared = shared;
  24852. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24853. }
  24854. Polygon.prototype.clone = function () {
  24855. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24856. return new Polygon(vertices, this.shared);
  24857. };
  24858. Polygon.prototype.flip = function () {
  24859. this.vertices.reverse().map(function (v) { v.flip(); });
  24860. this.plane.flip();
  24861. };
  24862. return Polygon;
  24863. })();
  24864. // # class Node
  24865. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24866. // by picking a polygon to split along. That polygon (and all other coplanar
  24867. // polygons) are added directly to that node and the other polygons are added to
  24868. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24869. // no distinction between internal and leaf nodes.
  24870. var Node = (function () {
  24871. function Node(polygons) {
  24872. this.plane = null;
  24873. this.front = null;
  24874. this.back = null;
  24875. this.polygons = [];
  24876. if (polygons) {
  24877. this.build(polygons);
  24878. }
  24879. }
  24880. Node.prototype.clone = function () {
  24881. var node = new Node();
  24882. node.plane = this.plane && this.plane.clone();
  24883. node.front = this.front && this.front.clone();
  24884. node.back = this.back && this.back.clone();
  24885. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24886. return node;
  24887. };
  24888. // Convert solid space to empty space and empty space to solid space.
  24889. Node.prototype.invert = function () {
  24890. for (var i = 0; i < this.polygons.length; i++) {
  24891. this.polygons[i].flip();
  24892. }
  24893. if (this.plane) {
  24894. this.plane.flip();
  24895. }
  24896. if (this.front) {
  24897. this.front.invert();
  24898. }
  24899. if (this.back) {
  24900. this.back.invert();
  24901. }
  24902. var temp = this.front;
  24903. this.front = this.back;
  24904. this.back = temp;
  24905. };
  24906. // Recursively remove all polygons in `polygons` that are inside this BSP
  24907. // tree.
  24908. Node.prototype.clipPolygons = function (polygons) {
  24909. if (!this.plane)
  24910. return polygons.slice();
  24911. var front = [], back = [];
  24912. for (var i = 0; i < polygons.length; i++) {
  24913. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24914. }
  24915. if (this.front) {
  24916. front = this.front.clipPolygons(front);
  24917. }
  24918. if (this.back) {
  24919. back = this.back.clipPolygons(back);
  24920. }
  24921. else {
  24922. back = [];
  24923. }
  24924. return front.concat(back);
  24925. };
  24926. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24927. // `bsp`.
  24928. Node.prototype.clipTo = function (bsp) {
  24929. this.polygons = bsp.clipPolygons(this.polygons);
  24930. if (this.front)
  24931. this.front.clipTo(bsp);
  24932. if (this.back)
  24933. this.back.clipTo(bsp);
  24934. };
  24935. // Return a list of all polygons in this BSP tree.
  24936. Node.prototype.allPolygons = function () {
  24937. var polygons = this.polygons.slice();
  24938. if (this.front)
  24939. polygons = polygons.concat(this.front.allPolygons());
  24940. if (this.back)
  24941. polygons = polygons.concat(this.back.allPolygons());
  24942. return polygons;
  24943. };
  24944. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24945. // new polygons are filtered down to the bottom of the tree and become new
  24946. // nodes there. Each set of polygons is partitioned using the first polygon
  24947. // (no heuristic is used to pick a good split).
  24948. Node.prototype.build = function (polygons) {
  24949. if (!polygons.length)
  24950. return;
  24951. if (!this.plane)
  24952. this.plane = polygons[0].plane.clone();
  24953. var front = [], back = [];
  24954. for (var i = 0; i < polygons.length; i++) {
  24955. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24956. }
  24957. if (front.length) {
  24958. if (!this.front)
  24959. this.front = new Node();
  24960. this.front.build(front);
  24961. }
  24962. if (back.length) {
  24963. if (!this.back)
  24964. this.back = new Node();
  24965. this.back.build(back);
  24966. }
  24967. };
  24968. return Node;
  24969. })();
  24970. var CSG = (function () {
  24971. function CSG() {
  24972. this.polygons = new Array();
  24973. }
  24974. // Convert BABYLON.Mesh to BABYLON.CSG
  24975. CSG.FromMesh = function (mesh) {
  24976. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24977. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24978. if (mesh instanceof BABYLON.Mesh) {
  24979. mesh.computeWorldMatrix(true);
  24980. matrix = mesh.getWorldMatrix();
  24981. meshPosition = mesh.position.clone();
  24982. meshRotation = mesh.rotation.clone();
  24983. if (mesh.rotationQuaternion) {
  24984. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24985. }
  24986. meshScaling = mesh.scaling.clone();
  24987. }
  24988. else {
  24989. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24990. }
  24991. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24992. var subMeshes = mesh.subMeshes;
  24993. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24994. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24995. vertices = [];
  24996. for (var j = 0; j < 3; j++) {
  24997. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24998. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24999. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25000. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25001. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25002. vertex = new Vertex(position, normal, uv);
  25003. vertices.push(vertex);
  25004. }
  25005. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25006. // To handle the case of degenerated triangle
  25007. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25008. if (polygon.plane)
  25009. polygons.push(polygon);
  25010. }
  25011. }
  25012. var csg = CSG.FromPolygons(polygons);
  25013. csg.matrix = matrix;
  25014. csg.position = meshPosition;
  25015. csg.rotation = meshRotation;
  25016. csg.scaling = meshScaling;
  25017. csg.rotationQuaternion = meshRotationQuaternion;
  25018. currentCSGMeshId++;
  25019. return csg;
  25020. };
  25021. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25022. CSG.FromPolygons = function (polygons) {
  25023. var csg = new CSG();
  25024. csg.polygons = polygons;
  25025. return csg;
  25026. };
  25027. CSG.prototype.clone = function () {
  25028. var csg = new CSG();
  25029. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25030. csg.copyTransformAttributes(this);
  25031. return csg;
  25032. };
  25033. CSG.prototype.toPolygons = function () {
  25034. return this.polygons;
  25035. };
  25036. CSG.prototype.union = function (csg) {
  25037. var a = new Node(this.clone().polygons);
  25038. var b = new Node(csg.clone().polygons);
  25039. a.clipTo(b);
  25040. b.clipTo(a);
  25041. b.invert();
  25042. b.clipTo(a);
  25043. b.invert();
  25044. a.build(b.allPolygons());
  25045. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25046. };
  25047. CSG.prototype.unionInPlace = function (csg) {
  25048. var a = new Node(this.polygons);
  25049. var b = new Node(csg.polygons);
  25050. a.clipTo(b);
  25051. b.clipTo(a);
  25052. b.invert();
  25053. b.clipTo(a);
  25054. b.invert();
  25055. a.build(b.allPolygons());
  25056. this.polygons = a.allPolygons();
  25057. };
  25058. CSG.prototype.subtract = function (csg) {
  25059. var a = new Node(this.clone().polygons);
  25060. var b = new Node(csg.clone().polygons);
  25061. a.invert();
  25062. a.clipTo(b);
  25063. b.clipTo(a);
  25064. b.invert();
  25065. b.clipTo(a);
  25066. b.invert();
  25067. a.build(b.allPolygons());
  25068. a.invert();
  25069. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25070. };
  25071. CSG.prototype.subtractInPlace = function (csg) {
  25072. var a = new Node(this.polygons);
  25073. var b = new Node(csg.polygons);
  25074. a.invert();
  25075. a.clipTo(b);
  25076. b.clipTo(a);
  25077. b.invert();
  25078. b.clipTo(a);
  25079. b.invert();
  25080. a.build(b.allPolygons());
  25081. a.invert();
  25082. this.polygons = a.allPolygons();
  25083. };
  25084. CSG.prototype.intersect = function (csg) {
  25085. var a = new Node(this.clone().polygons);
  25086. var b = new Node(csg.clone().polygons);
  25087. a.invert();
  25088. b.clipTo(a);
  25089. b.invert();
  25090. a.clipTo(b);
  25091. b.clipTo(a);
  25092. a.build(b.allPolygons());
  25093. a.invert();
  25094. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25095. };
  25096. CSG.prototype.intersectInPlace = function (csg) {
  25097. var a = new Node(this.polygons);
  25098. var b = new Node(csg.polygons);
  25099. a.invert();
  25100. b.clipTo(a);
  25101. b.invert();
  25102. a.clipTo(b);
  25103. b.clipTo(a);
  25104. a.build(b.allPolygons());
  25105. a.invert();
  25106. this.polygons = a.allPolygons();
  25107. };
  25108. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25109. // not modified.
  25110. CSG.prototype.inverse = function () {
  25111. var csg = this.clone();
  25112. csg.inverseInPlace();
  25113. return csg;
  25114. };
  25115. CSG.prototype.inverseInPlace = function () {
  25116. this.polygons.map(function (p) { p.flip(); });
  25117. };
  25118. // This is used to keep meshes transformations so they can be restored
  25119. // when we build back a Babylon Mesh
  25120. // NB : All CSG operations are performed in world coordinates
  25121. CSG.prototype.copyTransformAttributes = function (csg) {
  25122. this.matrix = csg.matrix;
  25123. this.position = csg.position;
  25124. this.rotation = csg.rotation;
  25125. this.scaling = csg.scaling;
  25126. this.rotationQuaternion = csg.rotationQuaternion;
  25127. return this;
  25128. };
  25129. // Build Raw mesh from CSG
  25130. // Coordinates here are in world space
  25131. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25132. var matrix = this.matrix.clone();
  25133. matrix.invert();
  25134. 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;
  25135. if (keepSubMeshes) {
  25136. // Sort Polygons, since subMeshes are indices range
  25137. polygons.sort(function (a, b) {
  25138. if (a.shared.meshId === b.shared.meshId) {
  25139. return a.shared.subMeshId - b.shared.subMeshId;
  25140. }
  25141. else {
  25142. return a.shared.meshId - b.shared.meshId;
  25143. }
  25144. });
  25145. }
  25146. for (var i = 0, il = polygons.length; i < il; i++) {
  25147. polygon = polygons[i];
  25148. // Building SubMeshes
  25149. if (!subMesh_dict[polygon.shared.meshId]) {
  25150. subMesh_dict[polygon.shared.meshId] = {};
  25151. }
  25152. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25153. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25154. indexStart: +Infinity,
  25155. indexEnd: -Infinity,
  25156. materialIndex: polygon.shared.materialIndex
  25157. };
  25158. }
  25159. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25160. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25161. polygonIndices[0] = 0;
  25162. polygonIndices[1] = j - 1;
  25163. polygonIndices[2] = j;
  25164. for (var k = 0; k < 3; k++) {
  25165. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25166. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25167. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25168. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25169. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25170. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25171. // Check if 2 points can be merged
  25172. if (!(typeof vertex_idx !== 'undefined' &&
  25173. normals[vertex_idx * 3] === localNormal.x &&
  25174. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25175. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25176. uvs[vertex_idx * 2] === uv.x &&
  25177. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25178. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25179. uvs.push(uv.x, uv.y);
  25180. normals.push(normal.x, normal.y, normal.z);
  25181. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25182. }
  25183. indices.push(vertex_idx);
  25184. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25185. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25186. currentIndex++;
  25187. }
  25188. }
  25189. }
  25190. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25191. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25192. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25193. mesh.setIndices(indices);
  25194. if (keepSubMeshes) {
  25195. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25196. var materialIndexOffset = 0, materialMaxIndex;
  25197. mesh.subMeshes.length = 0;
  25198. for (var m in subMesh_dict) {
  25199. materialMaxIndex = -1;
  25200. for (var sm in subMesh_dict[m]) {
  25201. subMesh_obj = subMesh_dict[m][sm];
  25202. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25203. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25204. }
  25205. materialIndexOffset += ++materialMaxIndex;
  25206. }
  25207. }
  25208. return mesh;
  25209. };
  25210. // Build Mesh from CSG taking material and transforms into account
  25211. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25212. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25213. mesh.material = material;
  25214. mesh.position.copyFrom(this.position);
  25215. mesh.rotation.copyFrom(this.rotation);
  25216. if (this.rotationQuaternion) {
  25217. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25218. }
  25219. mesh.scaling.copyFrom(this.scaling);
  25220. mesh.computeWorldMatrix(true);
  25221. return mesh;
  25222. };
  25223. return CSG;
  25224. })();
  25225. BABYLON.CSG = CSG;
  25226. })(BABYLON || (BABYLON = {}));
  25227. var BABYLON;
  25228. (function (BABYLON) {
  25229. var VRDistortionCorrectionPostProcess = (function (_super) {
  25230. __extends(VRDistortionCorrectionPostProcess, _super);
  25231. //ANY
  25232. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25233. var _this = this;
  25234. _super.call(this, name, "vrDistortionCorrection", [
  25235. 'LensCenter',
  25236. 'Scale',
  25237. 'ScaleIn',
  25238. 'HmdWarpParam'
  25239. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25240. this._isRightEye = isRightEye;
  25241. this._distortionFactors = vrMetrics.distortionK;
  25242. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25243. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25244. this.onSizeChanged = function () {
  25245. _this.aspectRatio = _this.width * .5 / _this.height;
  25246. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25247. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25248. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25249. };
  25250. this.onApply = function (effect) {
  25251. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25252. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25253. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25254. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25255. };
  25256. }
  25257. return VRDistortionCorrectionPostProcess;
  25258. })(BABYLON.PostProcess);
  25259. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25260. })(BABYLON || (BABYLON = {}));
  25261. // Mainly based on these 2 articles :
  25262. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  25263. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25264. var BABYLON;
  25265. (function (BABYLON) {
  25266. (function (JoystickAxis) {
  25267. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25268. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25269. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25270. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25271. var JoystickAxis = BABYLON.JoystickAxis;
  25272. var VirtualJoystick = (function () {
  25273. function VirtualJoystick(leftJoystick) {
  25274. var _this = this;
  25275. if (leftJoystick) {
  25276. this._leftJoystick = true;
  25277. }
  25278. else {
  25279. this._leftJoystick = false;
  25280. }
  25281. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25282. VirtualJoystick._globalJoystickIndex++;
  25283. // By default left & right arrow keys are moving the X
  25284. // and up & down keys are moving the Y
  25285. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25286. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25287. this.reverseLeftRight = false;
  25288. this.reverseUpDown = false;
  25289. // collections of pointers
  25290. this._touches = new BABYLON.SmartCollection();
  25291. this.deltaPosition = BABYLON.Vector3.Zero();
  25292. this._joystickSensibility = 25;
  25293. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25294. this._rotationSpeed = 25;
  25295. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25296. this._rotateOnAxisRelativeToMesh = false;
  25297. this._onResize = function (evt) {
  25298. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25299. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25300. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25301. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25302. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25303. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25304. };
  25305. // injecting a canvas element on top of the canvas 3D game
  25306. if (!VirtualJoystick.vjCanvas) {
  25307. window.addEventListener("resize", this._onResize, false);
  25308. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25309. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25310. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25311. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25312. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25313. VirtualJoystick.vjCanvas.style.width = "100%";
  25314. VirtualJoystick.vjCanvas.style.height = "100%";
  25315. VirtualJoystick.vjCanvas.style.position = "absolute";
  25316. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25317. VirtualJoystick.vjCanvas.style.top = "0px";
  25318. VirtualJoystick.vjCanvas.style.left = "0px";
  25319. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25320. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25321. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25322. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25323. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25324. document.body.appendChild(VirtualJoystick.vjCanvas);
  25325. }
  25326. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25327. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25328. this.pressed = false;
  25329. // default joystick color
  25330. this._joystickColor = "cyan";
  25331. this._joystickPointerID = -1;
  25332. // current joystick position
  25333. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25334. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25335. // origin joystick position
  25336. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25337. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25338. this._onPointerDownHandlerRef = function (evt) {
  25339. _this._onPointerDown(evt);
  25340. };
  25341. this._onPointerMoveHandlerRef = function (evt) {
  25342. _this._onPointerMove(evt);
  25343. };
  25344. this._onPointerOutHandlerRef = function (evt) {
  25345. _this._onPointerUp(evt);
  25346. };
  25347. this._onPointerUpHandlerRef = function (evt) {
  25348. _this._onPointerUp(evt);
  25349. };
  25350. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25351. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25352. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25353. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25354. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25355. evt.preventDefault(); // Disables system menu
  25356. }, false);
  25357. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25358. }
  25359. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25360. this._joystickSensibility = newJoystickSensibility;
  25361. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25362. };
  25363. VirtualJoystick.prototype._onPointerDown = function (e) {
  25364. var positionOnScreenCondition;
  25365. e.preventDefault();
  25366. if (this._leftJoystick === true) {
  25367. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25368. }
  25369. else {
  25370. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25371. }
  25372. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25373. // First contact will be dedicated to the virtual joystick
  25374. this._joystickPointerID = e.pointerId;
  25375. this._joystickPointerStartPos.x = e.clientX;
  25376. this._joystickPointerStartPos.y = e.clientY;
  25377. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25378. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25379. this._deltaJoystickVector.x = 0;
  25380. this._deltaJoystickVector.y = 0;
  25381. this.pressed = true;
  25382. this._touches.add(e.pointerId.toString(), e);
  25383. }
  25384. else {
  25385. // You can only trigger the action buttons with a joystick declared
  25386. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25387. this._action();
  25388. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25389. }
  25390. }
  25391. };
  25392. VirtualJoystick.prototype._onPointerMove = function (e) {
  25393. // If the current pointer is the one associated to the joystick (first touch contact)
  25394. if (this._joystickPointerID == e.pointerId) {
  25395. this._joystickPointerPos.x = e.clientX;
  25396. this._joystickPointerPos.y = e.clientY;
  25397. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25398. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25399. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25400. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25401. switch (this._axisTargetedByLeftAndRight) {
  25402. case JoystickAxis.X:
  25403. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25404. break;
  25405. case JoystickAxis.Y:
  25406. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25407. break;
  25408. case JoystickAxis.Z:
  25409. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25410. break;
  25411. }
  25412. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25413. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25414. switch (this._axisTargetedByUpAndDown) {
  25415. case JoystickAxis.X:
  25416. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25417. break;
  25418. case JoystickAxis.Y:
  25419. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25420. break;
  25421. case JoystickAxis.Z:
  25422. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25423. break;
  25424. }
  25425. }
  25426. else {
  25427. if (this._touches.item(e.pointerId.toString())) {
  25428. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25429. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25430. }
  25431. }
  25432. };
  25433. VirtualJoystick.prototype._onPointerUp = function (e) {
  25434. if (this._joystickPointerID == e.pointerId) {
  25435. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25436. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25437. this._joystickPointerID = -1;
  25438. this.pressed = false;
  25439. }
  25440. else {
  25441. var touch = this._touches.item(e.pointerId.toString());
  25442. if (touch) {
  25443. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25444. }
  25445. }
  25446. this._deltaJoystickVector.x = 0;
  25447. this._deltaJoystickVector.y = 0;
  25448. this._touches.remove(e.pointerId.toString());
  25449. };
  25450. /**
  25451. * Change the color of the virtual joystick
  25452. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25453. */
  25454. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25455. this._joystickColor = newColor;
  25456. };
  25457. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25458. this._action = action;
  25459. };
  25460. // Define which axis you'd like to control for left & right
  25461. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25462. switch (axis) {
  25463. case JoystickAxis.X:
  25464. case JoystickAxis.Y:
  25465. case JoystickAxis.Z:
  25466. this._axisTargetedByLeftAndRight = axis;
  25467. break;
  25468. default:
  25469. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25470. break;
  25471. }
  25472. };
  25473. // Define which axis you'd like to control for up & down
  25474. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25475. switch (axis) {
  25476. case JoystickAxis.X:
  25477. case JoystickAxis.Y:
  25478. case JoystickAxis.Z:
  25479. this._axisTargetedByUpAndDown = axis;
  25480. break;
  25481. default:
  25482. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25483. break;
  25484. }
  25485. };
  25486. VirtualJoystick.prototype._clearCanvas = function () {
  25487. if (this._leftJoystick) {
  25488. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25489. }
  25490. else {
  25491. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25492. }
  25493. };
  25494. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25495. var _this = this;
  25496. if (this.pressed) {
  25497. this._touches.forEach(function (touch) {
  25498. if (touch.pointerId === _this._joystickPointerID) {
  25499. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25500. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25501. VirtualJoystick.vjCanvasContext.beginPath();
  25502. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25503. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25504. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25505. VirtualJoystick.vjCanvasContext.stroke();
  25506. VirtualJoystick.vjCanvasContext.closePath();
  25507. VirtualJoystick.vjCanvasContext.beginPath();
  25508. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25509. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25510. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25511. VirtualJoystick.vjCanvasContext.stroke();
  25512. VirtualJoystick.vjCanvasContext.closePath();
  25513. VirtualJoystick.vjCanvasContext.beginPath();
  25514. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25515. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25516. VirtualJoystick.vjCanvasContext.stroke();
  25517. VirtualJoystick.vjCanvasContext.closePath();
  25518. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25519. }
  25520. else {
  25521. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25522. VirtualJoystick.vjCanvasContext.beginPath();
  25523. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25524. VirtualJoystick.vjCanvasContext.beginPath();
  25525. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25526. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25527. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25528. VirtualJoystick.vjCanvasContext.stroke();
  25529. VirtualJoystick.vjCanvasContext.closePath();
  25530. touch.prevX = touch.x;
  25531. touch.prevY = touch.y;
  25532. }
  25533. ;
  25534. });
  25535. }
  25536. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25537. };
  25538. VirtualJoystick.prototype.releaseCanvas = function () {
  25539. if (VirtualJoystick.vjCanvas) {
  25540. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25541. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25542. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25543. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25544. window.removeEventListener("resize", this._onResize);
  25545. document.body.removeChild(VirtualJoystick.vjCanvas);
  25546. VirtualJoystick.vjCanvas = null;
  25547. }
  25548. };
  25549. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25550. VirtualJoystick._globalJoystickIndex = 0;
  25551. return VirtualJoystick;
  25552. })();
  25553. BABYLON.VirtualJoystick = VirtualJoystick;
  25554. })(BABYLON || (BABYLON = {}));
  25555. var BABYLON;
  25556. (function (BABYLON) {
  25557. // We're mainly based on the logic defined into the FreeCamera code
  25558. var VirtualJoysticksCamera = (function (_super) {
  25559. __extends(VirtualJoysticksCamera, _super);
  25560. function VirtualJoysticksCamera(name, position, scene) {
  25561. _super.call(this, name, position, scene);
  25562. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25563. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25564. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25565. this._leftjoystick.setJoystickSensibility(0.15);
  25566. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25567. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25568. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25569. this._rightjoystick.reverseUpDown = true;
  25570. this._rightjoystick.setJoystickSensibility(0.05);
  25571. this._rightjoystick.setJoystickColor("yellow");
  25572. }
  25573. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25574. return this._leftjoystick;
  25575. };
  25576. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25577. return this._rightjoystick;
  25578. };
  25579. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25580. var speed = this._computeLocalCameraSpeed() * 50;
  25581. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25582. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25583. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25584. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25585. if (!this._leftjoystick.pressed) {
  25586. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25587. }
  25588. if (!this._rightjoystick.pressed) {
  25589. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25590. }
  25591. _super.prototype._checkInputs.call(this);
  25592. };
  25593. VirtualJoysticksCamera.prototype.dispose = function () {
  25594. this._leftjoystick.releaseCanvas();
  25595. _super.prototype.dispose.call(this);
  25596. };
  25597. return VirtualJoysticksCamera;
  25598. })(BABYLON.FreeCamera);
  25599. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25600. })(BABYLON || (BABYLON = {}));
  25601. var BABYLON;
  25602. (function (BABYLON) {
  25603. var ShaderMaterial = (function (_super) {
  25604. __extends(ShaderMaterial, _super);
  25605. function ShaderMaterial(name, scene, shaderPath, options) {
  25606. _super.call(this, name, scene);
  25607. this._textures = new Array();
  25608. this._floats = new Array();
  25609. this._floatsArrays = {};
  25610. this._colors3 = new Array();
  25611. this._colors4 = new Array();
  25612. this._vectors2 = new Array();
  25613. this._vectors3 = new Array();
  25614. this._vectors4 = new Array();
  25615. this._matrices = new Array();
  25616. this._matrices3x3 = new Array();
  25617. this._matrices2x2 = new Array();
  25618. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25619. this._shaderPath = shaderPath;
  25620. options.needAlphaBlending = options.needAlphaBlending || false;
  25621. options.needAlphaTesting = options.needAlphaTesting || false;
  25622. options.attributes = options.attributes || ["position", "normal", "uv"];
  25623. options.uniforms = options.uniforms || ["worldViewProjection"];
  25624. options.samplers = options.samplers || [];
  25625. options.defines = options.defines || [];
  25626. this._options = options;
  25627. }
  25628. ShaderMaterial.prototype.needAlphaBlending = function () {
  25629. return this._options.needAlphaBlending;
  25630. };
  25631. ShaderMaterial.prototype.needAlphaTesting = function () {
  25632. return this._options.needAlphaTesting;
  25633. };
  25634. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25635. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25636. this._options.uniforms.push(uniformName);
  25637. }
  25638. };
  25639. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25640. if (this._options.samplers.indexOf(name) === -1) {
  25641. this._options.samplers.push(name);
  25642. }
  25643. this._textures[name] = texture;
  25644. return this;
  25645. };
  25646. ShaderMaterial.prototype.setFloat = function (name, value) {
  25647. this._checkUniform(name);
  25648. this._floats[name] = value;
  25649. return this;
  25650. };
  25651. ShaderMaterial.prototype.setFloats = function (name, value) {
  25652. this._checkUniform(name);
  25653. this._floatsArrays[name] = value;
  25654. return this;
  25655. };
  25656. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25657. this._checkUniform(name);
  25658. this._colors3[name] = value;
  25659. return this;
  25660. };
  25661. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25662. this._checkUniform(name);
  25663. this._colors4[name] = value;
  25664. return this;
  25665. };
  25666. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25667. this._checkUniform(name);
  25668. this._vectors2[name] = value;
  25669. return this;
  25670. };
  25671. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25672. this._checkUniform(name);
  25673. this._vectors3[name] = value;
  25674. return this;
  25675. };
  25676. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25677. this._checkUniform(name);
  25678. this._vectors4[name] = value;
  25679. return this;
  25680. };
  25681. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25682. this._checkUniform(name);
  25683. this._matrices[name] = value;
  25684. return this;
  25685. };
  25686. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25687. this._checkUniform(name);
  25688. this._matrices3x3[name] = value;
  25689. return this;
  25690. };
  25691. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25692. this._checkUniform(name);
  25693. this._matrices2x2[name] = value;
  25694. return this;
  25695. };
  25696. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25697. var scene = this.getScene();
  25698. var engine = scene.getEngine();
  25699. if (!this.checkReadyOnEveryCall) {
  25700. if (this._renderId === scene.getRenderId()) {
  25701. return true;
  25702. }
  25703. }
  25704. // Instances
  25705. var defines = [];
  25706. var fallbacks = new BABYLON.EffectFallbacks();
  25707. if (useInstances) {
  25708. defines.push("#define INSTANCES");
  25709. }
  25710. for (var index = 0; index < this._options.defines.length; index++) {
  25711. defines.push(this._options.defines[index]);
  25712. }
  25713. // Bones
  25714. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25715. defines.push("#define BONES");
  25716. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25717. defines.push("#define BONES4");
  25718. fallbacks.addFallback(0, "BONES4");
  25719. }
  25720. // Alpha test
  25721. if (engine.getAlphaTesting()) {
  25722. defines.push("#define ALPHATEST");
  25723. }
  25724. var previousEffect = this._effect;
  25725. var join = defines.join("\n");
  25726. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25727. if (!this._effect.isReady()) {
  25728. return false;
  25729. }
  25730. if (previousEffect !== this._effect) {
  25731. scene.resetCachedMaterial();
  25732. }
  25733. this._renderId = scene.getRenderId();
  25734. return true;
  25735. };
  25736. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25737. var scene = this.getScene();
  25738. if (this._options.uniforms.indexOf("world") !== -1) {
  25739. this._effect.setMatrix("world", world);
  25740. }
  25741. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25742. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25743. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25744. }
  25745. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25746. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25747. }
  25748. };
  25749. ShaderMaterial.prototype.bind = function (world, mesh) {
  25750. // Std values
  25751. this.bindOnlyWorldMatrix(world);
  25752. if (this.getScene().getCachedMaterial() !== this) {
  25753. if (this._options.uniforms.indexOf("view") !== -1) {
  25754. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25755. }
  25756. if (this._options.uniforms.indexOf("projection") !== -1) {
  25757. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25758. }
  25759. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25760. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25761. }
  25762. // Bones
  25763. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25764. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25765. }
  25766. // Texture
  25767. for (var name in this._textures) {
  25768. this._effect.setTexture(name, this._textures[name]);
  25769. }
  25770. // Float
  25771. for (name in this._floats) {
  25772. this._effect.setFloat(name, this._floats[name]);
  25773. }
  25774. // Float s
  25775. for (name in this._floatsArrays) {
  25776. this._effect.setArray(name, this._floatsArrays[name]);
  25777. }
  25778. // Color3
  25779. for (name in this._colors3) {
  25780. this._effect.setColor3(name, this._colors3[name]);
  25781. }
  25782. // Color4
  25783. for (name in this._colors4) {
  25784. var color = this._colors4[name];
  25785. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25786. }
  25787. // Vector2
  25788. for (name in this._vectors2) {
  25789. this._effect.setVector2(name, this._vectors2[name]);
  25790. }
  25791. // Vector3
  25792. for (name in this._vectors3) {
  25793. this._effect.setVector3(name, this._vectors3[name]);
  25794. }
  25795. // Vector4
  25796. for (name in this._vectors4) {
  25797. this._effect.setVector4(name, this._vectors4[name]);
  25798. }
  25799. // Matrix
  25800. for (name in this._matrices) {
  25801. this._effect.setMatrix(name, this._matrices[name]);
  25802. }
  25803. // Matrix 3x3
  25804. for (name in this._matrices3x3) {
  25805. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25806. }
  25807. // Matrix 2x2
  25808. for (name in this._matrices2x2) {
  25809. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25810. }
  25811. }
  25812. _super.prototype.bind.call(this, world, mesh);
  25813. };
  25814. ShaderMaterial.prototype.clone = function (name) {
  25815. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25816. return newShaderMaterial;
  25817. };
  25818. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25819. for (var name in this._textures) {
  25820. this._textures[name].dispose();
  25821. }
  25822. this._textures = [];
  25823. _super.prototype.dispose.call(this, forceDisposeEffect);
  25824. };
  25825. return ShaderMaterial;
  25826. })(BABYLON.Material);
  25827. BABYLON.ShaderMaterial = ShaderMaterial;
  25828. })(BABYLON || (BABYLON = {}));
  25829. var BABYLON;
  25830. (function (BABYLON) {
  25831. var VertexData = (function () {
  25832. function VertexData() {
  25833. }
  25834. VertexData.prototype.set = function (data, kind) {
  25835. switch (kind) {
  25836. case BABYLON.VertexBuffer.PositionKind:
  25837. this.positions = data;
  25838. break;
  25839. case BABYLON.VertexBuffer.NormalKind:
  25840. this.normals = data;
  25841. break;
  25842. case BABYLON.VertexBuffer.UVKind:
  25843. this.uvs = data;
  25844. break;
  25845. case BABYLON.VertexBuffer.UV2Kind:
  25846. this.uvs2 = data;
  25847. break;
  25848. case BABYLON.VertexBuffer.UV3Kind:
  25849. this.uvs3 = data;
  25850. break;
  25851. case BABYLON.VertexBuffer.UV4Kind:
  25852. this.uvs4 = data;
  25853. break;
  25854. case BABYLON.VertexBuffer.UV5Kind:
  25855. this.uvs5 = data;
  25856. break;
  25857. case BABYLON.VertexBuffer.UV6Kind:
  25858. this.uvs6 = data;
  25859. break;
  25860. case BABYLON.VertexBuffer.ColorKind:
  25861. this.colors = data;
  25862. break;
  25863. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25864. this.matricesIndices = data;
  25865. break;
  25866. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25867. this.matricesWeights = data;
  25868. break;
  25869. }
  25870. };
  25871. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25872. this._applyTo(mesh, updatable);
  25873. };
  25874. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25875. this._applyTo(geometry, updatable);
  25876. };
  25877. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25878. this._update(mesh);
  25879. };
  25880. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25881. this._update(geometry);
  25882. };
  25883. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25884. if (this.positions) {
  25885. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25886. }
  25887. if (this.normals) {
  25888. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25889. }
  25890. if (this.uvs) {
  25891. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25892. }
  25893. if (this.uvs2) {
  25894. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25895. }
  25896. if (this.uvs3) {
  25897. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25898. }
  25899. if (this.uvs4) {
  25900. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25901. }
  25902. if (this.uvs5) {
  25903. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25904. }
  25905. if (this.uvs6) {
  25906. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25907. }
  25908. if (this.colors) {
  25909. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25910. }
  25911. if (this.matricesIndices) {
  25912. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25913. }
  25914. if (this.matricesWeights) {
  25915. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25916. }
  25917. if (this.indices) {
  25918. meshOrGeometry.setIndices(this.indices);
  25919. }
  25920. };
  25921. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25922. if (this.positions) {
  25923. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25924. }
  25925. if (this.normals) {
  25926. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25927. }
  25928. if (this.uvs) {
  25929. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25930. }
  25931. if (this.uvs2) {
  25932. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25933. }
  25934. if (this.uvs3) {
  25935. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25936. }
  25937. if (this.uvs4) {
  25938. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25939. }
  25940. if (this.uvs5) {
  25941. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25942. }
  25943. if (this.uvs6) {
  25944. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25945. }
  25946. if (this.colors) {
  25947. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25948. }
  25949. if (this.matricesIndices) {
  25950. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25951. }
  25952. if (this.matricesWeights) {
  25953. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25954. }
  25955. if (this.indices) {
  25956. meshOrGeometry.setIndices(this.indices);
  25957. }
  25958. };
  25959. VertexData.prototype.transform = function (matrix) {
  25960. var transformed = BABYLON.Vector3.Zero();
  25961. var index;
  25962. if (this.positions) {
  25963. var position = BABYLON.Vector3.Zero();
  25964. for (index = 0; index < this.positions.length; index += 3) {
  25965. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25966. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25967. this.positions[index] = transformed.x;
  25968. this.positions[index + 1] = transformed.y;
  25969. this.positions[index + 2] = transformed.z;
  25970. }
  25971. }
  25972. if (this.normals) {
  25973. var normal = BABYLON.Vector3.Zero();
  25974. for (index = 0; index < this.normals.length; index += 3) {
  25975. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25976. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25977. this.normals[index] = transformed.x;
  25978. this.normals[index + 1] = transformed.y;
  25979. this.normals[index + 2] = transformed.z;
  25980. }
  25981. }
  25982. };
  25983. VertexData.prototype.merge = function (other) {
  25984. var index;
  25985. if (other.indices) {
  25986. if (!this.indices) {
  25987. this.indices = [];
  25988. }
  25989. var offset = this.positions ? this.positions.length / 3 : 0;
  25990. for (index = 0; index < other.indices.length; index++) {
  25991. this.indices.push(other.indices[index] + offset);
  25992. }
  25993. }
  25994. if (other.positions) {
  25995. if (!this.positions) {
  25996. this.positions = [];
  25997. }
  25998. for (index = 0; index < other.positions.length; index++) {
  25999. this.positions.push(other.positions[index]);
  26000. }
  26001. }
  26002. if (other.normals) {
  26003. if (!this.normals) {
  26004. this.normals = [];
  26005. }
  26006. for (index = 0; index < other.normals.length; index++) {
  26007. this.normals.push(other.normals[index]);
  26008. }
  26009. }
  26010. if (other.uvs) {
  26011. if (!this.uvs) {
  26012. this.uvs = [];
  26013. }
  26014. for (index = 0; index < other.uvs.length; index++) {
  26015. this.uvs.push(other.uvs[index]);
  26016. }
  26017. }
  26018. if (other.uvs2) {
  26019. if (!this.uvs2) {
  26020. this.uvs2 = [];
  26021. }
  26022. for (index = 0; index < other.uvs2.length; index++) {
  26023. this.uvs2.push(other.uvs2[index]);
  26024. }
  26025. }
  26026. if (other.uvs3) {
  26027. if (!this.uvs3) {
  26028. this.uvs3 = [];
  26029. }
  26030. for (index = 0; index < other.uvs3.length; index++) {
  26031. this.uvs3.push(other.uvs3[index]);
  26032. }
  26033. }
  26034. if (other.uvs4) {
  26035. if (!this.uvs4) {
  26036. this.uvs4 = [];
  26037. }
  26038. for (index = 0; index < other.uvs4.length; index++) {
  26039. this.uvs4.push(other.uvs4[index]);
  26040. }
  26041. }
  26042. if (other.uvs5) {
  26043. if (!this.uvs5) {
  26044. this.uvs5 = [];
  26045. }
  26046. for (index = 0; index < other.uvs5.length; index++) {
  26047. this.uvs5.push(other.uvs5[index]);
  26048. }
  26049. }
  26050. if (other.uvs6) {
  26051. if (!this.uvs6) {
  26052. this.uvs6 = [];
  26053. }
  26054. for (index = 0; index < other.uvs6.length; index++) {
  26055. this.uvs6.push(other.uvs6[index]);
  26056. }
  26057. }
  26058. if (other.matricesIndices) {
  26059. if (!this.matricesIndices) {
  26060. this.matricesIndices = [];
  26061. }
  26062. for (index = 0; index < other.matricesIndices.length; index++) {
  26063. this.matricesIndices.push(other.matricesIndices[index]);
  26064. }
  26065. }
  26066. if (other.matricesWeights) {
  26067. if (!this.matricesWeights) {
  26068. this.matricesWeights = [];
  26069. }
  26070. for (index = 0; index < other.matricesWeights.length; index++) {
  26071. this.matricesWeights.push(other.matricesWeights[index]);
  26072. }
  26073. }
  26074. if (other.colors) {
  26075. if (!this.colors) {
  26076. this.colors = [];
  26077. }
  26078. for (index = 0; index < other.colors.length; index++) {
  26079. this.colors.push(other.colors[index]);
  26080. }
  26081. }
  26082. };
  26083. // Statics
  26084. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26085. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26086. };
  26087. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26088. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26089. };
  26090. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26091. var result = new VertexData();
  26092. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26093. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26094. }
  26095. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26096. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26097. }
  26098. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26099. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26100. }
  26101. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26102. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26103. }
  26104. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26105. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26106. }
  26107. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26108. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26109. }
  26110. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26111. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26112. }
  26113. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26114. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26115. }
  26116. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26117. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26118. }
  26119. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26120. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26121. }
  26122. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26123. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26124. }
  26125. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26126. return result;
  26127. };
  26128. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26129. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26130. closeArray = closeArray || false;
  26131. closePath = closePath || false;
  26132. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26133. offset = offset || defaultOffset;
  26134. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26135. var positions = [];
  26136. var indices = [];
  26137. var normals = [];
  26138. var uvs = [];
  26139. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26140. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26141. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26142. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26143. var minlg; // minimal length among all paths from pathArray
  26144. var lg = []; // array of path lengths : nb of vertex per path
  26145. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26146. var p; // path iterator
  26147. var i; // point iterator
  26148. var j; // point iterator
  26149. // if single path in pathArray
  26150. if (pathArray.length < 2) {
  26151. var ar1 = [];
  26152. var ar2 = [];
  26153. for (i = 0; i < pathArray[0].length - offset; i++) {
  26154. ar1.push(pathArray[0][i]);
  26155. ar2.push(pathArray[0][i + offset]);
  26156. }
  26157. pathArray = [ar1, ar2];
  26158. }
  26159. // positions and horizontal distances (u)
  26160. var idc = 0;
  26161. var closePathCorr = (closePath) ? 1 : 0;
  26162. var path;
  26163. var l;
  26164. minlg = pathArray[0].length;
  26165. var vectlg;
  26166. var dist;
  26167. for (p = 0; p < pathArray.length; p++) {
  26168. uTotalDistance[p] = 0;
  26169. us[p] = [0];
  26170. path = pathArray[p];
  26171. l = path.length;
  26172. minlg = (minlg < l) ? minlg : l;
  26173. j = 0;
  26174. while (j < l) {
  26175. positions.push(path[j].x, path[j].y, path[j].z);
  26176. if (j > 0) {
  26177. vectlg = path[j].subtract(path[j - 1]).length();
  26178. dist = vectlg + uTotalDistance[p];
  26179. us[p].push(dist);
  26180. uTotalDistance[p] = dist;
  26181. }
  26182. j++;
  26183. }
  26184. if (closePath) {
  26185. j--;
  26186. positions.push(path[0].x, path[0].y, path[0].z);
  26187. vectlg = path[j].subtract(path[0]).length();
  26188. dist = vectlg + uTotalDistance[p];
  26189. us[p].push(dist);
  26190. uTotalDistance[p] = dist;
  26191. }
  26192. lg[p] = l + closePathCorr;
  26193. idx[p] = idc;
  26194. idc += (l + closePathCorr);
  26195. }
  26196. // vertical distances (v)
  26197. var path1;
  26198. var path2;
  26199. var vertex1;
  26200. var vertex2;
  26201. for (i = 0; i < minlg + closePathCorr; i++) {
  26202. vTotalDistance[i] = 0;
  26203. vs[i] = [0];
  26204. for (p = 0; p < pathArray.length - 1; p++) {
  26205. path1 = pathArray[p];
  26206. path2 = pathArray[p + 1];
  26207. if (i === minlg) {
  26208. vertex1 = path1[0];
  26209. vertex2 = path2[0];
  26210. }
  26211. else {
  26212. vertex1 = path1[i];
  26213. vertex2 = path2[i];
  26214. }
  26215. vectlg = vertex2.subtract(vertex1).length();
  26216. dist = vectlg + vTotalDistance[i];
  26217. vs[i].push(dist);
  26218. vTotalDistance[i] = dist;
  26219. }
  26220. if (closeArray) {
  26221. path1 = pathArray[p];
  26222. path2 = pathArray[0];
  26223. vectlg = path2[i].subtract(path1[i]).length();
  26224. dist = vectlg + vTotalDistance[i];
  26225. vTotalDistance[i] = dist;
  26226. }
  26227. }
  26228. // uvs
  26229. var u;
  26230. var v;
  26231. for (p = 0; p < pathArray.length; p++) {
  26232. for (i = 0; i < minlg + closePathCorr; i++) {
  26233. u = us[p][i] / uTotalDistance[p];
  26234. v = vs[i][p] / vTotalDistance[i];
  26235. uvs.push(u, v);
  26236. }
  26237. }
  26238. // indices
  26239. p = 0; // path index
  26240. var pi = 0; // positions array index
  26241. var l1 = lg[p] - 1; // path1 length
  26242. var l2 = lg[p + 1] - 1; // path2 length
  26243. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26244. var shft = idx[1] - idx[0]; // shift
  26245. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26246. while (pi <= min && p < path1nb) {
  26247. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  26248. indices.push(pi, pi + shft, pi + 1);
  26249. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26250. pi += 1;
  26251. if (pi === min) {
  26252. p++;
  26253. if (p === lg.length - 1) {
  26254. shft = idx[0] - idx[p];
  26255. l1 = lg[p] - 1;
  26256. l2 = lg[0] - 1;
  26257. }
  26258. else {
  26259. shft = idx[p + 1] - idx[p];
  26260. l1 = lg[p] - 1;
  26261. l2 = lg[p + 1] - 1;
  26262. }
  26263. pi = idx[p];
  26264. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26265. }
  26266. }
  26267. // normals
  26268. VertexData.ComputeNormals(positions, indices, normals);
  26269. if (closePath) {
  26270. var indexFirst = 0;
  26271. var indexLast = 0;
  26272. for (p = 0; p < pathArray.length; p++) {
  26273. indexFirst = idx[p] * 3;
  26274. if (p + 1 < pathArray.length) {
  26275. indexLast = (idx[p + 1] - 1) * 3;
  26276. }
  26277. else {
  26278. indexLast = normals.length - 3;
  26279. }
  26280. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26281. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26282. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26283. normals[indexLast] = normals[indexFirst];
  26284. normals[indexLast + 1] = normals[indexFirst + 1];
  26285. normals[indexLast + 2] = normals[indexFirst + 2];
  26286. }
  26287. }
  26288. // sides
  26289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26290. // Result
  26291. var vertexData = new VertexData();
  26292. vertexData.indices = indices;
  26293. vertexData.positions = positions;
  26294. vertexData.normals = normals;
  26295. vertexData.uvs = uvs;
  26296. if (closePath) {
  26297. vertexData._idx = idx;
  26298. }
  26299. return vertexData;
  26300. };
  26301. VertexData.CreateBox = function (options, sideOrientation) {
  26302. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26303. var normalsSource = [
  26304. new BABYLON.Vector3(0, 0, 1),
  26305. new BABYLON.Vector3(0, 0, -1),
  26306. new BABYLON.Vector3(1, 0, 0),
  26307. new BABYLON.Vector3(-1, 0, 0),
  26308. new BABYLON.Vector3(0, 1, 0),
  26309. new BABYLON.Vector3(0, -1, 0)
  26310. ];
  26311. var indices = [];
  26312. var positions = [];
  26313. var normals = [];
  26314. var uvs = [];
  26315. var width = 1;
  26316. var height = 1;
  26317. var depth = 1;
  26318. if (options.width !== undefined) {
  26319. width = options.width || 1;
  26320. height = options.height || 1;
  26321. depth = options.depth || 1;
  26322. }
  26323. else {
  26324. width = options || 1;
  26325. height = options || 1;
  26326. depth = options || 1;
  26327. }
  26328. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26329. // Create each face in turn.
  26330. for (var index = 0; index < normalsSource.length; index++) {
  26331. var normal = normalsSource[index];
  26332. // Get two vectors perpendicular to the face normal and to each other.
  26333. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26334. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26335. // Six indices (two triangles) per face.
  26336. var verticesLength = positions.length / 3;
  26337. indices.push(verticesLength);
  26338. indices.push(verticesLength + 1);
  26339. indices.push(verticesLength + 2);
  26340. indices.push(verticesLength);
  26341. indices.push(verticesLength + 2);
  26342. indices.push(verticesLength + 3);
  26343. // Four vertices per face.
  26344. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26345. positions.push(vertex.x, vertex.y, vertex.z);
  26346. normals.push(normal.x, normal.y, normal.z);
  26347. uvs.push(1.0, 1.0);
  26348. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26349. positions.push(vertex.x, vertex.y, vertex.z);
  26350. normals.push(normal.x, normal.y, normal.z);
  26351. uvs.push(0.0, 1.0);
  26352. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26353. positions.push(vertex.x, vertex.y, vertex.z);
  26354. normals.push(normal.x, normal.y, normal.z);
  26355. uvs.push(0.0, 0.0);
  26356. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26357. positions.push(vertex.x, vertex.y, vertex.z);
  26358. normals.push(normal.x, normal.y, normal.z);
  26359. uvs.push(1.0, 0.0);
  26360. }
  26361. // sides
  26362. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26363. // Result
  26364. var vertexData = new VertexData();
  26365. vertexData.indices = indices;
  26366. vertexData.positions = positions;
  26367. vertexData.normals = normals;
  26368. vertexData.uvs = uvs;
  26369. return vertexData;
  26370. };
  26371. VertexData.CreateSphere = function (options, diameter, sideOrientation) {
  26372. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26373. var segments;
  26374. var diameterX;
  26375. var diameterY;
  26376. var diameterZ;
  26377. if (options.segments) {
  26378. segments = options.segments || 32;
  26379. diameterX = options.diameterX || 1;
  26380. diameterY = options.diameterY || 1;
  26381. diameterZ = options.diameterZ || 1;
  26382. }
  26383. else {
  26384. segments = options || 32;
  26385. diameterX = diameter || 1;
  26386. diameterY = diameterX;
  26387. diameterZ = diameterX;
  26388. }
  26389. sideOrientation = sideOrientation || options.sideOrientation;
  26390. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26391. var totalZRotationSteps = 2 + segments;
  26392. var totalYRotationSteps = 2 * totalZRotationSteps;
  26393. var indices = [];
  26394. var positions = [];
  26395. var normals = [];
  26396. var uvs = [];
  26397. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26398. var normalizedZ = zRotationStep / totalZRotationSteps;
  26399. var angleZ = (normalizedZ * Math.PI);
  26400. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26401. var normalizedY = yRotationStep / totalYRotationSteps;
  26402. var angleY = normalizedY * Math.PI * 2;
  26403. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26404. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26405. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26406. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26407. var vertex = complete.multiply(radius);
  26408. var normal = BABYLON.Vector3.Normalize(vertex);
  26409. positions.push(vertex.x, vertex.y, vertex.z);
  26410. normals.push(normal.x, normal.y, normal.z);
  26411. uvs.push(normalizedZ, normalizedY);
  26412. }
  26413. if (zRotationStep > 0) {
  26414. var verticesCount = positions.length / 3;
  26415. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26416. indices.push((firstIndex));
  26417. indices.push((firstIndex + 1));
  26418. indices.push(firstIndex + totalYRotationSteps + 1);
  26419. indices.push((firstIndex + totalYRotationSteps + 1));
  26420. indices.push((firstIndex + 1));
  26421. indices.push((firstIndex + totalYRotationSteps + 2));
  26422. }
  26423. }
  26424. }
  26425. // Sides
  26426. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26427. // Result
  26428. var vertexData = new VertexData();
  26429. vertexData.indices = indices;
  26430. vertexData.positions = positions;
  26431. vertexData.normals = normals;
  26432. vertexData.uvs = uvs;
  26433. return vertexData;
  26434. };
  26435. // Cylinder and cone (made using ribbons)
  26436. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26437. if (subdivisions === void 0) { subdivisions = 1; }
  26438. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26439. var indices = [];
  26440. var positions = [];
  26441. var normals = [];
  26442. var uvs = [];
  26443. var angle_step = Math.PI * 2 / tessellation;
  26444. var angle;
  26445. var h;
  26446. var radius;
  26447. var tan = (diameterBottom - diameterTop) / 2 / height;
  26448. var ringVertex = BABYLON.Vector3.Zero();
  26449. var ringNormal = BABYLON.Vector3.Zero();
  26450. // positions, normals, uvs
  26451. var i;
  26452. var j;
  26453. for (i = 0; i <= subdivisions; i++) {
  26454. h = i / subdivisions;
  26455. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26456. for (j = 0; j <= tessellation; j++) {
  26457. angle = j * angle_step;
  26458. ringVertex.x = Math.cos(-angle) * radius;
  26459. ringVertex.y = -height / 2 + h * height;
  26460. ringVertex.z = Math.sin(-angle) * radius;
  26461. if (diameterTop === 0 && i === subdivisions) {
  26462. // if no top cap, reuse former normals
  26463. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26464. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26465. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26466. }
  26467. else {
  26468. ringNormal.x = ringVertex.x;
  26469. ringNormal.z = ringVertex.z;
  26470. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26471. ringNormal.normalize();
  26472. }
  26473. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26474. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26475. uvs.push(j / tessellation, 1 - h);
  26476. }
  26477. }
  26478. // indices
  26479. for (i = 0; i < subdivisions; i++) {
  26480. for (j = 0; j < tessellation; j++) {
  26481. var i0 = i * (tessellation + 1) + j;
  26482. var i1 = (i + 1) * (tessellation + 1) + j;
  26483. var i2 = i * (tessellation + 1) + (j + 1);
  26484. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  26485. indices.push(i0, i1, i2);
  26486. indices.push(i3, i2, i1);
  26487. }
  26488. }
  26489. // Caps
  26490. var createCylinderCap = function (isTop) {
  26491. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26492. if (radius === 0) {
  26493. return;
  26494. }
  26495. var vbase = positions.length / 3;
  26496. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26497. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26498. // Cap positions, normals & uvs
  26499. var angle;
  26500. var circleVector;
  26501. var i;
  26502. for (i = 0; i < tessellation; i++) {
  26503. angle = Math.PI * 2 * i / tessellation;
  26504. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26505. var position = circleVector.scale(radius).add(offset);
  26506. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26507. positions.push(position.x, position.y, position.z);
  26508. normals.push(0, isTop ? 1 : -1, 0);
  26509. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26510. }
  26511. // Cap indices
  26512. for (i = 0; i < tessellation - 2; i++) {
  26513. if (!isTop) {
  26514. indices.push(vbase);
  26515. indices.push(vbase + (i + 1) % tessellation);
  26516. indices.push(vbase + (i + 2) % tessellation);
  26517. }
  26518. else {
  26519. indices.push(vbase);
  26520. indices.push(vbase + (i + 2) % tessellation);
  26521. indices.push(vbase + (i + 1) % tessellation);
  26522. }
  26523. }
  26524. };
  26525. // add caps to geometry
  26526. createCylinderCap(true);
  26527. createCylinderCap(false);
  26528. // Sides
  26529. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26530. var vertexData = new VertexData();
  26531. vertexData.indices = indices;
  26532. vertexData.positions = positions;
  26533. vertexData.normals = normals;
  26534. vertexData.uvs = uvs;
  26535. return vertexData;
  26536. };
  26537. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26538. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26539. var indices = [];
  26540. var positions = [];
  26541. var normals = [];
  26542. var uvs = [];
  26543. diameter = diameter || 1;
  26544. thickness = thickness || 0.5;
  26545. tessellation = tessellation || 16;
  26546. var stride = tessellation + 1;
  26547. for (var i = 0; i <= tessellation; i++) {
  26548. var u = i / tessellation;
  26549. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26550. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26551. for (var j = 0; j <= tessellation; j++) {
  26552. var v = 1 - j / tessellation;
  26553. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26554. var dx = Math.cos(innerAngle);
  26555. var dy = Math.sin(innerAngle);
  26556. // Create a vertex.
  26557. var normal = new BABYLON.Vector3(dx, dy, 0);
  26558. var position = normal.scale(thickness / 2);
  26559. var textureCoordinate = new BABYLON.Vector2(u, v);
  26560. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26561. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26562. positions.push(position.x, position.y, position.z);
  26563. normals.push(normal.x, normal.y, normal.z);
  26564. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26565. // And create indices for two triangles.
  26566. var nextI = (i + 1) % stride;
  26567. var nextJ = (j + 1) % stride;
  26568. indices.push(i * stride + j);
  26569. indices.push(i * stride + nextJ);
  26570. indices.push(nextI * stride + j);
  26571. indices.push(i * stride + nextJ);
  26572. indices.push(nextI * stride + nextJ);
  26573. indices.push(nextI * stride + j);
  26574. }
  26575. }
  26576. // Sides
  26577. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26578. // Result
  26579. var vertexData = new VertexData();
  26580. vertexData.indices = indices;
  26581. vertexData.positions = positions;
  26582. vertexData.normals = normals;
  26583. vertexData.uvs = uvs;
  26584. return vertexData;
  26585. };
  26586. VertexData.CreateLines = function (points) {
  26587. var indices = [];
  26588. var positions = [];
  26589. for (var index = 0; index < points.length; index++) {
  26590. positions.push(points[index].x, points[index].y, points[index].z);
  26591. if (index > 0) {
  26592. indices.push(index - 1);
  26593. indices.push(index);
  26594. }
  26595. }
  26596. // Result
  26597. var vertexData = new VertexData();
  26598. vertexData.indices = indices;
  26599. vertexData.positions = positions;
  26600. return vertexData;
  26601. };
  26602. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26603. dashSize = dashSize || 3;
  26604. gapSize = gapSize || 1;
  26605. dashNb = dashNb || 200;
  26606. var positions = new Array();
  26607. var indices = new Array();
  26608. var curvect = BABYLON.Vector3.Zero();
  26609. var lg = 0;
  26610. var nb = 0;
  26611. var shft = 0;
  26612. var dashshft = 0;
  26613. var curshft = 0;
  26614. var idx = 0;
  26615. var i = 0;
  26616. for (i = 0; i < points.length - 1; i++) {
  26617. points[i + 1].subtractToRef(points[i], curvect);
  26618. lg += curvect.length();
  26619. }
  26620. shft = lg / dashNb;
  26621. dashshft = dashSize * shft / (dashSize + gapSize);
  26622. for (i = 0; i < points.length - 1; i++) {
  26623. points[i + 1].subtractToRef(points[i], curvect);
  26624. nb = Math.floor(curvect.length() / shft);
  26625. curvect.normalize();
  26626. for (var j = 0; j < nb; j++) {
  26627. curshft = shft * j;
  26628. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26629. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26630. indices.push(idx, idx + 1);
  26631. idx += 2;
  26632. }
  26633. }
  26634. // Result
  26635. var vertexData = new VertexData();
  26636. vertexData.positions = positions;
  26637. vertexData.indices = indices;
  26638. return vertexData;
  26639. };
  26640. VertexData.CreateGround = function (width, height, subdivisions) {
  26641. var indices = [];
  26642. var positions = [];
  26643. var normals = [];
  26644. var uvs = [];
  26645. var row, col;
  26646. width = width || 1;
  26647. height = height || 1;
  26648. subdivisions = subdivisions || 1;
  26649. for (row = 0; row <= subdivisions; row++) {
  26650. for (col = 0; col <= subdivisions; col++) {
  26651. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26652. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26653. positions.push(position.x, position.y, position.z);
  26654. normals.push(normal.x, normal.y, normal.z);
  26655. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26656. }
  26657. }
  26658. for (row = 0; row < subdivisions; row++) {
  26659. for (col = 0; col < subdivisions; col++) {
  26660. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26661. indices.push(col + 1 + row * (subdivisions + 1));
  26662. indices.push(col + row * (subdivisions + 1));
  26663. indices.push(col + (row + 1) * (subdivisions + 1));
  26664. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26665. indices.push(col + row * (subdivisions + 1));
  26666. }
  26667. }
  26668. // Result
  26669. var vertexData = new VertexData();
  26670. vertexData.indices = indices;
  26671. vertexData.positions = positions;
  26672. vertexData.normals = normals;
  26673. vertexData.uvs = uvs;
  26674. return vertexData;
  26675. };
  26676. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26677. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26678. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26679. var indices = [];
  26680. var positions = [];
  26681. var normals = [];
  26682. var uvs = [];
  26683. var row, col, tileRow, tileCol;
  26684. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26685. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26686. precision.w = (precision.w < 1) ? 1 : precision.w;
  26687. precision.h = (precision.h < 1) ? 1 : precision.h;
  26688. var tileSize = {
  26689. 'w': (xmax - xmin) / subdivisions.w,
  26690. 'h': (zmax - zmin) / subdivisions.h
  26691. };
  26692. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26693. // Indices
  26694. var base = positions.length / 3;
  26695. var rowLength = precision.w + 1;
  26696. for (row = 0; row < precision.h; row++) {
  26697. for (col = 0; col < precision.w; col++) {
  26698. var square = [
  26699. base + col + row * rowLength,
  26700. base + (col + 1) + row * rowLength,
  26701. base + (col + 1) + (row + 1) * rowLength,
  26702. base + col + (row + 1) * rowLength
  26703. ];
  26704. indices.push(square[1]);
  26705. indices.push(square[2]);
  26706. indices.push(square[3]);
  26707. indices.push(square[0]);
  26708. indices.push(square[1]);
  26709. indices.push(square[3]);
  26710. }
  26711. }
  26712. // Position, normals and uvs
  26713. var position = BABYLON.Vector3.Zero();
  26714. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26715. for (row = 0; row <= precision.h; row++) {
  26716. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26717. for (col = 0; col <= precision.w; col++) {
  26718. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26719. position.y = 0;
  26720. positions.push(position.x, position.y, position.z);
  26721. normals.push(normal.x, normal.y, normal.z);
  26722. uvs.push(col / precision.w, row / precision.h);
  26723. }
  26724. }
  26725. }
  26726. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26727. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26728. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26729. }
  26730. }
  26731. // Result
  26732. var vertexData = new VertexData();
  26733. vertexData.indices = indices;
  26734. vertexData.positions = positions;
  26735. vertexData.normals = normals;
  26736. vertexData.uvs = uvs;
  26737. return vertexData;
  26738. };
  26739. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26740. var indices = [];
  26741. var positions = [];
  26742. var normals = [];
  26743. var uvs = [];
  26744. var row, col;
  26745. // Vertices
  26746. for (row = 0; row <= subdivisions; row++) {
  26747. for (col = 0; col <= subdivisions; col++) {
  26748. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26749. // Compute height
  26750. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26751. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26752. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26753. var r = buffer[pos] / 255.0;
  26754. var g = buffer[pos + 1] / 255.0;
  26755. var b = buffer[pos + 2] / 255.0;
  26756. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26757. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26758. // Add vertex
  26759. positions.push(position.x, position.y, position.z);
  26760. normals.push(0, 0, 0);
  26761. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26762. }
  26763. }
  26764. // Indices
  26765. for (row = 0; row < subdivisions; row++) {
  26766. for (col = 0; col < subdivisions; col++) {
  26767. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26768. indices.push(col + 1 + row * (subdivisions + 1));
  26769. indices.push(col + row * (subdivisions + 1));
  26770. indices.push(col + (row + 1) * (subdivisions + 1));
  26771. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26772. indices.push(col + row * (subdivisions + 1));
  26773. }
  26774. }
  26775. // Normals
  26776. VertexData.ComputeNormals(positions, indices, normals);
  26777. // Result
  26778. var vertexData = new VertexData();
  26779. vertexData.indices = indices;
  26780. vertexData.positions = positions;
  26781. vertexData.normals = normals;
  26782. vertexData.uvs = uvs;
  26783. return vertexData;
  26784. };
  26785. VertexData.CreatePlane = function (size, sideOrientation) {
  26786. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26787. var indices = [];
  26788. var positions = [];
  26789. var normals = [];
  26790. var uvs = [];
  26791. size = size || 1;
  26792. // Vertices
  26793. var halfSize = size / 2.0;
  26794. positions.push(-halfSize, -halfSize, 0);
  26795. normals.push(0, 0, -1.0);
  26796. uvs.push(0.0, 0.0);
  26797. positions.push(halfSize, -halfSize, 0);
  26798. normals.push(0, 0, -1.0);
  26799. uvs.push(1.0, 0.0);
  26800. positions.push(halfSize, halfSize, 0);
  26801. normals.push(0, 0, -1.0);
  26802. uvs.push(1.0, 1.0);
  26803. positions.push(-halfSize, halfSize, 0);
  26804. normals.push(0, 0, -1.0);
  26805. uvs.push(0.0, 1.0);
  26806. // Indices
  26807. indices.push(0);
  26808. indices.push(1);
  26809. indices.push(2);
  26810. indices.push(0);
  26811. indices.push(2);
  26812. indices.push(3);
  26813. // Sides
  26814. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26815. // Result
  26816. var vertexData = new VertexData();
  26817. vertexData.indices = indices;
  26818. vertexData.positions = positions;
  26819. vertexData.normals = normals;
  26820. vertexData.uvs = uvs;
  26821. return vertexData;
  26822. };
  26823. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26824. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26825. var positions = [];
  26826. var indices = [];
  26827. var normals = [];
  26828. var uvs = [];
  26829. // positions and uvs
  26830. positions.push(0, 0, 0); // disc center first
  26831. uvs.push(0.5, 0.5);
  26832. var step = Math.PI * 2 / tessellation;
  26833. for (var a = 0; a < Math.PI * 2; a += step) {
  26834. var x = Math.cos(a);
  26835. var y = Math.sin(a);
  26836. var u = (x + 1) / 2;
  26837. var v = (1 - y) / 2;
  26838. positions.push(radius * x, radius * y, 0);
  26839. uvs.push(u, v);
  26840. }
  26841. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26842. uvs.push(uvs[2], uvs[3]);
  26843. //indices
  26844. var vertexNb = positions.length / 3;
  26845. for (var i = 1; i < vertexNb - 1; i++) {
  26846. indices.push(i + 1, 0, i);
  26847. }
  26848. // result
  26849. VertexData.ComputeNormals(positions, indices, normals);
  26850. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26851. var vertexData = new VertexData();
  26852. vertexData.indices = indices;
  26853. vertexData.positions = positions;
  26854. vertexData.normals = normals;
  26855. vertexData.uvs = uvs;
  26856. return vertexData;
  26857. };
  26858. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26859. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26860. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26861. var indices = [];
  26862. var positions = [];
  26863. var normals = [];
  26864. var uvs = [];
  26865. radius = radius || 2;
  26866. tube = tube || 0.5;
  26867. radialSegments = radialSegments || 32;
  26868. tubularSegments = tubularSegments || 32;
  26869. p = p || 2;
  26870. q = q || 3;
  26871. // Helper
  26872. var getPos = function (angle) {
  26873. var cu = Math.cos(angle);
  26874. var su = Math.sin(angle);
  26875. var quOverP = q / p * angle;
  26876. var cs = Math.cos(quOverP);
  26877. var tx = radius * (2 + cs) * 0.5 * cu;
  26878. var ty = radius * (2 + cs) * su * 0.5;
  26879. var tz = radius * Math.sin(quOverP) * 0.5;
  26880. return new BABYLON.Vector3(tx, ty, tz);
  26881. };
  26882. // Vertices
  26883. var i;
  26884. var j;
  26885. for (i = 0; i <= radialSegments; i++) {
  26886. var modI = i % radialSegments;
  26887. var u = modI / radialSegments * 2 * p * Math.PI;
  26888. var p1 = getPos(u);
  26889. var p2 = getPos(u + 0.01);
  26890. var tang = p2.subtract(p1);
  26891. var n = p2.add(p1);
  26892. var bitan = BABYLON.Vector3.Cross(tang, n);
  26893. n = BABYLON.Vector3.Cross(bitan, tang);
  26894. bitan.normalize();
  26895. n.normalize();
  26896. for (j = 0; j < tubularSegments; j++) {
  26897. var modJ = j % tubularSegments;
  26898. var v = modJ / tubularSegments * 2 * Math.PI;
  26899. var cx = -tube * Math.cos(v);
  26900. var cy = tube * Math.sin(v);
  26901. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26902. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26903. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26904. uvs.push(i / radialSegments);
  26905. uvs.push(j / tubularSegments);
  26906. }
  26907. }
  26908. for (i = 0; i < radialSegments; i++) {
  26909. for (j = 0; j < tubularSegments; j++) {
  26910. var jNext = (j + 1) % tubularSegments;
  26911. var a = i * tubularSegments + j;
  26912. var b = (i + 1) * tubularSegments + j;
  26913. var c = (i + 1) * tubularSegments + jNext;
  26914. var d = i * tubularSegments + jNext;
  26915. indices.push(d);
  26916. indices.push(b);
  26917. indices.push(a);
  26918. indices.push(d);
  26919. indices.push(c);
  26920. indices.push(b);
  26921. }
  26922. }
  26923. // Normals
  26924. VertexData.ComputeNormals(positions, indices, normals);
  26925. // Sides
  26926. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26927. // Result
  26928. var vertexData = new VertexData();
  26929. vertexData.indices = indices;
  26930. vertexData.positions = positions;
  26931. vertexData.normals = normals;
  26932. vertexData.uvs = uvs;
  26933. return vertexData;
  26934. };
  26935. // Tools
  26936. /**
  26937. * @param {any} - positions (number[] or Float32Array)
  26938. * @param {any} - indices (number[] or Uint16Array)
  26939. * @param {any} - normals (number[] or Float32Array)
  26940. */
  26941. VertexData.ComputeNormals = function (positions, indices, normals) {
  26942. var index = 0;
  26943. // temp Vector3
  26944. var p1p2 = BABYLON.Vector3.Zero();
  26945. var p3p2 = BABYLON.Vector3.Zero();
  26946. var faceNormal = BABYLON.Vector3.Zero();
  26947. var vertexNormali1 = BABYLON.Vector3.Zero();
  26948. for (index = 0; index < positions.length; index++) {
  26949. normals[index] = 0.0;
  26950. }
  26951. // indice triplet = 1 face
  26952. var nbFaces = indices.length / 3;
  26953. for (index = 0; index < nbFaces; index++) {
  26954. var i1 = indices[index * 3];
  26955. var i2 = indices[index * 3 + 1];
  26956. var i3 = indices[index * 3 + 2];
  26957. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  26958. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26959. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26960. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  26961. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26962. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26963. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  26964. faceNormal.normalize();
  26965. normals[i1 * 3] += faceNormal.x;
  26966. normals[i1 * 3 + 1] += faceNormal.y;
  26967. normals[i1 * 3 + 2] += faceNormal.z;
  26968. normals[i2 * 3] += faceNormal.x;
  26969. normals[i2 * 3 + 1] += faceNormal.y;
  26970. normals[i2 * 3 + 2] += faceNormal.z;
  26971. normals[i3 * 3] += faceNormal.x;
  26972. normals[i3 * 3 + 1] += faceNormal.y;
  26973. normals[i3 * 3 + 2] += faceNormal.z;
  26974. }
  26975. // last normalization
  26976. for (index = 0; index < normals.length / 3; index++) {
  26977. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  26978. vertexNormali1.normalize();
  26979. normals[index * 3] = vertexNormali1.x;
  26980. normals[index * 3 + 1] = vertexNormali1.y;
  26981. normals[index * 3 + 2] = vertexNormali1.z;
  26982. }
  26983. };
  26984. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26985. var li = indices.length;
  26986. var ln = normals.length;
  26987. var i;
  26988. var n;
  26989. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26990. switch (sideOrientation) {
  26991. case BABYLON.Mesh.FRONTSIDE:
  26992. // nothing changed
  26993. break;
  26994. case BABYLON.Mesh.BACKSIDE:
  26995. var tmp;
  26996. // indices
  26997. for (i = 0; i < li; i += 3) {
  26998. tmp = indices[i];
  26999. indices[i] = indices[i + 2];
  27000. indices[i + 2] = tmp;
  27001. }
  27002. // normals
  27003. for (n = 0; n < ln; n++) {
  27004. normals[n] = -normals[n];
  27005. }
  27006. break;
  27007. case BABYLON.Mesh.DOUBLESIDE:
  27008. // positions
  27009. var lp = positions.length;
  27010. var l = lp / 3;
  27011. for (var p = 0; p < lp; p++) {
  27012. positions[lp + p] = positions[p];
  27013. }
  27014. // indices
  27015. for (i = 0; i < li; i += 3) {
  27016. indices[i + li] = indices[i + 2] + l;
  27017. indices[i + 1 + li] = indices[i + 1] + l;
  27018. indices[i + 2 + li] = indices[i] + l;
  27019. }
  27020. // normals
  27021. for (n = 0; n < ln; n++) {
  27022. normals[ln + n] = -normals[n];
  27023. }
  27024. // uvs
  27025. var lu = uvs.length;
  27026. for (var u = 0; u < lu; u++) {
  27027. uvs[u + lu] = uvs[u];
  27028. }
  27029. break;
  27030. }
  27031. };
  27032. return VertexData;
  27033. })();
  27034. BABYLON.VertexData = VertexData;
  27035. })(BABYLON || (BABYLON = {}));
  27036. var BABYLON;
  27037. (function (BABYLON) {
  27038. var AnaglyphPostProcess = (function (_super) {
  27039. __extends(AnaglyphPostProcess, _super);
  27040. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27041. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27042. }
  27043. return AnaglyphPostProcess;
  27044. })(BABYLON.PostProcess);
  27045. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27046. })(BABYLON || (BABYLON = {}));
  27047. var BABYLON;
  27048. (function (BABYLON) {
  27049. var Tags = (function () {
  27050. function Tags() {
  27051. }
  27052. Tags.EnableFor = function (obj) {
  27053. obj._tags = obj._tags || {};
  27054. obj.hasTags = function () {
  27055. return Tags.HasTags(obj);
  27056. };
  27057. obj.addTags = function (tagsString) {
  27058. return Tags.AddTagsTo(obj, tagsString);
  27059. };
  27060. obj.removeTags = function (tagsString) {
  27061. return Tags.RemoveTagsFrom(obj, tagsString);
  27062. };
  27063. obj.matchesTagsQuery = function (tagsQuery) {
  27064. return Tags.MatchesQuery(obj, tagsQuery);
  27065. };
  27066. };
  27067. Tags.DisableFor = function (obj) {
  27068. delete obj._tags;
  27069. delete obj.hasTags;
  27070. delete obj.addTags;
  27071. delete obj.removeTags;
  27072. delete obj.matchesTagsQuery;
  27073. };
  27074. Tags.HasTags = function (obj) {
  27075. if (!obj._tags) {
  27076. return false;
  27077. }
  27078. return !BABYLON.Tools.IsEmpty(obj._tags);
  27079. };
  27080. Tags.GetTags = function (obj) {
  27081. if (!obj._tags) {
  27082. return null;
  27083. }
  27084. return obj._tags;
  27085. };
  27086. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27087. // a tag cannot start with '||', '&&', and '!'
  27088. // it cannot contain whitespaces
  27089. Tags.AddTagsTo = function (obj, tagsString) {
  27090. if (!tagsString) {
  27091. return;
  27092. }
  27093. var tags = tagsString.split(" ");
  27094. for (var t in tags) {
  27095. Tags._AddTagTo(obj, tags[t]);
  27096. }
  27097. };
  27098. Tags._AddTagTo = function (obj, tag) {
  27099. tag = tag.trim();
  27100. if (tag === "" || tag === "true" || tag === "false") {
  27101. return;
  27102. }
  27103. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27104. return;
  27105. }
  27106. Tags.EnableFor(obj);
  27107. obj._tags[tag] = true;
  27108. };
  27109. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27110. if (!Tags.HasTags(obj)) {
  27111. return;
  27112. }
  27113. var tags = tagsString.split(" ");
  27114. for (var t in tags) {
  27115. Tags._RemoveTagFrom(obj, tags[t]);
  27116. }
  27117. };
  27118. Tags._RemoveTagFrom = function (obj, tag) {
  27119. delete obj._tags[tag];
  27120. };
  27121. Tags.MatchesQuery = function (obj, tagsQuery) {
  27122. if (tagsQuery === undefined) {
  27123. return true;
  27124. }
  27125. if (tagsQuery === "") {
  27126. return Tags.HasTags(obj);
  27127. }
  27128. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27129. };
  27130. return Tags;
  27131. })();
  27132. BABYLON.Tags = Tags;
  27133. })(BABYLON || (BABYLON = {}));
  27134. var BABYLON;
  27135. (function (BABYLON) {
  27136. var Internals;
  27137. (function (Internals) {
  27138. var AndOrNotEvaluator = (function () {
  27139. function AndOrNotEvaluator() {
  27140. }
  27141. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27142. if (!query.match(/\([^\(\)]*\)/g)) {
  27143. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27144. }
  27145. else {
  27146. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27147. // remove parenthesis
  27148. r = r.slice(1, r.length - 1);
  27149. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27150. });
  27151. }
  27152. if (query === "true") {
  27153. return true;
  27154. }
  27155. if (query === "false") {
  27156. return false;
  27157. }
  27158. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27159. };
  27160. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27161. evaluateCallback = evaluateCallback || (function (r) {
  27162. return r === "true" ? true : false;
  27163. });
  27164. var result;
  27165. var or = parenthesisContent.split("||");
  27166. for (var i in or) {
  27167. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27168. var and = ori.split("&&");
  27169. if (and.length > 1) {
  27170. for (var j = 0; j < and.length; ++j) {
  27171. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27172. if (andj !== "true" && andj !== "false") {
  27173. if (andj[0] === "!") {
  27174. result = !evaluateCallback(andj.substring(1));
  27175. }
  27176. else {
  27177. result = evaluateCallback(andj);
  27178. }
  27179. }
  27180. else {
  27181. result = andj === "true" ? true : false;
  27182. }
  27183. if (!result) {
  27184. ori = "false";
  27185. break;
  27186. }
  27187. }
  27188. }
  27189. if (result || ori === "true") {
  27190. result = true;
  27191. break;
  27192. }
  27193. // result equals false (or undefined)
  27194. if (ori !== "true" && ori !== "false") {
  27195. if (ori[0] === "!") {
  27196. result = !evaluateCallback(ori.substring(1));
  27197. }
  27198. else {
  27199. result = evaluateCallback(ori);
  27200. }
  27201. }
  27202. else {
  27203. result = ori === "true" ? true : false;
  27204. }
  27205. }
  27206. // the whole parenthesis scope is replaced by 'true' or 'false'
  27207. return result ? "true" : "false";
  27208. };
  27209. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27210. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27211. // remove whitespaces
  27212. r = r.replace(/[\s]/g, function () { return ""; });
  27213. return r.length % 2 ? "!" : "";
  27214. });
  27215. booleanString = booleanString.trim();
  27216. if (booleanString === "!true") {
  27217. booleanString = "false";
  27218. }
  27219. else if (booleanString === "!false") {
  27220. booleanString = "true";
  27221. }
  27222. return booleanString;
  27223. };
  27224. return AndOrNotEvaluator;
  27225. })();
  27226. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27227. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27228. })(BABYLON || (BABYLON = {}));
  27229. var BABYLON;
  27230. (function (BABYLON) {
  27231. var PostProcessRenderPass = (function () {
  27232. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27233. this._enabled = true;
  27234. this._refCount = 0;
  27235. this._name = name;
  27236. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27237. this.setRenderList(renderList);
  27238. this._renderTexture.onBeforeRender = beforeRender;
  27239. this._renderTexture.onAfterRender = afterRender;
  27240. this._scene = scene;
  27241. this._renderList = renderList;
  27242. }
  27243. // private
  27244. PostProcessRenderPass.prototype._incRefCount = function () {
  27245. if (this._refCount === 0) {
  27246. this._scene.customRenderTargets.push(this._renderTexture);
  27247. }
  27248. return ++this._refCount;
  27249. };
  27250. PostProcessRenderPass.prototype._decRefCount = function () {
  27251. this._refCount--;
  27252. if (this._refCount <= 0) {
  27253. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27254. }
  27255. return this._refCount;
  27256. };
  27257. PostProcessRenderPass.prototype._update = function () {
  27258. this.setRenderList(this._renderList);
  27259. };
  27260. // public
  27261. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27262. this._renderTexture.renderList = renderList;
  27263. };
  27264. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27265. return this._renderTexture;
  27266. };
  27267. return PostProcessRenderPass;
  27268. })();
  27269. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27270. })(BABYLON || (BABYLON = {}));
  27271. var BABYLON;
  27272. (function (BABYLON) {
  27273. var PostProcessRenderEffect = (function () {
  27274. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27275. this._engine = engine;
  27276. this._name = name;
  27277. this._singleInstance = singleInstance || true;
  27278. this._getPostProcess = getPostProcess;
  27279. this._cameras = [];
  27280. this._indicesForCamera = [];
  27281. this._postProcesses = {};
  27282. this._renderPasses = {};
  27283. this._renderEffectAsPasses = {};
  27284. }
  27285. PostProcessRenderEffect.prototype._update = function () {
  27286. for (var renderPassName in this._renderPasses) {
  27287. this._renderPasses[renderPassName]._update();
  27288. }
  27289. };
  27290. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27291. this._renderPasses[renderPass._name] = renderPass;
  27292. this._linkParameters();
  27293. };
  27294. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27295. delete this._renderPasses[renderPass._name];
  27296. this._linkParameters();
  27297. };
  27298. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27299. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27300. this._linkParameters();
  27301. };
  27302. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27303. for (var renderPassName in this._renderPasses) {
  27304. if (renderPassName === passName) {
  27305. return this._renderPasses[passName];
  27306. }
  27307. }
  27308. };
  27309. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27310. this._renderPasses = {};
  27311. this._linkParameters();
  27312. };
  27313. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27314. var cameraKey;
  27315. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27316. for (var i = 0; i < _cam.length; i++) {
  27317. var camera = _cam[i];
  27318. var cameraName = camera.name;
  27319. if (this._singleInstance) {
  27320. cameraKey = 0;
  27321. }
  27322. else {
  27323. cameraKey = cameraName;
  27324. }
  27325. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27326. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27327. if (!this._indicesForCamera[cameraName]) {
  27328. this._indicesForCamera[cameraName] = [];
  27329. }
  27330. this._indicesForCamera[cameraName].push(index);
  27331. if (this._cameras.indexOf(camera) === -1) {
  27332. this._cameras[cameraName] = camera;
  27333. }
  27334. for (var passName in this._renderPasses) {
  27335. this._renderPasses[passName]._incRefCount();
  27336. }
  27337. }
  27338. this._linkParameters();
  27339. };
  27340. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27341. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27342. for (var i = 0; i < _cam.length; i++) {
  27343. var camera = _cam[i];
  27344. var cameraName = camera.name;
  27345. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27346. var index = this._cameras.indexOf(cameraName);
  27347. this._indicesForCamera.splice(index, 1);
  27348. this._cameras.splice(index, 1);
  27349. for (var passName in this._renderPasses) {
  27350. this._renderPasses[passName]._decRefCount();
  27351. }
  27352. }
  27353. };
  27354. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27355. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27356. for (var i = 0; i < _cam.length; i++) {
  27357. var camera = _cam[i];
  27358. var cameraName = camera.name;
  27359. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27360. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27361. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27362. }
  27363. }
  27364. for (var passName in this._renderPasses) {
  27365. this._renderPasses[passName]._incRefCount();
  27366. }
  27367. }
  27368. };
  27369. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27370. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27371. for (var i = 0; i < _cam.length; i++) {
  27372. var camera = _cam[i];
  27373. var cameraName = camera.Name;
  27374. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27375. for (var passName in this._renderPasses) {
  27376. this._renderPasses[passName]._decRefCount();
  27377. }
  27378. }
  27379. };
  27380. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27381. if (this._singleInstance) {
  27382. return this._postProcesses[0];
  27383. }
  27384. else {
  27385. return this._postProcesses[camera.name];
  27386. }
  27387. };
  27388. PostProcessRenderEffect.prototype._linkParameters = function () {
  27389. var _this = this;
  27390. for (var index in this._postProcesses) {
  27391. if (this.applyParameters) {
  27392. this.applyParameters(this._postProcesses[index]);
  27393. }
  27394. this._postProcesses[index].onBeforeRender = function (effect) {
  27395. _this._linkTextures(effect);
  27396. };
  27397. }
  27398. };
  27399. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27400. for (var renderPassName in this._renderPasses) {
  27401. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27402. }
  27403. for (var renderEffectName in this._renderEffectAsPasses) {
  27404. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27405. }
  27406. };
  27407. return PostProcessRenderEffect;
  27408. })();
  27409. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27410. })(BABYLON || (BABYLON = {}));
  27411. var BABYLON;
  27412. (function (BABYLON) {
  27413. var PostProcessRenderPipeline = (function () {
  27414. function PostProcessRenderPipeline(engine, name) {
  27415. this._engine = engine;
  27416. this._name = name;
  27417. this._renderEffects = {};
  27418. this._renderEffectsForIsolatedPass = {};
  27419. this._cameras = [];
  27420. }
  27421. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27422. this._renderEffects[renderEffect._name] = renderEffect;
  27423. };
  27424. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27425. var renderEffects = this._renderEffects[renderEffectName];
  27426. if (!renderEffects) {
  27427. return;
  27428. }
  27429. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27430. };
  27431. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27432. var renderEffects = this._renderEffects[renderEffectName];
  27433. if (!renderEffects) {
  27434. return;
  27435. }
  27436. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27437. };
  27438. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27439. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27440. var indicesToDelete = [];
  27441. for (var i = 0; i < _cam.length; i++) {
  27442. var camera = _cam[i];
  27443. var cameraName = camera.name;
  27444. if (this._cameras.indexOf(camera) === -1) {
  27445. this._cameras[cameraName] = camera;
  27446. }
  27447. else if (unique) {
  27448. indicesToDelete.push(i);
  27449. }
  27450. }
  27451. for (var i = 0; i < indicesToDelete.length; i++) {
  27452. cameras.splice(indicesToDelete[i], 1);
  27453. }
  27454. for (var renderEffectName in this._renderEffects) {
  27455. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27456. }
  27457. };
  27458. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27459. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27460. for (var renderEffectName in this._renderEffects) {
  27461. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27462. }
  27463. for (var i = 0; i < _cam.length; i++) {
  27464. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27465. }
  27466. };
  27467. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27468. var _this = this;
  27469. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27470. var pass = null;
  27471. for (var renderEffectName in this._renderEffects) {
  27472. pass = this._renderEffects[renderEffectName].getPass(passName);
  27473. if (pass != null) {
  27474. break;
  27475. }
  27476. }
  27477. if (pass === null) {
  27478. return;
  27479. }
  27480. for (var renderEffectName in this._renderEffects) {
  27481. this._renderEffects[renderEffectName]._disable(_cam);
  27482. }
  27483. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27484. for (var i = 0; i < _cam.length; i++) {
  27485. var camera = _cam[i];
  27486. var cameraName = camera.name;
  27487. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  27488. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27489. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27490. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27491. }
  27492. };
  27493. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27494. var _this = this;
  27495. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27496. for (var i = 0; i < _cam.length; i++) {
  27497. var camera = _cam[i];
  27498. var cameraName = camera.name;
  27499. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  27500. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27501. }
  27502. for (var renderEffectName in this._renderEffects) {
  27503. this._renderEffects[renderEffectName]._enable(_cam);
  27504. }
  27505. };
  27506. PostProcessRenderPipeline.prototype._update = function () {
  27507. for (var renderEffectName in this._renderEffects) {
  27508. this._renderEffects[renderEffectName]._update();
  27509. }
  27510. for (var i = 0; i < this._cameras.length; i++) {
  27511. var cameraName = this._cameras[i].name;
  27512. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27513. this._renderEffectsForIsolatedPass[cameraName]._update();
  27514. }
  27515. }
  27516. };
  27517. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27518. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27519. return PostProcessRenderPipeline;
  27520. })();
  27521. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27522. })(BABYLON || (BABYLON = {}));
  27523. var BABYLON;
  27524. (function (BABYLON) {
  27525. var PostProcessRenderPipelineManager = (function () {
  27526. function PostProcessRenderPipelineManager() {
  27527. this._renderPipelines = {};
  27528. }
  27529. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27530. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27531. };
  27532. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27533. var renderPipeline = this._renderPipelines[renderPipelineName];
  27534. if (!renderPipeline) {
  27535. return;
  27536. }
  27537. renderPipeline._attachCameras(cameras, unique);
  27538. };
  27539. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27540. var renderPipeline = this._renderPipelines[renderPipelineName];
  27541. if (!renderPipeline) {
  27542. return;
  27543. }
  27544. renderPipeline._detachCameras(cameras);
  27545. };
  27546. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27547. var renderPipeline = this._renderPipelines[renderPipelineName];
  27548. if (!renderPipeline) {
  27549. return;
  27550. }
  27551. renderPipeline._enableEffect(renderEffectName, cameras);
  27552. };
  27553. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27554. var renderPipeline = this._renderPipelines[renderPipelineName];
  27555. if (!renderPipeline) {
  27556. return;
  27557. }
  27558. renderPipeline._disableEffect(renderEffectName, cameras);
  27559. };
  27560. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27561. var renderPipeline = this._renderPipelines[renderPipelineName];
  27562. if (!renderPipeline) {
  27563. return;
  27564. }
  27565. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27566. };
  27567. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27568. var renderPipeline = this._renderPipelines[renderPipelineName];
  27569. if (!renderPipeline) {
  27570. return;
  27571. }
  27572. renderPipeline._disableDisplayOnlyPass(cameras);
  27573. };
  27574. PostProcessRenderPipelineManager.prototype.update = function () {
  27575. for (var renderPipelineName in this._renderPipelines) {
  27576. this._renderPipelines[renderPipelineName]._update();
  27577. }
  27578. };
  27579. return PostProcessRenderPipelineManager;
  27580. })();
  27581. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27582. })(BABYLON || (BABYLON = {}));
  27583. var BABYLON;
  27584. (function (BABYLON) {
  27585. var DisplayPassPostProcess = (function (_super) {
  27586. __extends(DisplayPassPostProcess, _super);
  27587. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27588. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27589. }
  27590. return DisplayPassPostProcess;
  27591. })(BABYLON.PostProcess);
  27592. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27593. })(BABYLON || (BABYLON = {}));
  27594. var BABYLON;
  27595. (function (BABYLON) {
  27596. var BoundingBoxRenderer = (function () {
  27597. function BoundingBoxRenderer(scene) {
  27598. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27599. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27600. this.showBackLines = true;
  27601. this.renderList = new BABYLON.SmartArray(32);
  27602. this._scene = scene;
  27603. }
  27604. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27605. if (this._colorShader) {
  27606. return;
  27607. }
  27608. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27609. attributes: ["position"],
  27610. uniforms: ["worldViewProjection", "color"]
  27611. });
  27612. var engine = this._scene.getEngine();
  27613. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27614. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27615. 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]);
  27616. };
  27617. BoundingBoxRenderer.prototype.reset = function () {
  27618. this.renderList.reset();
  27619. };
  27620. BoundingBoxRenderer.prototype.render = function () {
  27621. if (this.renderList.length === 0) {
  27622. return;
  27623. }
  27624. this._prepareRessources();
  27625. if (!this._colorShader.isReady()) {
  27626. return;
  27627. }
  27628. var engine = this._scene.getEngine();
  27629. engine.setDepthWrite(false);
  27630. this._colorShader._preBind();
  27631. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27632. var boundingBox = this.renderList.data[boundingBoxIndex];
  27633. var min = boundingBox.minimum;
  27634. var max = boundingBox.maximum;
  27635. var diff = max.subtract(min);
  27636. var median = min.add(diff.scale(0.5));
  27637. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27638. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27639. .multiply(boundingBox.getWorldMatrix());
  27640. // VBOs
  27641. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27642. if (this.showBackLines) {
  27643. // Back
  27644. engine.setDepthFunctionToGreaterOrEqual();
  27645. this._scene.resetCachedMaterial();
  27646. this._colorShader.setColor4("color", this.backColor.toColor4());
  27647. this._colorShader.bind(worldMatrix);
  27648. // Draw order
  27649. engine.draw(false, 0, 24);
  27650. }
  27651. // Front
  27652. engine.setDepthFunctionToLess();
  27653. this._scene.resetCachedMaterial();
  27654. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27655. this._colorShader.bind(worldMatrix);
  27656. // Draw order
  27657. engine.draw(false, 0, 24);
  27658. }
  27659. this._colorShader.unbind();
  27660. engine.setDepthFunctionToLessOrEqual();
  27661. engine.setDepthWrite(true);
  27662. };
  27663. BoundingBoxRenderer.prototype.dispose = function () {
  27664. if (!this._colorShader) {
  27665. return;
  27666. }
  27667. this._colorShader.dispose();
  27668. this._vb.dispose();
  27669. this._scene.getEngine()._releaseBuffer(this._ib);
  27670. };
  27671. return BoundingBoxRenderer;
  27672. })();
  27673. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27674. })(BABYLON || (BABYLON = {}));
  27675. var BABYLON;
  27676. (function (BABYLON) {
  27677. var Condition = (function () {
  27678. function Condition(actionManager) {
  27679. this._actionManager = actionManager;
  27680. }
  27681. Condition.prototype.isValid = function () {
  27682. return true;
  27683. };
  27684. Condition.prototype._getProperty = function (propertyPath) {
  27685. return this._actionManager._getProperty(propertyPath);
  27686. };
  27687. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27688. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27689. };
  27690. return Condition;
  27691. })();
  27692. BABYLON.Condition = Condition;
  27693. var ValueCondition = (function (_super) {
  27694. __extends(ValueCondition, _super);
  27695. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27696. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27697. _super.call(this, actionManager);
  27698. this.propertyPath = propertyPath;
  27699. this.value = value;
  27700. this.operator = operator;
  27701. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27702. this._property = this._getProperty(this.propertyPath);
  27703. }
  27704. Object.defineProperty(ValueCondition, "IsEqual", {
  27705. get: function () {
  27706. return ValueCondition._IsEqual;
  27707. },
  27708. enumerable: true,
  27709. configurable: true
  27710. });
  27711. Object.defineProperty(ValueCondition, "IsDifferent", {
  27712. get: function () {
  27713. return ValueCondition._IsDifferent;
  27714. },
  27715. enumerable: true,
  27716. configurable: true
  27717. });
  27718. Object.defineProperty(ValueCondition, "IsGreater", {
  27719. get: function () {
  27720. return ValueCondition._IsGreater;
  27721. },
  27722. enumerable: true,
  27723. configurable: true
  27724. });
  27725. Object.defineProperty(ValueCondition, "IsLesser", {
  27726. get: function () {
  27727. return ValueCondition._IsLesser;
  27728. },
  27729. enumerable: true,
  27730. configurable: true
  27731. });
  27732. // Methods
  27733. ValueCondition.prototype.isValid = function () {
  27734. switch (this.operator) {
  27735. case ValueCondition.IsGreater:
  27736. return this._target[this._property] > this.value;
  27737. case ValueCondition.IsLesser:
  27738. return this._target[this._property] < this.value;
  27739. case ValueCondition.IsEqual:
  27740. case ValueCondition.IsDifferent:
  27741. var check;
  27742. if (this.value.equals) {
  27743. check = this.value.equals(this._target[this._property]);
  27744. }
  27745. else {
  27746. check = this.value === this._target[this._property];
  27747. }
  27748. return this.operator === ValueCondition.IsEqual ? check : !check;
  27749. }
  27750. return false;
  27751. };
  27752. // Statics
  27753. ValueCondition._IsEqual = 0;
  27754. ValueCondition._IsDifferent = 1;
  27755. ValueCondition._IsGreater = 2;
  27756. ValueCondition._IsLesser = 3;
  27757. return ValueCondition;
  27758. })(Condition);
  27759. BABYLON.ValueCondition = ValueCondition;
  27760. var PredicateCondition = (function (_super) {
  27761. __extends(PredicateCondition, _super);
  27762. function PredicateCondition(actionManager, predicate) {
  27763. _super.call(this, actionManager);
  27764. this.predicate = predicate;
  27765. }
  27766. PredicateCondition.prototype.isValid = function () {
  27767. return this.predicate();
  27768. };
  27769. return PredicateCondition;
  27770. })(Condition);
  27771. BABYLON.PredicateCondition = PredicateCondition;
  27772. var StateCondition = (function (_super) {
  27773. __extends(StateCondition, _super);
  27774. function StateCondition(actionManager, target, value) {
  27775. _super.call(this, actionManager);
  27776. this.value = value;
  27777. this._target = target;
  27778. }
  27779. // Methods
  27780. StateCondition.prototype.isValid = function () {
  27781. return this._target.state === this.value;
  27782. };
  27783. return StateCondition;
  27784. })(Condition);
  27785. BABYLON.StateCondition = StateCondition;
  27786. })(BABYLON || (BABYLON = {}));
  27787. var BABYLON;
  27788. (function (BABYLON) {
  27789. var Action = (function () {
  27790. function Action(triggerOptions, condition) {
  27791. this.triggerOptions = triggerOptions;
  27792. if (triggerOptions.parameter) {
  27793. this.trigger = triggerOptions.trigger;
  27794. this._triggerParameter = triggerOptions.parameter;
  27795. }
  27796. else {
  27797. this.trigger = triggerOptions;
  27798. }
  27799. this._nextActiveAction = this;
  27800. this._condition = condition;
  27801. }
  27802. // Methods
  27803. Action.prototype._prepare = function () {
  27804. };
  27805. Action.prototype.getTriggerParameter = function () {
  27806. return this._triggerParameter;
  27807. };
  27808. Action.prototype._executeCurrent = function (evt) {
  27809. if (this._nextActiveAction._condition) {
  27810. var condition = this._nextActiveAction._condition;
  27811. var currentRenderId = this._actionManager.getScene().getRenderId();
  27812. // We cache the current evaluation for the current frame
  27813. if (condition._evaluationId === currentRenderId) {
  27814. if (!condition._currentResult) {
  27815. return;
  27816. }
  27817. }
  27818. else {
  27819. condition._evaluationId = currentRenderId;
  27820. if (!condition.isValid()) {
  27821. condition._currentResult = false;
  27822. return;
  27823. }
  27824. condition._currentResult = true;
  27825. }
  27826. }
  27827. this._nextActiveAction.execute(evt);
  27828. if (this._nextActiveAction._child) {
  27829. if (!this._nextActiveAction._child._actionManager) {
  27830. this._nextActiveAction._child._actionManager = this._actionManager;
  27831. }
  27832. this._nextActiveAction = this._nextActiveAction._child;
  27833. }
  27834. else {
  27835. this._nextActiveAction = this;
  27836. }
  27837. };
  27838. Action.prototype.execute = function (evt) {
  27839. };
  27840. Action.prototype.then = function (action) {
  27841. this._child = action;
  27842. action._actionManager = this._actionManager;
  27843. action._prepare();
  27844. return action;
  27845. };
  27846. Action.prototype._getProperty = function (propertyPath) {
  27847. return this._actionManager._getProperty(propertyPath);
  27848. };
  27849. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27850. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27851. };
  27852. return Action;
  27853. })();
  27854. BABYLON.Action = Action;
  27855. })(BABYLON || (BABYLON = {}));
  27856. var BABYLON;
  27857. (function (BABYLON) {
  27858. /**
  27859. * ActionEvent is the event beint sent when an action is triggered.
  27860. */
  27861. var ActionEvent = (function () {
  27862. /**
  27863. * @constructor
  27864. * @param source The mesh that triggered the action.
  27865. * @param pointerX the X mouse cursor position at the time of the event
  27866. * @param pointerY the Y mouse cursor position at the time of the event
  27867. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27868. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27869. */
  27870. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27871. this.source = source;
  27872. this.pointerX = pointerX;
  27873. this.pointerY = pointerY;
  27874. this.meshUnderPointer = meshUnderPointer;
  27875. this.sourceEvent = sourceEvent;
  27876. this.additionalData = additionalData;
  27877. }
  27878. /**
  27879. * Helper function to auto-create an ActionEvent from a source mesh.
  27880. * @param source the source mesh that triggered the event
  27881. * @param evt {Event} The original (browser) event
  27882. */
  27883. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27884. var scene = source.getScene();
  27885. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27886. };
  27887. /**
  27888. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27889. * @param scene the scene where the event occurred
  27890. * @param evt {Event} The original (browser) event
  27891. */
  27892. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27893. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27894. };
  27895. return ActionEvent;
  27896. })();
  27897. BABYLON.ActionEvent = ActionEvent;
  27898. /**
  27899. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27900. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27901. */
  27902. var ActionManager = (function () {
  27903. function ActionManager(scene) {
  27904. // Members
  27905. this.actions = new Array();
  27906. this._scene = scene;
  27907. scene._actionManagers.push(this);
  27908. }
  27909. Object.defineProperty(ActionManager, "NothingTrigger", {
  27910. get: function () {
  27911. return ActionManager._NothingTrigger;
  27912. },
  27913. enumerable: true,
  27914. configurable: true
  27915. });
  27916. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27917. get: function () {
  27918. return ActionManager._OnPickTrigger;
  27919. },
  27920. enumerable: true,
  27921. configurable: true
  27922. });
  27923. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27924. get: function () {
  27925. return ActionManager._OnLeftPickTrigger;
  27926. },
  27927. enumerable: true,
  27928. configurable: true
  27929. });
  27930. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27931. get: function () {
  27932. return ActionManager._OnRightPickTrigger;
  27933. },
  27934. enumerable: true,
  27935. configurable: true
  27936. });
  27937. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27938. get: function () {
  27939. return ActionManager._OnCenterPickTrigger;
  27940. },
  27941. enumerable: true,
  27942. configurable: true
  27943. });
  27944. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27945. get: function () {
  27946. return ActionManager._OnPointerOverTrigger;
  27947. },
  27948. enumerable: true,
  27949. configurable: true
  27950. });
  27951. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27952. get: function () {
  27953. return ActionManager._OnPointerOutTrigger;
  27954. },
  27955. enumerable: true,
  27956. configurable: true
  27957. });
  27958. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27959. get: function () {
  27960. return ActionManager._OnEveryFrameTrigger;
  27961. },
  27962. enumerable: true,
  27963. configurable: true
  27964. });
  27965. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27966. get: function () {
  27967. return ActionManager._OnIntersectionEnterTrigger;
  27968. },
  27969. enumerable: true,
  27970. configurable: true
  27971. });
  27972. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27973. get: function () {
  27974. return ActionManager._OnIntersectionExitTrigger;
  27975. },
  27976. enumerable: true,
  27977. configurable: true
  27978. });
  27979. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27980. get: function () {
  27981. return ActionManager._OnKeyDownTrigger;
  27982. },
  27983. enumerable: true,
  27984. configurable: true
  27985. });
  27986. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27987. get: function () {
  27988. return ActionManager._OnKeyUpTrigger;
  27989. },
  27990. enumerable: true,
  27991. configurable: true
  27992. });
  27993. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27994. get: function () {
  27995. return ActionManager._OnPickUpTrigger;
  27996. },
  27997. enumerable: true,
  27998. configurable: true
  27999. });
  28000. // Methods
  28001. ActionManager.prototype.dispose = function () {
  28002. var index = this._scene._actionManagers.indexOf(this);
  28003. if (index > -1) {
  28004. this._scene._actionManagers.splice(index, 1);
  28005. }
  28006. };
  28007. ActionManager.prototype.getScene = function () {
  28008. return this._scene;
  28009. };
  28010. /**
  28011. * Does this action manager handles actions of any of the given triggers
  28012. * @param {number[]} triggers - the triggers to be tested
  28013. * @return {boolean} whether one (or more) of the triggers is handeled
  28014. */
  28015. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28016. for (var index = 0; index < this.actions.length; index++) {
  28017. var action = this.actions[index];
  28018. if (triggers.indexOf(action.trigger) > -1) {
  28019. return true;
  28020. }
  28021. }
  28022. return false;
  28023. };
  28024. /**
  28025. * Does this action manager handles actions of a given trigger
  28026. * @param {number} trigger - the trigger to be tested
  28027. * @return {boolean} whether the trigger is handeled
  28028. */
  28029. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28030. for (var index = 0; index < this.actions.length; index++) {
  28031. var action = this.actions[index];
  28032. if (action.trigger === trigger) {
  28033. return true;
  28034. }
  28035. }
  28036. return false;
  28037. };
  28038. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28039. /**
  28040. * Does this action manager has pointer triggers
  28041. * @return {boolean} whether or not it has pointer triggers
  28042. */
  28043. get: function () {
  28044. for (var index = 0; index < this.actions.length; index++) {
  28045. var action = this.actions[index];
  28046. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28047. return true;
  28048. }
  28049. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28050. return true;
  28051. }
  28052. }
  28053. return false;
  28054. },
  28055. enumerable: true,
  28056. configurable: true
  28057. });
  28058. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28059. /**
  28060. * Does this action manager has pick triggers
  28061. * @return {boolean} whether or not it has pick triggers
  28062. */
  28063. get: function () {
  28064. for (var index = 0; index < this.actions.length; index++) {
  28065. var action = this.actions[index];
  28066. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28067. return true;
  28068. }
  28069. }
  28070. return false;
  28071. },
  28072. enumerable: true,
  28073. configurable: true
  28074. });
  28075. /**
  28076. * Registers an action to this action manager
  28077. * @param {BABYLON.Action} action - the action to be registered
  28078. * @return {BABYLON.Action} the action amended (prepared) after registration
  28079. */
  28080. ActionManager.prototype.registerAction = function (action) {
  28081. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28082. if (this.getScene().actionManager !== this) {
  28083. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28084. return null;
  28085. }
  28086. }
  28087. this.actions.push(action);
  28088. action._actionManager = this;
  28089. action._prepare();
  28090. return action;
  28091. };
  28092. /**
  28093. * Process a specific trigger
  28094. * @param {number} trigger - the trigger to process
  28095. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28096. */
  28097. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28098. for (var index = 0; index < this.actions.length; index++) {
  28099. var action = this.actions[index];
  28100. if (action.trigger === trigger) {
  28101. if (trigger === ActionManager.OnKeyUpTrigger
  28102. || trigger === ActionManager.OnKeyDownTrigger) {
  28103. var parameter = action.getTriggerParameter();
  28104. if (parameter) {
  28105. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28106. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28107. if (actualkey !== parameter.toLowerCase()) {
  28108. continue;
  28109. }
  28110. }
  28111. }
  28112. action._executeCurrent(evt);
  28113. }
  28114. }
  28115. };
  28116. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28117. var properties = propertyPath.split(".");
  28118. for (var index = 0; index < properties.length - 1; index++) {
  28119. target = target[properties[index]];
  28120. }
  28121. return target;
  28122. };
  28123. ActionManager.prototype._getProperty = function (propertyPath) {
  28124. var properties = propertyPath.split(".");
  28125. return properties[properties.length - 1];
  28126. };
  28127. // Statics
  28128. ActionManager._NothingTrigger = 0;
  28129. ActionManager._OnPickTrigger = 1;
  28130. ActionManager._OnLeftPickTrigger = 2;
  28131. ActionManager._OnRightPickTrigger = 3;
  28132. ActionManager._OnCenterPickTrigger = 4;
  28133. ActionManager._OnPointerOverTrigger = 5;
  28134. ActionManager._OnPointerOutTrigger = 6;
  28135. ActionManager._OnEveryFrameTrigger = 7;
  28136. ActionManager._OnIntersectionEnterTrigger = 8;
  28137. ActionManager._OnIntersectionExitTrigger = 9;
  28138. ActionManager._OnKeyDownTrigger = 10;
  28139. ActionManager._OnKeyUpTrigger = 11;
  28140. ActionManager._OnPickUpTrigger = 12;
  28141. return ActionManager;
  28142. })();
  28143. BABYLON.ActionManager = ActionManager;
  28144. })(BABYLON || (BABYLON = {}));
  28145. var BABYLON;
  28146. (function (BABYLON) {
  28147. var InterpolateValueAction = (function (_super) {
  28148. __extends(InterpolateValueAction, _super);
  28149. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28150. if (duration === void 0) { duration = 1000; }
  28151. _super.call(this, triggerOptions, condition);
  28152. this.propertyPath = propertyPath;
  28153. this.value = value;
  28154. this.duration = duration;
  28155. this.stopOtherAnimations = stopOtherAnimations;
  28156. this._target = target;
  28157. }
  28158. InterpolateValueAction.prototype._prepare = function () {
  28159. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28160. this._property = this._getProperty(this.propertyPath);
  28161. };
  28162. InterpolateValueAction.prototype.execute = function () {
  28163. var scene = this._actionManager.getScene();
  28164. var keys = [
  28165. {
  28166. frame: 0,
  28167. value: this._target[this._property]
  28168. }, {
  28169. frame: 100,
  28170. value: this.value
  28171. }
  28172. ];
  28173. var dataType;
  28174. if (typeof this.value === "number") {
  28175. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28176. }
  28177. else if (this.value instanceof BABYLON.Color3) {
  28178. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28179. }
  28180. else if (this.value instanceof BABYLON.Vector3) {
  28181. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28182. }
  28183. else if (this.value instanceof BABYLON.Matrix) {
  28184. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28185. }
  28186. else if (this.value instanceof BABYLON.Quaternion) {
  28187. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28188. }
  28189. else {
  28190. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28191. return;
  28192. }
  28193. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28194. animation.setKeys(keys);
  28195. if (this.stopOtherAnimations) {
  28196. scene.stopAnimation(this._target);
  28197. }
  28198. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28199. };
  28200. return InterpolateValueAction;
  28201. })(BABYLON.Action);
  28202. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28203. })(BABYLON || (BABYLON = {}));
  28204. var BABYLON;
  28205. (function (BABYLON) {
  28206. var SwitchBooleanAction = (function (_super) {
  28207. __extends(SwitchBooleanAction, _super);
  28208. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28209. _super.call(this, triggerOptions, condition);
  28210. this.propertyPath = propertyPath;
  28211. this._target = target;
  28212. }
  28213. SwitchBooleanAction.prototype._prepare = function () {
  28214. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28215. this._property = this._getProperty(this.propertyPath);
  28216. };
  28217. SwitchBooleanAction.prototype.execute = function () {
  28218. this._target[this._property] = !this._target[this._property];
  28219. };
  28220. return SwitchBooleanAction;
  28221. })(BABYLON.Action);
  28222. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28223. var SetStateAction = (function (_super) {
  28224. __extends(SetStateAction, _super);
  28225. function SetStateAction(triggerOptions, target, value, condition) {
  28226. _super.call(this, triggerOptions, condition);
  28227. this.value = value;
  28228. this._target = target;
  28229. }
  28230. SetStateAction.prototype.execute = function () {
  28231. this._target.state = this.value;
  28232. };
  28233. return SetStateAction;
  28234. })(BABYLON.Action);
  28235. BABYLON.SetStateAction = SetStateAction;
  28236. var SetValueAction = (function (_super) {
  28237. __extends(SetValueAction, _super);
  28238. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28239. _super.call(this, triggerOptions, condition);
  28240. this.propertyPath = propertyPath;
  28241. this.value = value;
  28242. this._target = target;
  28243. }
  28244. SetValueAction.prototype._prepare = function () {
  28245. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28246. this._property = this._getProperty(this.propertyPath);
  28247. };
  28248. SetValueAction.prototype.execute = function () {
  28249. this._target[this._property] = this.value;
  28250. };
  28251. return SetValueAction;
  28252. })(BABYLON.Action);
  28253. BABYLON.SetValueAction = SetValueAction;
  28254. var IncrementValueAction = (function (_super) {
  28255. __extends(IncrementValueAction, _super);
  28256. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28257. _super.call(this, triggerOptions, condition);
  28258. this.propertyPath = propertyPath;
  28259. this.value = value;
  28260. this._target = target;
  28261. }
  28262. IncrementValueAction.prototype._prepare = function () {
  28263. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28264. this._property = this._getProperty(this.propertyPath);
  28265. if (typeof this._target[this._property] !== "number") {
  28266. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28267. }
  28268. };
  28269. IncrementValueAction.prototype.execute = function () {
  28270. this._target[this._property] += this.value;
  28271. };
  28272. return IncrementValueAction;
  28273. })(BABYLON.Action);
  28274. BABYLON.IncrementValueAction = IncrementValueAction;
  28275. var PlayAnimationAction = (function (_super) {
  28276. __extends(PlayAnimationAction, _super);
  28277. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28278. _super.call(this, triggerOptions, condition);
  28279. this.from = from;
  28280. this.to = to;
  28281. this.loop = loop;
  28282. this._target = target;
  28283. }
  28284. PlayAnimationAction.prototype._prepare = function () {
  28285. };
  28286. PlayAnimationAction.prototype.execute = function () {
  28287. var scene = this._actionManager.getScene();
  28288. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28289. };
  28290. return PlayAnimationAction;
  28291. })(BABYLON.Action);
  28292. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28293. var StopAnimationAction = (function (_super) {
  28294. __extends(StopAnimationAction, _super);
  28295. function StopAnimationAction(triggerOptions, target, condition) {
  28296. _super.call(this, triggerOptions, condition);
  28297. this._target = target;
  28298. }
  28299. StopAnimationAction.prototype._prepare = function () {
  28300. };
  28301. StopAnimationAction.prototype.execute = function () {
  28302. var scene = this._actionManager.getScene();
  28303. scene.stopAnimation(this._target);
  28304. };
  28305. return StopAnimationAction;
  28306. })(BABYLON.Action);
  28307. BABYLON.StopAnimationAction = StopAnimationAction;
  28308. var DoNothingAction = (function (_super) {
  28309. __extends(DoNothingAction, _super);
  28310. function DoNothingAction(triggerOptions, condition) {
  28311. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28312. _super.call(this, triggerOptions, condition);
  28313. }
  28314. DoNothingAction.prototype.execute = function () {
  28315. };
  28316. return DoNothingAction;
  28317. })(BABYLON.Action);
  28318. BABYLON.DoNothingAction = DoNothingAction;
  28319. var CombineAction = (function (_super) {
  28320. __extends(CombineAction, _super);
  28321. function CombineAction(triggerOptions, children, condition) {
  28322. _super.call(this, triggerOptions, condition);
  28323. this.children = children;
  28324. }
  28325. CombineAction.prototype._prepare = function () {
  28326. for (var index = 0; index < this.children.length; index++) {
  28327. this.children[index]._actionManager = this._actionManager;
  28328. this.children[index]._prepare();
  28329. }
  28330. };
  28331. CombineAction.prototype.execute = function (evt) {
  28332. for (var index = 0; index < this.children.length; index++) {
  28333. this.children[index].execute(evt);
  28334. }
  28335. };
  28336. return CombineAction;
  28337. })(BABYLON.Action);
  28338. BABYLON.CombineAction = CombineAction;
  28339. var ExecuteCodeAction = (function (_super) {
  28340. __extends(ExecuteCodeAction, _super);
  28341. function ExecuteCodeAction(triggerOptions, func, condition) {
  28342. _super.call(this, triggerOptions, condition);
  28343. this.func = func;
  28344. }
  28345. ExecuteCodeAction.prototype.execute = function (evt) {
  28346. this.func(evt);
  28347. };
  28348. return ExecuteCodeAction;
  28349. })(BABYLON.Action);
  28350. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28351. var SetParentAction = (function (_super) {
  28352. __extends(SetParentAction, _super);
  28353. function SetParentAction(triggerOptions, target, parent, condition) {
  28354. _super.call(this, triggerOptions, condition);
  28355. this._target = target;
  28356. this._parent = parent;
  28357. }
  28358. SetParentAction.prototype._prepare = function () {
  28359. };
  28360. SetParentAction.prototype.execute = function () {
  28361. if (this._target.parent === this._parent) {
  28362. return;
  28363. }
  28364. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28365. invertParentWorldMatrix.invert();
  28366. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28367. this._target.parent = this._parent;
  28368. };
  28369. return SetParentAction;
  28370. })(BABYLON.Action);
  28371. BABYLON.SetParentAction = SetParentAction;
  28372. var PlaySoundAction = (function (_super) {
  28373. __extends(PlaySoundAction, _super);
  28374. function PlaySoundAction(triggerOptions, sound, condition) {
  28375. _super.call(this, triggerOptions, condition);
  28376. this._sound = sound;
  28377. }
  28378. PlaySoundAction.prototype._prepare = function () {
  28379. };
  28380. PlaySoundAction.prototype.execute = function () {
  28381. if (this._sound !== undefined)
  28382. this._sound.play();
  28383. };
  28384. return PlaySoundAction;
  28385. })(BABYLON.Action);
  28386. BABYLON.PlaySoundAction = PlaySoundAction;
  28387. var StopSoundAction = (function (_super) {
  28388. __extends(StopSoundAction, _super);
  28389. function StopSoundAction(triggerOptions, sound, condition) {
  28390. _super.call(this, triggerOptions, condition);
  28391. this._sound = sound;
  28392. }
  28393. StopSoundAction.prototype._prepare = function () {
  28394. };
  28395. StopSoundAction.prototype.execute = function () {
  28396. if (this._sound !== undefined)
  28397. this._sound.stop();
  28398. };
  28399. return StopSoundAction;
  28400. })(BABYLON.Action);
  28401. BABYLON.StopSoundAction = StopSoundAction;
  28402. })(BABYLON || (BABYLON = {}));
  28403. var BABYLON;
  28404. (function (BABYLON) {
  28405. var Geometry = (function () {
  28406. function Geometry(id, scene, vertexData, updatable, mesh) {
  28407. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28408. this._totalVertices = 0;
  28409. this._indices = [];
  28410. this._isDisposed = false;
  28411. this.id = id;
  28412. this._engine = scene.getEngine();
  28413. this._meshes = [];
  28414. this._scene = scene;
  28415. // vertexData
  28416. if (vertexData) {
  28417. this.setAllVerticesData(vertexData, updatable);
  28418. }
  28419. else {
  28420. this._totalVertices = 0;
  28421. this._indices = [];
  28422. }
  28423. // applyToMesh
  28424. if (mesh) {
  28425. this.applyToMesh(mesh);
  28426. mesh.computeWorldMatrix(true);
  28427. }
  28428. }
  28429. Geometry.prototype.getScene = function () {
  28430. return this._scene;
  28431. };
  28432. Geometry.prototype.getEngine = function () {
  28433. return this._engine;
  28434. };
  28435. Geometry.prototype.isReady = function () {
  28436. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28437. };
  28438. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28439. vertexData.applyToGeometry(this, updatable);
  28440. this.notifyUpdate();
  28441. };
  28442. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28443. this._vertexBuffers = this._vertexBuffers || {};
  28444. if (this._vertexBuffers[kind]) {
  28445. this._vertexBuffers[kind].dispose();
  28446. }
  28447. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28448. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28449. stride = this._vertexBuffers[kind].getStrideSize();
  28450. this._totalVertices = data.length / stride;
  28451. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28452. var meshes = this._meshes;
  28453. var numOfMeshes = meshes.length;
  28454. for (var index = 0; index < numOfMeshes; index++) {
  28455. var mesh = meshes[index];
  28456. mesh._resetPointsArrayCache();
  28457. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28458. mesh._createGlobalSubMesh();
  28459. mesh.computeWorldMatrix(true);
  28460. }
  28461. }
  28462. this.notifyUpdate(kind);
  28463. };
  28464. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28465. var vertexBuffer = this.getVertexBuffer(kind);
  28466. if (!vertexBuffer) {
  28467. return;
  28468. }
  28469. vertexBuffer.updateDirectly(data, offset);
  28470. this.notifyUpdate(kind);
  28471. };
  28472. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28473. var vertexBuffer = this.getVertexBuffer(kind);
  28474. if (!vertexBuffer) {
  28475. return;
  28476. }
  28477. vertexBuffer.update(data);
  28478. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28479. var extend;
  28480. var stride = vertexBuffer.getStrideSize();
  28481. this._totalVertices = data.length / stride;
  28482. if (updateExtends) {
  28483. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28484. }
  28485. var meshes = this._meshes;
  28486. var numOfMeshes = meshes.length;
  28487. for (var index = 0; index < numOfMeshes; index++) {
  28488. var mesh = meshes[index];
  28489. mesh._resetPointsArrayCache();
  28490. if (updateExtends) {
  28491. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28492. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28493. var subMesh = mesh.subMeshes[subIndex];
  28494. subMesh.refreshBoundingInfo();
  28495. }
  28496. }
  28497. }
  28498. }
  28499. this.notifyUpdate(kind);
  28500. };
  28501. Geometry.prototype.getTotalVertices = function () {
  28502. if (!this.isReady()) {
  28503. return 0;
  28504. }
  28505. return this._totalVertices;
  28506. };
  28507. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28508. var vertexBuffer = this.getVertexBuffer(kind);
  28509. if (!vertexBuffer) {
  28510. return null;
  28511. }
  28512. var orig = vertexBuffer.getData();
  28513. if (!copyWhenShared || this._meshes.length === 1) {
  28514. return orig;
  28515. }
  28516. else {
  28517. var len = orig.length;
  28518. var copy = [];
  28519. for (var i = 0; i < len; i++) {
  28520. copy.push(orig[i]);
  28521. }
  28522. return copy;
  28523. }
  28524. };
  28525. Geometry.prototype.getVertexBuffer = function (kind) {
  28526. if (!this.isReady()) {
  28527. return null;
  28528. }
  28529. return this._vertexBuffers[kind];
  28530. };
  28531. Geometry.prototype.getVertexBuffers = function () {
  28532. if (!this.isReady()) {
  28533. return null;
  28534. }
  28535. return this._vertexBuffers;
  28536. };
  28537. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28538. if (!this._vertexBuffers) {
  28539. if (this._delayInfo) {
  28540. return this._delayInfo.indexOf(kind) !== -1;
  28541. }
  28542. return false;
  28543. }
  28544. return this._vertexBuffers[kind] !== undefined;
  28545. };
  28546. Geometry.prototype.getVerticesDataKinds = function () {
  28547. var result = [];
  28548. if (!this._vertexBuffers && this._delayInfo) {
  28549. for (var kind in this._delayInfo) {
  28550. result.push(kind);
  28551. }
  28552. }
  28553. else {
  28554. for (kind in this._vertexBuffers) {
  28555. result.push(kind);
  28556. }
  28557. }
  28558. return result;
  28559. };
  28560. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28561. if (this._indexBuffer) {
  28562. this._engine._releaseBuffer(this._indexBuffer);
  28563. }
  28564. this._indices = indices;
  28565. if (this._meshes.length !== 0 && this._indices) {
  28566. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28567. }
  28568. if (totalVertices !== undefined) {
  28569. this._totalVertices = totalVertices;
  28570. }
  28571. var meshes = this._meshes;
  28572. var numOfMeshes = meshes.length;
  28573. for (var index = 0; index < numOfMeshes; index++) {
  28574. meshes[index]._createGlobalSubMesh();
  28575. }
  28576. this.notifyUpdate();
  28577. };
  28578. Geometry.prototype.getTotalIndices = function () {
  28579. if (!this.isReady()) {
  28580. return 0;
  28581. }
  28582. return this._indices.length;
  28583. };
  28584. Geometry.prototype.getIndices = function (copyWhenShared) {
  28585. if (!this.isReady()) {
  28586. return null;
  28587. }
  28588. var orig = this._indices;
  28589. if (!copyWhenShared || this._meshes.length === 1) {
  28590. return orig;
  28591. }
  28592. else {
  28593. var len = orig.length;
  28594. var copy = [];
  28595. for (var i = 0; i < len; i++) {
  28596. copy.push(orig[i]);
  28597. }
  28598. return copy;
  28599. }
  28600. };
  28601. Geometry.prototype.getIndexBuffer = function () {
  28602. if (!this.isReady()) {
  28603. return null;
  28604. }
  28605. return this._indexBuffer;
  28606. };
  28607. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28608. var meshes = this._meshes;
  28609. var index = meshes.indexOf(mesh);
  28610. if (index === -1) {
  28611. return;
  28612. }
  28613. for (var kind in this._vertexBuffers) {
  28614. this._vertexBuffers[kind].dispose();
  28615. }
  28616. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28617. this._indexBuffer = null;
  28618. }
  28619. meshes.splice(index, 1);
  28620. mesh._geometry = null;
  28621. if (meshes.length === 0 && shouldDispose) {
  28622. this.dispose();
  28623. }
  28624. };
  28625. Geometry.prototype.applyToMesh = function (mesh) {
  28626. if (mesh._geometry === this) {
  28627. return;
  28628. }
  28629. var previousGeometry = mesh._geometry;
  28630. if (previousGeometry) {
  28631. previousGeometry.releaseForMesh(mesh);
  28632. }
  28633. var meshes = this._meshes;
  28634. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28635. mesh._geometry = this;
  28636. this._scene.pushGeometry(this);
  28637. meshes.push(mesh);
  28638. if (this.isReady()) {
  28639. this._applyToMesh(mesh);
  28640. }
  28641. else {
  28642. mesh._boundingInfo = this._boundingInfo;
  28643. }
  28644. };
  28645. Geometry.prototype._applyToMesh = function (mesh) {
  28646. var numOfMeshes = this._meshes.length;
  28647. // vertexBuffers
  28648. for (var kind in this._vertexBuffers) {
  28649. if (numOfMeshes === 1) {
  28650. this._vertexBuffers[kind].create();
  28651. }
  28652. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28653. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28654. mesh._resetPointsArrayCache();
  28655. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28656. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28657. mesh._createGlobalSubMesh();
  28658. //bounding info was just created again, world matrix should be applied again.
  28659. mesh._updateBoundingInfo();
  28660. }
  28661. }
  28662. // indexBuffer
  28663. if (numOfMeshes === 1 && this._indices) {
  28664. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28665. }
  28666. if (this._indexBuffer) {
  28667. this._indexBuffer.references = numOfMeshes;
  28668. }
  28669. };
  28670. Geometry.prototype.notifyUpdate = function (kind) {
  28671. if (this.onGeometryUpdated) {
  28672. this.onGeometryUpdated(this, kind);
  28673. }
  28674. };
  28675. Geometry.prototype.load = function (scene, onLoaded) {
  28676. var _this = this;
  28677. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28678. return;
  28679. }
  28680. if (this.isReady()) {
  28681. if (onLoaded) {
  28682. onLoaded();
  28683. }
  28684. return;
  28685. }
  28686. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28687. scene._addPendingData(this);
  28688. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28689. _this._delayLoadingFunction(JSON.parse(data), _this);
  28690. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28691. _this._delayInfo = [];
  28692. scene._removePendingData(_this);
  28693. var meshes = _this._meshes;
  28694. var numOfMeshes = meshes.length;
  28695. for (var index = 0; index < numOfMeshes; index++) {
  28696. _this._applyToMesh(meshes[index]);
  28697. }
  28698. if (onLoaded) {
  28699. onLoaded();
  28700. }
  28701. }, function () { }, scene.database);
  28702. };
  28703. Geometry.prototype.isDisposed = function () {
  28704. return this._isDisposed;
  28705. };
  28706. Geometry.prototype.dispose = function () {
  28707. var meshes = this._meshes;
  28708. var numOfMeshes = meshes.length;
  28709. var index;
  28710. for (index = 0; index < numOfMeshes; index++) {
  28711. this.releaseForMesh(meshes[index]);
  28712. }
  28713. this._meshes = [];
  28714. for (var kind in this._vertexBuffers) {
  28715. this._vertexBuffers[kind].dispose();
  28716. }
  28717. this._vertexBuffers = [];
  28718. this._totalVertices = 0;
  28719. if (this._indexBuffer) {
  28720. this._engine._releaseBuffer(this._indexBuffer);
  28721. }
  28722. this._indexBuffer = null;
  28723. this._indices = [];
  28724. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28725. this.delayLoadingFile = null;
  28726. this._delayLoadingFunction = null;
  28727. this._delayInfo = [];
  28728. this._boundingInfo = null; // todo: .dispose()
  28729. this._scene.removeGeometry(this);
  28730. this._isDisposed = true;
  28731. };
  28732. Geometry.prototype.copy = function (id) {
  28733. var vertexData = new BABYLON.VertexData();
  28734. vertexData.indices = [];
  28735. var indices = this.getIndices();
  28736. for (var index = 0; index < indices.length; index++) {
  28737. vertexData.indices.push(indices[index]);
  28738. }
  28739. var updatable = false;
  28740. var stopChecking = false;
  28741. for (var kind in this._vertexBuffers) {
  28742. // using slice() to make a copy of the array and not just reference it
  28743. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28744. if (!stopChecking) {
  28745. updatable = this.getVertexBuffer(kind).isUpdatable();
  28746. stopChecking = !updatable;
  28747. }
  28748. }
  28749. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28750. geometry.delayLoadState = this.delayLoadState;
  28751. geometry.delayLoadingFile = this.delayLoadingFile;
  28752. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28753. for (kind in this._delayInfo) {
  28754. geometry._delayInfo = geometry._delayInfo || [];
  28755. geometry._delayInfo.push(kind);
  28756. }
  28757. // Bounding info
  28758. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28759. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28760. return geometry;
  28761. };
  28762. // Statics
  28763. Geometry.ExtractFromMesh = function (mesh, id) {
  28764. var geometry = mesh._geometry;
  28765. if (!geometry) {
  28766. return null;
  28767. }
  28768. return geometry.copy(id);
  28769. };
  28770. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28771. // be aware Math.random() could cause collisions
  28772. Geometry.RandomId = function () {
  28773. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28774. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28775. return v.toString(16);
  28776. });
  28777. };
  28778. return Geometry;
  28779. })();
  28780. BABYLON.Geometry = Geometry;
  28781. /////// Primitives //////////////////////////////////////////////
  28782. var Geometry;
  28783. (function (Geometry) {
  28784. var Primitives;
  28785. (function (Primitives) {
  28786. /// Abstract class
  28787. var _Primitive = (function (_super) {
  28788. __extends(_Primitive, _super);
  28789. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28790. this._beingRegenerated = true;
  28791. this._canBeRegenerated = canBeRegenerated;
  28792. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28793. this._beingRegenerated = false;
  28794. }
  28795. _Primitive.prototype.canBeRegenerated = function () {
  28796. return this._canBeRegenerated;
  28797. };
  28798. _Primitive.prototype.regenerate = function () {
  28799. if (!this._canBeRegenerated) {
  28800. return;
  28801. }
  28802. this._beingRegenerated = true;
  28803. this.setAllVerticesData(this._regenerateVertexData(), false);
  28804. this._beingRegenerated = false;
  28805. };
  28806. _Primitive.prototype.asNewGeometry = function (id) {
  28807. return _super.prototype.copy.call(this, id);
  28808. };
  28809. // overrides
  28810. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28811. if (!this._beingRegenerated) {
  28812. return;
  28813. }
  28814. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28815. };
  28816. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28817. if (!this._beingRegenerated) {
  28818. return;
  28819. }
  28820. _super.prototype.setVerticesData.call(this, kind, data, false);
  28821. };
  28822. // to override
  28823. // protected
  28824. _Primitive.prototype._regenerateVertexData = function () {
  28825. throw new Error("Abstract method");
  28826. };
  28827. _Primitive.prototype.copy = function (id) {
  28828. throw new Error("Must be overriden in sub-classes.");
  28829. };
  28830. return _Primitive;
  28831. })(Geometry);
  28832. Primitives._Primitive = _Primitive;
  28833. var Ribbon = (function (_super) {
  28834. __extends(Ribbon, _super);
  28835. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28836. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28837. this.pathArray = pathArray;
  28838. this.closeArray = closeArray;
  28839. this.closePath = closePath;
  28840. this.offset = offset;
  28841. this.side = side;
  28842. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28843. }
  28844. Ribbon.prototype._regenerateVertexData = function () {
  28845. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28846. };
  28847. Ribbon.prototype.copy = function (id) {
  28848. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28849. };
  28850. return Ribbon;
  28851. })(_Primitive);
  28852. Primitives.Ribbon = Ribbon;
  28853. var Box = (function (_super) {
  28854. __extends(Box, _super);
  28855. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28857. this.size = size;
  28858. this.side = side;
  28859. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28860. }
  28861. Box.prototype._regenerateVertexData = function () {
  28862. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28863. };
  28864. Box.prototype.copy = function (id) {
  28865. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28866. };
  28867. return Box;
  28868. })(_Primitive);
  28869. Primitives.Box = Box;
  28870. var Sphere = (function (_super) {
  28871. __extends(Sphere, _super);
  28872. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28873. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28874. this.segments = segments;
  28875. this.diameter = diameter;
  28876. this.side = side;
  28877. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28878. }
  28879. Sphere.prototype._regenerateVertexData = function () {
  28880. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  28881. };
  28882. Sphere.prototype.copy = function (id) {
  28883. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28884. };
  28885. return Sphere;
  28886. })(_Primitive);
  28887. Primitives.Sphere = Sphere;
  28888. var Cylinder = (function (_super) {
  28889. __extends(Cylinder, _super);
  28890. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28891. if (subdivisions === void 0) { subdivisions = 1; }
  28892. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28893. this.height = height;
  28894. this.diameterTop = diameterTop;
  28895. this.diameterBottom = diameterBottom;
  28896. this.tessellation = tessellation;
  28897. this.subdivisions = subdivisions;
  28898. this.side = side;
  28899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28900. }
  28901. Cylinder.prototype._regenerateVertexData = function () {
  28902. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  28903. };
  28904. Cylinder.prototype.copy = function (id) {
  28905. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28906. };
  28907. return Cylinder;
  28908. })(_Primitive);
  28909. Primitives.Cylinder = Cylinder;
  28910. var Torus = (function (_super) {
  28911. __extends(Torus, _super);
  28912. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28913. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28914. this.diameter = diameter;
  28915. this.thickness = thickness;
  28916. this.tessellation = tessellation;
  28917. this.side = side;
  28918. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28919. }
  28920. Torus.prototype._regenerateVertexData = function () {
  28921. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  28922. };
  28923. Torus.prototype.copy = function (id) {
  28924. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28925. };
  28926. return Torus;
  28927. })(_Primitive);
  28928. Primitives.Torus = Torus;
  28929. var Ground = (function (_super) {
  28930. __extends(Ground, _super);
  28931. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28932. this.width = width;
  28933. this.height = height;
  28934. this.subdivisions = subdivisions;
  28935. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28936. }
  28937. Ground.prototype._regenerateVertexData = function () {
  28938. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  28939. };
  28940. Ground.prototype.copy = function (id) {
  28941. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28942. };
  28943. return Ground;
  28944. })(_Primitive);
  28945. Primitives.Ground = Ground;
  28946. var TiledGround = (function (_super) {
  28947. __extends(TiledGround, _super);
  28948. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28949. this.xmin = xmin;
  28950. this.zmin = zmin;
  28951. this.xmax = xmax;
  28952. this.zmax = zmax;
  28953. this.subdivisions = subdivisions;
  28954. this.precision = precision;
  28955. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28956. }
  28957. TiledGround.prototype._regenerateVertexData = function () {
  28958. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  28959. };
  28960. TiledGround.prototype.copy = function (id) {
  28961. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28962. };
  28963. return TiledGround;
  28964. })(_Primitive);
  28965. Primitives.TiledGround = TiledGround;
  28966. var Plane = (function (_super) {
  28967. __extends(Plane, _super);
  28968. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28969. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28970. this.size = size;
  28971. this.side = side;
  28972. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28973. }
  28974. Plane.prototype._regenerateVertexData = function () {
  28975. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  28976. };
  28977. Plane.prototype.copy = function (id) {
  28978. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28979. };
  28980. return Plane;
  28981. })(_Primitive);
  28982. Primitives.Plane = Plane;
  28983. var TorusKnot = (function (_super) {
  28984. __extends(TorusKnot, _super);
  28985. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28986. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28987. this.radius = radius;
  28988. this.tube = tube;
  28989. this.radialSegments = radialSegments;
  28990. this.tubularSegments = tubularSegments;
  28991. this.p = p;
  28992. this.q = q;
  28993. this.side = side;
  28994. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28995. }
  28996. TorusKnot.prototype._regenerateVertexData = function () {
  28997. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  28998. };
  28999. TorusKnot.prototype.copy = function (id) {
  29000. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29001. };
  29002. return TorusKnot;
  29003. })(_Primitive);
  29004. Primitives.TorusKnot = TorusKnot;
  29005. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29006. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29007. })(BABYLON || (BABYLON = {}));
  29008. var BABYLON;
  29009. (function (BABYLON) {
  29010. var GroundMesh = (function (_super) {
  29011. __extends(GroundMesh, _super);
  29012. function GroundMesh(name, scene) {
  29013. _super.call(this, name, scene);
  29014. this.generateOctree = false;
  29015. this._worldInverse = new BABYLON.Matrix();
  29016. }
  29017. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29018. get: function () {
  29019. return this._subdivisions;
  29020. },
  29021. enumerable: true,
  29022. configurable: true
  29023. });
  29024. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29025. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29026. this._subdivisions = chunksCount;
  29027. this.subdivide(this._subdivisions);
  29028. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29029. };
  29030. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29031. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29032. this.getWorldMatrix().invertToRef(this._worldInverse);
  29033. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29034. var pickInfo = this.intersects(ray);
  29035. if (pickInfo.hit) {
  29036. return pickInfo.pickedPoint.y;
  29037. }
  29038. return 0;
  29039. };
  29040. return GroundMesh;
  29041. })(BABYLON.Mesh);
  29042. BABYLON.GroundMesh = GroundMesh;
  29043. })(BABYLON || (BABYLON = {}));
  29044. var BABYLON;
  29045. (function (BABYLON) {
  29046. var LinesMesh = (function (_super) {
  29047. __extends(LinesMesh, _super);
  29048. function LinesMesh(name, scene, updatable) {
  29049. if (updatable === void 0) { updatable = false; }
  29050. _super.call(this, name, scene);
  29051. this.color = new BABYLON.Color3(1, 1, 1);
  29052. this.alpha = 1;
  29053. this._indices = new Array();
  29054. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29055. attributes: ["position"],
  29056. uniforms: ["worldViewProjection", "color"],
  29057. needAlphaBlending: true
  29058. });
  29059. }
  29060. Object.defineProperty(LinesMesh.prototype, "material", {
  29061. get: function () {
  29062. return this._colorShader;
  29063. },
  29064. enumerable: true,
  29065. configurable: true
  29066. });
  29067. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29068. get: function () {
  29069. return false;
  29070. },
  29071. enumerable: true,
  29072. configurable: true
  29073. });
  29074. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29075. get: function () {
  29076. return false;
  29077. },
  29078. enumerable: true,
  29079. configurable: true
  29080. });
  29081. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29082. var engine = this.getScene().getEngine();
  29083. var indexToBind = this._geometry.getIndexBuffer();
  29084. // VBOs
  29085. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29086. // Color
  29087. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29088. };
  29089. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29090. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29091. return;
  29092. }
  29093. var engine = this.getScene().getEngine();
  29094. // Draw order
  29095. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29096. };
  29097. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29098. return null;
  29099. };
  29100. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29101. this._colorShader.dispose();
  29102. _super.prototype.dispose.call(this, doNotRecurse);
  29103. };
  29104. return LinesMesh;
  29105. })(BABYLON.Mesh);
  29106. BABYLON.LinesMesh = LinesMesh;
  29107. })(BABYLON || (BABYLON = {}));
  29108. var BABYLON;
  29109. (function (BABYLON) {
  29110. var OutlineRenderer = (function () {
  29111. function OutlineRenderer(scene) {
  29112. this._scene = scene;
  29113. }
  29114. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29115. var _this = this;
  29116. if (useOverlay === void 0) { useOverlay = false; }
  29117. var scene = this._scene;
  29118. var engine = this._scene.getEngine();
  29119. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29120. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29121. return;
  29122. }
  29123. var mesh = subMesh.getRenderingMesh();
  29124. var material = subMesh.getMaterial();
  29125. engine.enableEffect(this._effect);
  29126. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29127. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29128. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29129. // Bones
  29130. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29131. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29132. }
  29133. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29134. // Alpha test
  29135. if (material && material.needAlphaTesting()) {
  29136. var alphaTexture = material.getAlphaTestTexture();
  29137. this._effect.setTexture("diffuseSampler", alphaTexture);
  29138. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29139. }
  29140. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29141. };
  29142. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29143. var defines = [];
  29144. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29145. var mesh = subMesh.getMesh();
  29146. var material = subMesh.getMaterial();
  29147. // Alpha test
  29148. if (material && material.needAlphaTesting()) {
  29149. defines.push("#define ALPHATEST");
  29150. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29151. attribs.push(BABYLON.VertexBuffer.UVKind);
  29152. defines.push("#define UV1");
  29153. }
  29154. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29155. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29156. defines.push("#define UV2");
  29157. }
  29158. }
  29159. // Bones
  29160. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29161. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29162. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29163. defines.push("#define BONES");
  29164. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29165. }
  29166. // Instances
  29167. if (useInstances) {
  29168. defines.push("#define INSTANCES");
  29169. attribs.push("world0");
  29170. attribs.push("world1");
  29171. attribs.push("world2");
  29172. attribs.push("world3");
  29173. }
  29174. // Get correct effect
  29175. var join = defines.join("\n");
  29176. if (this._cachedDefines !== join) {
  29177. this._cachedDefines = join;
  29178. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29179. }
  29180. return this._effect.isReady();
  29181. };
  29182. return OutlineRenderer;
  29183. })();
  29184. BABYLON.OutlineRenderer = OutlineRenderer;
  29185. })(BABYLON || (BABYLON = {}));
  29186. var BABYLON;
  29187. (function (BABYLON) {
  29188. var MeshAssetTask = (function () {
  29189. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29190. this.name = name;
  29191. this.meshesNames = meshesNames;
  29192. this.rootUrl = rootUrl;
  29193. this.sceneFilename = sceneFilename;
  29194. this.isCompleted = false;
  29195. }
  29196. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29197. var _this = this;
  29198. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29199. _this.loadedMeshes = meshes;
  29200. _this.loadedParticleSystems = particleSystems;
  29201. _this.loadedSkeletons = skeletons;
  29202. _this.isCompleted = true;
  29203. if (_this.onSuccess) {
  29204. _this.onSuccess(_this);
  29205. }
  29206. onSuccess();
  29207. }, null, function () {
  29208. if (_this.onError) {
  29209. _this.onError(_this);
  29210. }
  29211. onError();
  29212. });
  29213. };
  29214. return MeshAssetTask;
  29215. })();
  29216. BABYLON.MeshAssetTask = MeshAssetTask;
  29217. var TextFileAssetTask = (function () {
  29218. function TextFileAssetTask(name, url) {
  29219. this.name = name;
  29220. this.url = url;
  29221. this.isCompleted = false;
  29222. }
  29223. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29224. var _this = this;
  29225. BABYLON.Tools.LoadFile(this.url, function (data) {
  29226. _this.text = data;
  29227. _this.isCompleted = true;
  29228. if (_this.onSuccess) {
  29229. _this.onSuccess(_this);
  29230. }
  29231. onSuccess();
  29232. }, null, scene.database, false, function () {
  29233. if (_this.onError) {
  29234. _this.onError(_this);
  29235. }
  29236. onError();
  29237. });
  29238. };
  29239. return TextFileAssetTask;
  29240. })();
  29241. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29242. var BinaryFileAssetTask = (function () {
  29243. function BinaryFileAssetTask(name, url) {
  29244. this.name = name;
  29245. this.url = url;
  29246. this.isCompleted = false;
  29247. }
  29248. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29249. var _this = this;
  29250. BABYLON.Tools.LoadFile(this.url, function (data) {
  29251. _this.data = data;
  29252. _this.isCompleted = true;
  29253. if (_this.onSuccess) {
  29254. _this.onSuccess(_this);
  29255. }
  29256. onSuccess();
  29257. }, null, scene.database, true, function () {
  29258. if (_this.onError) {
  29259. _this.onError(_this);
  29260. }
  29261. onError();
  29262. });
  29263. };
  29264. return BinaryFileAssetTask;
  29265. })();
  29266. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29267. var ImageAssetTask = (function () {
  29268. function ImageAssetTask(name, url) {
  29269. this.name = name;
  29270. this.url = url;
  29271. this.isCompleted = false;
  29272. }
  29273. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29274. var _this = this;
  29275. var img = new Image();
  29276. img.onload = function () {
  29277. _this.image = img;
  29278. _this.isCompleted = true;
  29279. if (_this.onSuccess) {
  29280. _this.onSuccess(_this);
  29281. }
  29282. onSuccess();
  29283. };
  29284. img.onerror = function () {
  29285. if (_this.onError) {
  29286. _this.onError(_this);
  29287. }
  29288. onError();
  29289. };
  29290. img.src = this.url;
  29291. };
  29292. return ImageAssetTask;
  29293. })();
  29294. BABYLON.ImageAssetTask = ImageAssetTask;
  29295. var TextureAssetTask = (function () {
  29296. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29298. this.name = name;
  29299. this.url = url;
  29300. this.noMipmap = noMipmap;
  29301. this.invertY = invertY;
  29302. this.samplingMode = samplingMode;
  29303. this.isCompleted = false;
  29304. }
  29305. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29306. var _this = this;
  29307. var onload = function () {
  29308. _this.isCompleted = true;
  29309. if (_this.onSuccess) {
  29310. _this.onSuccess(_this);
  29311. }
  29312. onSuccess();
  29313. };
  29314. var onerror = function () {
  29315. if (_this.onError) {
  29316. _this.onError(_this);
  29317. }
  29318. onError();
  29319. };
  29320. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29321. };
  29322. return TextureAssetTask;
  29323. })();
  29324. BABYLON.TextureAssetTask = TextureAssetTask;
  29325. var AssetsManager = (function () {
  29326. function AssetsManager(scene) {
  29327. this._tasks = new Array();
  29328. this._waitingTasksCount = 0;
  29329. this.useDefaultLoadingScreen = true;
  29330. this._scene = scene;
  29331. }
  29332. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29333. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29334. this._tasks.push(task);
  29335. return task;
  29336. };
  29337. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29338. var task = new TextFileAssetTask(taskName, url);
  29339. this._tasks.push(task);
  29340. return task;
  29341. };
  29342. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29343. var task = new BinaryFileAssetTask(taskName, url);
  29344. this._tasks.push(task);
  29345. return task;
  29346. };
  29347. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29348. var task = new ImageAssetTask(taskName, url);
  29349. this._tasks.push(task);
  29350. return task;
  29351. };
  29352. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29354. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29355. this._tasks.push(task);
  29356. return task;
  29357. };
  29358. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29359. this._waitingTasksCount--;
  29360. if (this._waitingTasksCount === 0) {
  29361. if (this.onFinish) {
  29362. this.onFinish(this._tasks);
  29363. }
  29364. this._scene.getEngine().hideLoadingUI();
  29365. }
  29366. };
  29367. AssetsManager.prototype._runTask = function (task) {
  29368. var _this = this;
  29369. task.run(this._scene, function () {
  29370. if (_this.onTaskSuccess) {
  29371. _this.onTaskSuccess(task);
  29372. }
  29373. _this._decreaseWaitingTasksCount();
  29374. }, function () {
  29375. if (_this.onTaskError) {
  29376. _this.onTaskError(task);
  29377. }
  29378. _this._decreaseWaitingTasksCount();
  29379. });
  29380. };
  29381. AssetsManager.prototype.reset = function () {
  29382. this._tasks = new Array();
  29383. return this;
  29384. };
  29385. AssetsManager.prototype.load = function () {
  29386. this._waitingTasksCount = this._tasks.length;
  29387. if (this._waitingTasksCount === 0) {
  29388. if (this.onFinish) {
  29389. this.onFinish(this._tasks);
  29390. }
  29391. return this;
  29392. }
  29393. if (this.useDefaultLoadingScreen) {
  29394. this._scene.getEngine().displayLoadingUI();
  29395. }
  29396. for (var index = 0; index < this._tasks.length; index++) {
  29397. var task = this._tasks[index];
  29398. this._runTask(task);
  29399. }
  29400. return this;
  29401. };
  29402. return AssetsManager;
  29403. })();
  29404. BABYLON.AssetsManager = AssetsManager;
  29405. })(BABYLON || (BABYLON = {}));
  29406. var BABYLON;
  29407. (function (BABYLON) {
  29408. var VRDeviceOrientationFreeCamera = (function (_super) {
  29409. __extends(VRDeviceOrientationFreeCamera, _super);
  29410. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29411. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29412. _super.call(this, name, position, scene);
  29413. this._alpha = 0;
  29414. this._beta = 0;
  29415. this._gamma = 0;
  29416. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29417. metrics.compensateDistorsion = compensateDistorsion;
  29418. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29419. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29420. }
  29421. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29422. this._alpha = +evt.alpha | 0;
  29423. this._beta = +evt.beta | 0;
  29424. this._gamma = +evt.gamma | 0;
  29425. if (this._gamma < 0) {
  29426. this._gamma = 90 + this._gamma;
  29427. }
  29428. else {
  29429. // Incline it in the correct angle.
  29430. this._gamma = 270 - this._gamma;
  29431. }
  29432. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29433. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29434. this.rotation.z = this._beta / 180.0 * Math.PI;
  29435. };
  29436. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29437. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29438. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29439. };
  29440. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29441. _super.prototype.detachControl.call(this, element);
  29442. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29443. };
  29444. return VRDeviceOrientationFreeCamera;
  29445. })(BABYLON.FreeCamera);
  29446. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29447. })(BABYLON || (BABYLON = {}));
  29448. var BABYLON;
  29449. (function (BABYLON) {
  29450. var WebVRFreeCamera = (function (_super) {
  29451. __extends(WebVRFreeCamera, _super);
  29452. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29453. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29454. _super.call(this, name, position, scene);
  29455. this._hmdDevice = null;
  29456. this._sensorDevice = null;
  29457. this._cacheState = null;
  29458. this._cacheQuaternion = new BABYLON.Quaternion();
  29459. this._cacheRotation = BABYLON.Vector3.Zero();
  29460. this._vrEnabled = false;
  29461. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29462. metrics.compensateDistorsion = compensateDistorsion;
  29463. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29464. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29465. }
  29466. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29467. var size = devices.length;
  29468. var i = 0;
  29469. // Reset devices.
  29470. this._sensorDevice = null;
  29471. this._hmdDevice = null;
  29472. // Search for a HmdDevice.
  29473. while (i < size && this._hmdDevice === null) {
  29474. if (devices[i] instanceof HMDVRDevice) {
  29475. this._hmdDevice = devices[i];
  29476. }
  29477. i++;
  29478. }
  29479. i = 0;
  29480. while (i < size && this._sensorDevice === null) {
  29481. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29482. this._sensorDevice = devices[i];
  29483. }
  29484. i++;
  29485. }
  29486. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29487. };
  29488. WebVRFreeCamera.prototype._checkInputs = function () {
  29489. if (this._vrEnabled) {
  29490. this._cacheState = this._sensorDevice.getState();
  29491. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29492. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29493. this.rotation.x = -this._cacheRotation.z;
  29494. this.rotation.y = -this._cacheRotation.y;
  29495. this.rotation.z = this._cacheRotation.x;
  29496. }
  29497. _super.prototype._checkInputs.call(this);
  29498. };
  29499. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29500. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29501. if (navigator.getVRDevices) {
  29502. navigator.getVRDevices().then(this._getWebVRDevices);
  29503. }
  29504. else if (navigator.mozGetVRDevices) {
  29505. navigator.mozGetVRDevices(this._getWebVRDevices);
  29506. }
  29507. };
  29508. WebVRFreeCamera.prototype.detachControl = function (element) {
  29509. _super.prototype.detachControl.call(this, element);
  29510. this._vrEnabled = false;
  29511. };
  29512. return WebVRFreeCamera;
  29513. })(BABYLON.FreeCamera);
  29514. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29515. })(BABYLON || (BABYLON = {}));
  29516. var BABYLON;
  29517. (function (BABYLON) {
  29518. // Standard optimizations
  29519. var SceneOptimization = (function () {
  29520. function SceneOptimization(priority) {
  29521. if (priority === void 0) { priority = 0; }
  29522. this.priority = priority;
  29523. this.apply = function (scene) {
  29524. return true; // Return true if everything that can be done was applied
  29525. };
  29526. }
  29527. return SceneOptimization;
  29528. })();
  29529. BABYLON.SceneOptimization = SceneOptimization;
  29530. var TextureOptimization = (function (_super) {
  29531. __extends(TextureOptimization, _super);
  29532. function TextureOptimization(priority, maximumSize) {
  29533. var _this = this;
  29534. if (priority === void 0) { priority = 0; }
  29535. if (maximumSize === void 0) { maximumSize = 1024; }
  29536. _super.call(this, priority);
  29537. this.priority = priority;
  29538. this.maximumSize = maximumSize;
  29539. this.apply = function (scene) {
  29540. var allDone = true;
  29541. for (var index = 0; index < scene.textures.length; index++) {
  29542. var texture = scene.textures[index];
  29543. if (!texture.canRescale) {
  29544. continue;
  29545. }
  29546. var currentSize = texture.getSize();
  29547. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29548. if (maxDimension > _this.maximumSize) {
  29549. texture.scale(0.5);
  29550. allDone = false;
  29551. }
  29552. }
  29553. return allDone;
  29554. };
  29555. }
  29556. return TextureOptimization;
  29557. })(SceneOptimization);
  29558. BABYLON.TextureOptimization = TextureOptimization;
  29559. var HardwareScalingOptimization = (function (_super) {
  29560. __extends(HardwareScalingOptimization, _super);
  29561. function HardwareScalingOptimization(priority, maximumScale) {
  29562. var _this = this;
  29563. if (priority === void 0) { priority = 0; }
  29564. if (maximumScale === void 0) { maximumScale = 2; }
  29565. _super.call(this, priority);
  29566. this.priority = priority;
  29567. this.maximumScale = maximumScale;
  29568. this._currentScale = 1;
  29569. this.apply = function (scene) {
  29570. _this._currentScale++;
  29571. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29572. return _this._currentScale >= _this.maximumScale;
  29573. };
  29574. }
  29575. return HardwareScalingOptimization;
  29576. })(SceneOptimization);
  29577. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29578. var ShadowsOptimization = (function (_super) {
  29579. __extends(ShadowsOptimization, _super);
  29580. function ShadowsOptimization() {
  29581. _super.apply(this, arguments);
  29582. this.apply = function (scene) {
  29583. scene.shadowsEnabled = false;
  29584. return true;
  29585. };
  29586. }
  29587. return ShadowsOptimization;
  29588. })(SceneOptimization);
  29589. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29590. var PostProcessesOptimization = (function (_super) {
  29591. __extends(PostProcessesOptimization, _super);
  29592. function PostProcessesOptimization() {
  29593. _super.apply(this, arguments);
  29594. this.apply = function (scene) {
  29595. scene.postProcessesEnabled = false;
  29596. return true;
  29597. };
  29598. }
  29599. return PostProcessesOptimization;
  29600. })(SceneOptimization);
  29601. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29602. var LensFlaresOptimization = (function (_super) {
  29603. __extends(LensFlaresOptimization, _super);
  29604. function LensFlaresOptimization() {
  29605. _super.apply(this, arguments);
  29606. this.apply = function (scene) {
  29607. scene.lensFlaresEnabled = false;
  29608. return true;
  29609. };
  29610. }
  29611. return LensFlaresOptimization;
  29612. })(SceneOptimization);
  29613. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29614. var ParticlesOptimization = (function (_super) {
  29615. __extends(ParticlesOptimization, _super);
  29616. function ParticlesOptimization() {
  29617. _super.apply(this, arguments);
  29618. this.apply = function (scene) {
  29619. scene.particlesEnabled = false;
  29620. return true;
  29621. };
  29622. }
  29623. return ParticlesOptimization;
  29624. })(SceneOptimization);
  29625. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29626. var RenderTargetsOptimization = (function (_super) {
  29627. __extends(RenderTargetsOptimization, _super);
  29628. function RenderTargetsOptimization() {
  29629. _super.apply(this, arguments);
  29630. this.apply = function (scene) {
  29631. scene.renderTargetsEnabled = false;
  29632. return true;
  29633. };
  29634. }
  29635. return RenderTargetsOptimization;
  29636. })(SceneOptimization);
  29637. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29638. var MergeMeshesOptimization = (function (_super) {
  29639. __extends(MergeMeshesOptimization, _super);
  29640. function MergeMeshesOptimization() {
  29641. var _this = this;
  29642. _super.apply(this, arguments);
  29643. this._canBeMerged = function (abstractMesh) {
  29644. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29645. return false;
  29646. }
  29647. var mesh = abstractMesh;
  29648. if (!mesh.isVisible || !mesh.isEnabled()) {
  29649. return false;
  29650. }
  29651. if (mesh.instances.length > 0) {
  29652. return false;
  29653. }
  29654. if (mesh.skeleton || mesh.hasLODLevels) {
  29655. return false;
  29656. }
  29657. return true;
  29658. };
  29659. this.apply = function (scene, updateSelectionTree) {
  29660. var globalPool = scene.meshes.slice(0);
  29661. var globalLength = globalPool.length;
  29662. for (var index = 0; index < globalLength; index++) {
  29663. var currentPool = new Array();
  29664. var current = globalPool[index];
  29665. // Checks
  29666. if (!_this._canBeMerged(current)) {
  29667. continue;
  29668. }
  29669. currentPool.push(current);
  29670. // Find compatible meshes
  29671. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29672. var otherMesh = globalPool[subIndex];
  29673. if (!_this._canBeMerged(otherMesh)) {
  29674. continue;
  29675. }
  29676. if (otherMesh.material !== current.material) {
  29677. continue;
  29678. }
  29679. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29680. continue;
  29681. }
  29682. currentPool.push(otherMesh);
  29683. globalLength--;
  29684. globalPool.splice(subIndex, 1);
  29685. subIndex--;
  29686. }
  29687. if (currentPool.length < 2) {
  29688. continue;
  29689. }
  29690. // Merge meshes
  29691. BABYLON.Mesh.MergeMeshes(currentPool);
  29692. }
  29693. if (updateSelectionTree != undefined) {
  29694. if (updateSelectionTree) {
  29695. scene.createOrUpdateSelectionOctree();
  29696. }
  29697. }
  29698. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29699. scene.createOrUpdateSelectionOctree();
  29700. }
  29701. return true;
  29702. };
  29703. }
  29704. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29705. get: function () {
  29706. return MergeMeshesOptimization._UpdateSelectionTree;
  29707. },
  29708. set: function (value) {
  29709. MergeMeshesOptimization._UpdateSelectionTree = value;
  29710. },
  29711. enumerable: true,
  29712. configurable: true
  29713. });
  29714. MergeMeshesOptimization._UpdateSelectionTree = false;
  29715. return MergeMeshesOptimization;
  29716. })(SceneOptimization);
  29717. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29718. // Options
  29719. var SceneOptimizerOptions = (function () {
  29720. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29721. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29722. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29723. this.targetFrameRate = targetFrameRate;
  29724. this.trackerDuration = trackerDuration;
  29725. this.optimizations = new Array();
  29726. }
  29727. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29728. var result = new SceneOptimizerOptions(targetFrameRate);
  29729. var priority = 0;
  29730. result.optimizations.push(new MergeMeshesOptimization(priority));
  29731. result.optimizations.push(new ShadowsOptimization(priority));
  29732. result.optimizations.push(new LensFlaresOptimization(priority));
  29733. // Next priority
  29734. priority++;
  29735. result.optimizations.push(new PostProcessesOptimization(priority));
  29736. result.optimizations.push(new ParticlesOptimization(priority));
  29737. // Next priority
  29738. priority++;
  29739. result.optimizations.push(new TextureOptimization(priority, 1024));
  29740. return result;
  29741. };
  29742. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29743. var result = new SceneOptimizerOptions(targetFrameRate);
  29744. var priority = 0;
  29745. result.optimizations.push(new MergeMeshesOptimization(priority));
  29746. result.optimizations.push(new ShadowsOptimization(priority));
  29747. result.optimizations.push(new LensFlaresOptimization(priority));
  29748. // Next priority
  29749. priority++;
  29750. result.optimizations.push(new PostProcessesOptimization(priority));
  29751. result.optimizations.push(new ParticlesOptimization(priority));
  29752. // Next priority
  29753. priority++;
  29754. result.optimizations.push(new TextureOptimization(priority, 512));
  29755. // Next priority
  29756. priority++;
  29757. result.optimizations.push(new RenderTargetsOptimization(priority));
  29758. // Next priority
  29759. priority++;
  29760. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29761. return result;
  29762. };
  29763. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29764. var result = new SceneOptimizerOptions(targetFrameRate);
  29765. var priority = 0;
  29766. result.optimizations.push(new MergeMeshesOptimization(priority));
  29767. result.optimizations.push(new ShadowsOptimization(priority));
  29768. result.optimizations.push(new LensFlaresOptimization(priority));
  29769. // Next priority
  29770. priority++;
  29771. result.optimizations.push(new PostProcessesOptimization(priority));
  29772. result.optimizations.push(new ParticlesOptimization(priority));
  29773. // Next priority
  29774. priority++;
  29775. result.optimizations.push(new TextureOptimization(priority, 256));
  29776. // Next priority
  29777. priority++;
  29778. result.optimizations.push(new RenderTargetsOptimization(priority));
  29779. // Next priority
  29780. priority++;
  29781. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29782. return result;
  29783. };
  29784. return SceneOptimizerOptions;
  29785. })();
  29786. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29787. // Scene optimizer tool
  29788. var SceneOptimizer = (function () {
  29789. function SceneOptimizer() {
  29790. }
  29791. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29792. // TODO: add an epsilon
  29793. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29794. if (onSuccess) {
  29795. onSuccess();
  29796. }
  29797. return;
  29798. }
  29799. // Apply current level of optimizations
  29800. var allDone = true;
  29801. var noOptimizationApplied = true;
  29802. for (var index = 0; index < options.optimizations.length; index++) {
  29803. var optimization = options.optimizations[index];
  29804. if (optimization.priority === currentPriorityLevel) {
  29805. noOptimizationApplied = false;
  29806. allDone = allDone && optimization.apply(scene);
  29807. }
  29808. }
  29809. // If no optimization was applied, this is a failure :(
  29810. if (noOptimizationApplied) {
  29811. if (onFailure) {
  29812. onFailure();
  29813. }
  29814. return;
  29815. }
  29816. // If all optimizations were done, move to next level
  29817. if (allDone) {
  29818. currentPriorityLevel++;
  29819. }
  29820. // Let's the system running for a specific amount of time before checking FPS
  29821. scene.executeWhenReady(function () {
  29822. setTimeout(function () {
  29823. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29824. }, options.trackerDuration);
  29825. });
  29826. };
  29827. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29828. if (!options) {
  29829. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29830. }
  29831. // Let's the system running for a specific amount of time before checking FPS
  29832. scene.executeWhenReady(function () {
  29833. setTimeout(function () {
  29834. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29835. }, options.trackerDuration);
  29836. });
  29837. };
  29838. return SceneOptimizer;
  29839. })();
  29840. BABYLON.SceneOptimizer = SceneOptimizer;
  29841. })(BABYLON || (BABYLON = {}));
  29842. var BABYLON;
  29843. (function (BABYLON) {
  29844. var Internals;
  29845. (function (Internals) {
  29846. var MeshLODLevel = (function () {
  29847. function MeshLODLevel(distance, mesh) {
  29848. this.distance = distance;
  29849. this.mesh = mesh;
  29850. }
  29851. return MeshLODLevel;
  29852. })();
  29853. Internals.MeshLODLevel = MeshLODLevel;
  29854. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29855. })(BABYLON || (BABYLON = {}));
  29856. var BABYLON;
  29857. (function (BABYLON) {
  29858. var AudioEngine = (function () {
  29859. function AudioEngine() {
  29860. this._audioContext = null;
  29861. this._audioContextInitialized = false;
  29862. this.canUseWebAudio = false;
  29863. this.WarnedWebAudioUnsupported = false;
  29864. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29865. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29866. this.canUseWebAudio = true;
  29867. }
  29868. }
  29869. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29870. get: function () {
  29871. if (!this._audioContextInitialized) {
  29872. this._initializeAudioContext();
  29873. }
  29874. return this._audioContext;
  29875. },
  29876. enumerable: true,
  29877. configurable: true
  29878. });
  29879. AudioEngine.prototype._initializeAudioContext = function () {
  29880. try {
  29881. if (this.canUseWebAudio) {
  29882. this._audioContext = new AudioContext();
  29883. // create a global volume gain node
  29884. this.masterGain = this._audioContext.createGain();
  29885. this.masterGain.gain.value = 1;
  29886. this.masterGain.connect(this._audioContext.destination);
  29887. this._audioContextInitialized = true;
  29888. }
  29889. }
  29890. catch (e) {
  29891. this.canUseWebAudio = false;
  29892. BABYLON.Tools.Error("Web Audio: " + e.message);
  29893. }
  29894. };
  29895. AudioEngine.prototype.dispose = function () {
  29896. if (this.canUseWebAudio && this._audioContextInitialized) {
  29897. if (this._connectedAnalyser) {
  29898. this._connectedAnalyser.stopDebugCanvas();
  29899. this._connectedAnalyser.dispose();
  29900. this.masterGain.disconnect();
  29901. this.masterGain.connect(this._audioContext.destination);
  29902. this._connectedAnalyser = null;
  29903. }
  29904. this.masterGain.gain.value = 1;
  29905. }
  29906. this.WarnedWebAudioUnsupported = false;
  29907. };
  29908. AudioEngine.prototype.getGlobalVolume = function () {
  29909. if (this.canUseWebAudio && this._audioContextInitialized) {
  29910. return this.masterGain.gain.value;
  29911. }
  29912. else {
  29913. return -1;
  29914. }
  29915. };
  29916. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29917. if (this.canUseWebAudio && this._audioContextInitialized) {
  29918. this.masterGain.gain.value = newVolume;
  29919. }
  29920. };
  29921. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29922. if (this._connectedAnalyser) {
  29923. this._connectedAnalyser.stopDebugCanvas();
  29924. }
  29925. if (this.canUseWebAudio && this._audioContextInitialized) {
  29926. this._connectedAnalyser = analyser;
  29927. this.masterGain.disconnect();
  29928. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29929. }
  29930. };
  29931. return AudioEngine;
  29932. })();
  29933. BABYLON.AudioEngine = AudioEngine;
  29934. })(BABYLON || (BABYLON = {}));
  29935. var BABYLON;
  29936. (function (BABYLON) {
  29937. var Sound = (function () {
  29938. /**
  29939. * Create a sound and attach it to a scene
  29940. * @param name Name of your sound
  29941. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29942. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29943. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29944. */
  29945. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29946. var _this = this;
  29947. this.autoplay = false;
  29948. this.loop = false;
  29949. this.useCustomAttenuation = false;
  29950. this.spatialSound = false;
  29951. this.refDistance = 1;
  29952. this.rolloffFactor = 1;
  29953. this.maxDistance = 100;
  29954. this.distanceModel = "linear";
  29955. this._panningModel = "equalpower";
  29956. this._playbackRate = 1;
  29957. this._startTime = 0;
  29958. this._startOffset = 0;
  29959. this._position = BABYLON.Vector3.Zero();
  29960. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29961. this._volume = 1;
  29962. this._isLoaded = false;
  29963. this._isReadyToPlay = false;
  29964. this.isPlaying = false;
  29965. this.isPaused = false;
  29966. this._isDirectional = false;
  29967. // Used if you'd like to create a directional sound.
  29968. // If not set, the sound will be omnidirectional
  29969. this._coneInnerAngle = 360;
  29970. this._coneOuterAngle = 360;
  29971. this._coneOuterGain = 0;
  29972. this.name = name;
  29973. this._scene = scene;
  29974. this._readyToPlayCallback = readyToPlayCallback;
  29975. // Default custom attenuation function is a linear attenuation
  29976. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29977. if (currentDistance < maxDistance) {
  29978. return currentVolume * (1 - currentDistance / maxDistance);
  29979. }
  29980. else {
  29981. return 0;
  29982. }
  29983. };
  29984. if (options) {
  29985. this.autoplay = options.autoplay || false;
  29986. this.loop = options.loop || false;
  29987. // if volume === 0, we need another way to check this option
  29988. if (options.volume !== undefined) {
  29989. this._volume = options.volume;
  29990. }
  29991. this.spatialSound = options.spatialSound || false;
  29992. this.maxDistance = options.maxDistance || 100;
  29993. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29994. this.rolloffFactor = options.rolloffFactor || 1;
  29995. this.refDistance = options.refDistance || 1;
  29996. this.distanceModel = options.distanceModel || "linear";
  29997. this._playbackRate = options.playbackRate || 1;
  29998. }
  29999. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30000. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30001. this._soundGain.gain.value = this._volume;
  30002. this._inputAudioNode = this._soundGain;
  30003. this._ouputAudioNode = this._soundGain;
  30004. if (this.spatialSound) {
  30005. this._createSpatialParameters();
  30006. }
  30007. this._scene.mainSoundTrack.AddSound(this);
  30008. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30009. if (urlOrArrayBuffer) {
  30010. // If it's an URL
  30011. if (typeof (urlOrArrayBuffer) === "string") {
  30012. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30013. }
  30014. else {
  30015. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30016. this._soundLoaded(urlOrArrayBuffer);
  30017. }
  30018. else {
  30019. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30020. }
  30021. }
  30022. }
  30023. }
  30024. else {
  30025. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30026. this._scene.mainSoundTrack.AddSound(this);
  30027. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30028. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30029. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30030. }
  30031. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30032. if (this._readyToPlayCallback) {
  30033. window.setTimeout(function () {
  30034. _this._readyToPlayCallback();
  30035. }, 1000);
  30036. }
  30037. }
  30038. }
  30039. Sound.prototype.dispose = function () {
  30040. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30041. if (this.isPlaying) {
  30042. this.stop();
  30043. }
  30044. this._isReadyToPlay = false;
  30045. if (this.soundTrackId === -1) {
  30046. this._scene.mainSoundTrack.RemoveSound(this);
  30047. }
  30048. else {
  30049. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30050. }
  30051. if (this._soundGain) {
  30052. this._soundGain.disconnect();
  30053. this._soundGain = null;
  30054. }
  30055. if (this._soundPanner) {
  30056. this._soundPanner.disconnect();
  30057. this._soundPanner = null;
  30058. }
  30059. if (this._soundSource) {
  30060. this._soundSource.disconnect();
  30061. this._soundSource = null;
  30062. }
  30063. this._audioBuffer = null;
  30064. if (this._connectedMesh) {
  30065. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30066. this._connectedMesh = null;
  30067. }
  30068. }
  30069. };
  30070. Sound.prototype._soundLoaded = function (audioData) {
  30071. var _this = this;
  30072. this._isLoaded = true;
  30073. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30074. _this._audioBuffer = buffer;
  30075. _this._isReadyToPlay = true;
  30076. if (_this.autoplay) {
  30077. _this.play();
  30078. }
  30079. if (_this._readyToPlayCallback) {
  30080. _this._readyToPlayCallback();
  30081. }
  30082. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30083. };
  30084. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30085. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30086. this._audioBuffer = audioBuffer;
  30087. this._isReadyToPlay = true;
  30088. }
  30089. };
  30090. Sound.prototype.updateOptions = function (options) {
  30091. if (options) {
  30092. this.loop = options.loop || this.loop;
  30093. this.maxDistance = options.maxDistance || this.maxDistance;
  30094. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30095. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30096. this.refDistance = options.refDistance || this.refDistance;
  30097. this.distanceModel = options.distanceModel || this.distanceModel;
  30098. this._playbackRate = options.playbackRate || this._playbackRate;
  30099. this._updateSpatialParameters();
  30100. if (this.isPlaying) {
  30101. this._soundSource.playbackRate.value = this._playbackRate;
  30102. }
  30103. }
  30104. };
  30105. Sound.prototype._createSpatialParameters = function () {
  30106. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30107. if (this._scene.headphone) {
  30108. this._panningModel = "HRTF";
  30109. }
  30110. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30111. this._updateSpatialParameters();
  30112. this._soundPanner.connect(this._ouputAudioNode);
  30113. this._inputAudioNode = this._soundPanner;
  30114. }
  30115. };
  30116. Sound.prototype._updateSpatialParameters = function () {
  30117. if (this.spatialSound) {
  30118. if (this.useCustomAttenuation) {
  30119. // Tricks to disable in a way embedded Web Audio attenuation
  30120. this._soundPanner.distanceModel = "linear";
  30121. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30122. this._soundPanner.refDistance = 1;
  30123. this._soundPanner.rolloffFactor = 1;
  30124. this._soundPanner.panningModel = this._panningModel;
  30125. }
  30126. else {
  30127. this._soundPanner.distanceModel = this.distanceModel;
  30128. this._soundPanner.maxDistance = this.maxDistance;
  30129. this._soundPanner.refDistance = this.refDistance;
  30130. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30131. this._soundPanner.panningModel = this._panningModel;
  30132. }
  30133. }
  30134. };
  30135. Sound.prototype.switchPanningModelToHRTF = function () {
  30136. this._panningModel = "HRTF";
  30137. this._switchPanningModel();
  30138. };
  30139. Sound.prototype.switchPanningModelToEqualPower = function () {
  30140. this._panningModel = "equalpower";
  30141. this._switchPanningModel();
  30142. };
  30143. Sound.prototype._switchPanningModel = function () {
  30144. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30145. this._soundPanner.panningModel = this._panningModel;
  30146. }
  30147. };
  30148. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30149. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30150. this._ouputAudioNode.disconnect();
  30151. this._ouputAudioNode.connect(soundTrackAudioNode);
  30152. }
  30153. };
  30154. /**
  30155. * Transform this sound into a directional source
  30156. * @param coneInnerAngle Size of the inner cone in degree
  30157. * @param coneOuterAngle Size of the outer cone in degree
  30158. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30159. */
  30160. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30161. if (coneOuterAngle < coneInnerAngle) {
  30162. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30163. return;
  30164. }
  30165. this._coneInnerAngle = coneInnerAngle;
  30166. this._coneOuterAngle = coneOuterAngle;
  30167. this._coneOuterGain = coneOuterGain;
  30168. this._isDirectional = true;
  30169. if (this.isPlaying && this.loop) {
  30170. this.stop();
  30171. this.play();
  30172. }
  30173. };
  30174. Sound.prototype.setPosition = function (newPosition) {
  30175. this._position = newPosition;
  30176. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30177. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30178. }
  30179. };
  30180. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30181. this._localDirection = newLocalDirection;
  30182. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30183. this._updateDirection();
  30184. }
  30185. };
  30186. Sound.prototype._updateDirection = function () {
  30187. var mat = this._connectedMesh.getWorldMatrix();
  30188. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30189. direction.normalize();
  30190. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30191. };
  30192. Sound.prototype.updateDistanceFromListener = function () {
  30193. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30194. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30195. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30196. }
  30197. };
  30198. Sound.prototype.setAttenuationFunction = function (callback) {
  30199. this._customAttenuationFunction = callback;
  30200. };
  30201. /**
  30202. * Play the sound
  30203. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30204. */
  30205. Sound.prototype.play = function (time) {
  30206. var _this = this;
  30207. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30208. try {
  30209. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30210. if (!this._soundSource) {
  30211. if (this.spatialSound) {
  30212. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30213. if (this._isDirectional) {
  30214. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30215. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30216. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30217. if (this._connectedMesh) {
  30218. this._updateDirection();
  30219. }
  30220. else {
  30221. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30222. }
  30223. }
  30224. }
  30225. }
  30226. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30227. this._soundSource.buffer = this._audioBuffer;
  30228. this._soundSource.connect(this._inputAudioNode);
  30229. this._soundSource.loop = this.loop;
  30230. this._soundSource.playbackRate.value = this._playbackRate;
  30231. this._startTime = startTime;
  30232. this._soundSource.onended = function () { _this._onended(); };
  30233. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30234. this.isPlaying = true;
  30235. this.isPaused = false;
  30236. }
  30237. catch (ex) {
  30238. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30239. }
  30240. }
  30241. };
  30242. Sound.prototype._onended = function () {
  30243. this.isPlaying = false;
  30244. if (this.onended) {
  30245. this.onended();
  30246. }
  30247. };
  30248. /**
  30249. * Stop the sound
  30250. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30251. */
  30252. Sound.prototype.stop = function (time) {
  30253. if (this.isPlaying) {
  30254. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30255. this._soundSource.stop(stopTime);
  30256. this.isPlaying = false;
  30257. }
  30258. };
  30259. Sound.prototype.pause = function () {
  30260. if (this.isPlaying) {
  30261. this.stop(0);
  30262. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30263. this.isPaused = true;
  30264. }
  30265. };
  30266. Sound.prototype.setVolume = function (newVolume, time) {
  30267. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30268. if (time) {
  30269. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30270. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30271. }
  30272. else {
  30273. this._soundGain.gain.value = newVolume;
  30274. }
  30275. }
  30276. this._volume = newVolume;
  30277. };
  30278. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30279. this._playbackRate = newPlaybackRate;
  30280. if (this.isPlaying) {
  30281. this._soundSource.playbackRate.value = this._playbackRate;
  30282. }
  30283. };
  30284. Sound.prototype.getVolume = function () {
  30285. return this._volume;
  30286. };
  30287. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30288. var _this = this;
  30289. this._connectedMesh = meshToConnectTo;
  30290. if (!this.spatialSound) {
  30291. this.spatialSound = true;
  30292. this._createSpatialParameters();
  30293. if (this.isPlaying && this.loop) {
  30294. this.stop();
  30295. this.play();
  30296. }
  30297. }
  30298. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30299. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30300. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30301. };
  30302. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30303. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30304. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30305. this._updateDirection();
  30306. }
  30307. };
  30308. return Sound;
  30309. })();
  30310. BABYLON.Sound = Sound;
  30311. })(BABYLON || (BABYLON = {}));
  30312. var BABYLON;
  30313. (function (BABYLON) {
  30314. var SoundTrack = (function () {
  30315. function SoundTrack(scene, options) {
  30316. this.id = -1;
  30317. this._isMainTrack = false;
  30318. this._scene = scene;
  30319. this._audioEngine = BABYLON.Engine.audioEngine;
  30320. this.soundCollection = new Array();
  30321. if (this._audioEngine.canUseWebAudio) {
  30322. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30323. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30324. if (options) {
  30325. if (options.volume) {
  30326. this._outputAudioNode.gain.value = options.volume;
  30327. }
  30328. if (options.mainTrack) {
  30329. this._isMainTrack = options.mainTrack;
  30330. }
  30331. }
  30332. }
  30333. if (!this._isMainTrack) {
  30334. this._scene.soundTracks.push(this);
  30335. this.id = this._scene.soundTracks.length - 1;
  30336. }
  30337. }
  30338. SoundTrack.prototype.dispose = function () {
  30339. if (this._audioEngine.canUseWebAudio) {
  30340. if (this._connectedAnalyser) {
  30341. this._connectedAnalyser.stopDebugCanvas();
  30342. }
  30343. while (this.soundCollection.length) {
  30344. this.soundCollection[0].dispose();
  30345. }
  30346. if (this._outputAudioNode) {
  30347. this._outputAudioNode.disconnect();
  30348. }
  30349. this._outputAudioNode = null;
  30350. }
  30351. };
  30352. SoundTrack.prototype.AddSound = function (sound) {
  30353. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30354. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30355. }
  30356. if (sound.soundTrackId) {
  30357. if (sound.soundTrackId === -1) {
  30358. this._scene.mainSoundTrack.RemoveSound(sound);
  30359. }
  30360. else {
  30361. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30362. }
  30363. }
  30364. this.soundCollection.push(sound);
  30365. sound.soundTrackId = this.id;
  30366. };
  30367. SoundTrack.prototype.RemoveSound = function (sound) {
  30368. var index = this.soundCollection.indexOf(sound);
  30369. if (index !== -1) {
  30370. this.soundCollection.splice(index, 1);
  30371. }
  30372. };
  30373. SoundTrack.prototype.setVolume = function (newVolume) {
  30374. if (this._audioEngine.canUseWebAudio) {
  30375. this._outputAudioNode.gain.value = newVolume;
  30376. }
  30377. };
  30378. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30379. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30380. for (var i = 0; i < this.soundCollection.length; i++) {
  30381. this.soundCollection[i].switchPanningModelToHRTF();
  30382. }
  30383. }
  30384. };
  30385. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30386. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30387. for (var i = 0; i < this.soundCollection.length; i++) {
  30388. this.soundCollection[i].switchPanningModelToEqualPower();
  30389. }
  30390. }
  30391. };
  30392. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30393. if (this._connectedAnalyser) {
  30394. this._connectedAnalyser.stopDebugCanvas();
  30395. }
  30396. this._connectedAnalyser = analyser;
  30397. if (this._audioEngine.canUseWebAudio) {
  30398. this._outputAudioNode.disconnect();
  30399. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30400. }
  30401. };
  30402. return SoundTrack;
  30403. })();
  30404. BABYLON.SoundTrack = SoundTrack;
  30405. })(BABYLON || (BABYLON = {}));
  30406. var BABYLON;
  30407. (function (BABYLON) {
  30408. var DebugLayer = (function () {
  30409. function DebugLayer(scene) {
  30410. var _this = this;
  30411. this._transformationMatrix = BABYLON.Matrix.Identity();
  30412. this._enabled = false;
  30413. this._labelsEnabled = false;
  30414. this._displayStatistics = true;
  30415. this._displayTree = false;
  30416. this._displayLogs = false;
  30417. this._identityMatrix = BABYLON.Matrix.Identity();
  30418. this.axisRatio = 0.02;
  30419. this.accentColor = "orange";
  30420. this._scene = scene;
  30421. this._syncPositions = function () {
  30422. var engine = _this._scene.getEngine();
  30423. var canvasRect = engine.getRenderingCanvasClientRect();
  30424. if (_this._showUI) {
  30425. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30426. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30427. _this._statsDiv.style.width = "400px";
  30428. _this._statsDiv.style.height = "auto";
  30429. _this._statsSubsetDiv.style.maxHeight = "240px";
  30430. _this._optionsDiv.style.left = "0px";
  30431. _this._optionsDiv.style.top = "10px";
  30432. _this._optionsDiv.style.width = "200px";
  30433. _this._optionsDiv.style.height = "auto";
  30434. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30435. _this._logDiv.style.left = "0px";
  30436. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30437. _this._logDiv.style.width = "600px";
  30438. _this._logDiv.style.height = "160px";
  30439. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30440. _this._treeDiv.style.top = "10px";
  30441. _this._treeDiv.style.width = "300px";
  30442. _this._treeDiv.style.height = "auto";
  30443. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30444. }
  30445. _this._globalDiv.style.left = canvasRect.left + "px";
  30446. _this._globalDiv.style.top = canvasRect.top + "px";
  30447. _this._drawingCanvas.style.left = "0px";
  30448. _this._drawingCanvas.style.top = "0px";
  30449. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30450. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30451. var devicePixelRatio = window.devicePixelRatio || 1;
  30452. var context = _this._drawingContext;
  30453. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30454. context.mozBackingStorePixelRatio ||
  30455. context.msBackingStorePixelRatio ||
  30456. context.oBackingStorePixelRatio ||
  30457. context.backingStorePixelRatio || 1;
  30458. _this._ratio = devicePixelRatio / backingStoreRatio;
  30459. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30460. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30461. };
  30462. this._onCanvasClick = function (evt) {
  30463. _this._clickPosition = {
  30464. x: evt.clientX * _this._ratio,
  30465. y: evt.clientY * _this._ratio
  30466. };
  30467. };
  30468. this._syncUI = function () {
  30469. if (_this._showUI) {
  30470. if (_this._displayStatistics) {
  30471. _this._displayStats();
  30472. _this._statsDiv.style.display = "";
  30473. }
  30474. else {
  30475. _this._statsDiv.style.display = "none";
  30476. }
  30477. if (_this._displayLogs) {
  30478. _this._logDiv.style.display = "";
  30479. }
  30480. else {
  30481. _this._logDiv.style.display = "none";
  30482. }
  30483. if (_this._displayTree) {
  30484. _this._treeDiv.style.display = "";
  30485. if (_this._needToRefreshMeshesTree) {
  30486. _this._needToRefreshMeshesTree = false;
  30487. _this._refreshMeshesTreeContent();
  30488. }
  30489. }
  30490. else {
  30491. _this._treeDiv.style.display = "none";
  30492. }
  30493. }
  30494. };
  30495. this._syncData = function () {
  30496. if (_this._labelsEnabled || !_this._showUI) {
  30497. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30498. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30499. var engine = _this._scene.getEngine();
  30500. var viewport = _this._camera.viewport;
  30501. var globalViewport = viewport.toGlobal(engine);
  30502. // Meshes
  30503. var meshes = _this._camera.getActiveMeshes();
  30504. for (var index = 0; index < meshes.length; index++) {
  30505. var mesh = meshes.data[index];
  30506. var position = mesh.getBoundingInfo().boundingSphere.center;
  30507. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30508. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30509. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30510. }
  30511. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30512. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30513. }
  30514. }
  30515. // Cameras
  30516. var cameras = _this._scene.cameras;
  30517. for (index = 0; index < cameras.length; index++) {
  30518. var camera = cameras[index];
  30519. if (camera === _this._camera) {
  30520. continue;
  30521. }
  30522. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30523. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30524. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30525. _this._camera.detachControl(engine.getRenderingCanvas());
  30526. _this._camera = camera;
  30527. _this._camera.attachControl(engine.getRenderingCanvas());
  30528. }, function () { return "purple"; });
  30529. }
  30530. }
  30531. // Lights
  30532. var lights = _this._scene.lights;
  30533. for (index = 0; index < lights.length; index++) {
  30534. var light = lights[index];
  30535. if (light.position) {
  30536. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30537. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30538. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30539. light.setEnabled(!light.isEnabled());
  30540. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30541. }
  30542. }
  30543. }
  30544. }
  30545. _this._clickPosition = undefined;
  30546. };
  30547. }
  30548. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30549. while (this._treeSubsetDiv.hasChildNodes()) {
  30550. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30551. }
  30552. // Add meshes
  30553. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30554. sortedArray.sort(function (a, b) {
  30555. if (a.name === b.name) {
  30556. return 0;
  30557. }
  30558. return (a.name > b.name) ? 1 : -1;
  30559. });
  30560. for (var index = 0; index < sortedArray.length; index++) {
  30561. var mesh = sortedArray[index];
  30562. if (!mesh.isEnabled()) {
  30563. continue;
  30564. }
  30565. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30566. m.isVisible = element.checked;
  30567. }, mesh);
  30568. }
  30569. };
  30570. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30571. this._drawingContext.beginPath();
  30572. this._drawingContext.moveTo(zero.x, zero.y);
  30573. this._drawingContext.lineTo(unit.x, unit.y);
  30574. this._drawingContext.strokeStyle = color;
  30575. this._drawingContext.lineWidth = 4;
  30576. this._drawingContext.stroke();
  30577. this._drawingContext.font = "normal 14px Segoe UI";
  30578. this._drawingContext.fillStyle = color;
  30579. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30580. };
  30581. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30582. var position = mesh.getBoundingInfo().boundingSphere.center;
  30583. var worldMatrix = mesh.getWorldMatrix();
  30584. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30585. var unit = (unprojectedVector.subtract(position)).length();
  30586. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30587. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30588. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30589. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30590. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30591. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30592. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30593. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30594. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30595. };
  30596. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30597. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30598. this._drawingContext.font = "normal 12px Segoe UI";
  30599. var textMetrics = this._drawingContext.measureText(text);
  30600. var centerX = projectedPosition.x - textMetrics.width / 2;
  30601. var centerY = projectedPosition.y;
  30602. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30603. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30604. onClick();
  30605. }
  30606. this._drawingContext.beginPath();
  30607. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30608. this._drawingContext.fillStyle = getFillStyle();
  30609. this._drawingContext.globalAlpha = 0.5;
  30610. this._drawingContext.fill();
  30611. this._drawingContext.globalAlpha = 1.0;
  30612. this._drawingContext.strokeStyle = '#FFFFFF';
  30613. this._drawingContext.lineWidth = 1;
  30614. this._drawingContext.stroke();
  30615. this._drawingContext.fillStyle = "#FFFFFF";
  30616. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30617. this._drawingContext.beginPath();
  30618. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30619. this._drawingContext.fill();
  30620. }
  30621. };
  30622. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30623. if (!this._clickPosition) {
  30624. return false;
  30625. }
  30626. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30627. return false;
  30628. }
  30629. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30630. return false;
  30631. }
  30632. return true;
  30633. };
  30634. DebugLayer.prototype.isVisible = function () {
  30635. return this._enabled;
  30636. };
  30637. DebugLayer.prototype.hide = function () {
  30638. if (!this._enabled) {
  30639. return;
  30640. }
  30641. this._enabled = false;
  30642. var engine = this._scene.getEngine();
  30643. this._scene.unregisterBeforeRender(this._syncData);
  30644. this._scene.unregisterAfterRender(this._syncUI);
  30645. document.body.removeChild(this._globalDiv);
  30646. window.removeEventListener("resize", this._syncPositions);
  30647. this._scene.forceShowBoundingBoxes = false;
  30648. this._scene.forceWireframe = false;
  30649. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30650. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30651. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30652. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30653. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30654. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30655. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30656. this._scene.shadowsEnabled = true;
  30657. this._scene.particlesEnabled = true;
  30658. this._scene.postProcessesEnabled = true;
  30659. this._scene.collisionsEnabled = true;
  30660. this._scene.lightsEnabled = true;
  30661. this._scene.texturesEnabled = true;
  30662. this._scene.lensFlaresEnabled = true;
  30663. this._scene.proceduralTexturesEnabled = true;
  30664. this._scene.renderTargetsEnabled = true;
  30665. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30666. };
  30667. DebugLayer.prototype.show = function (showUI, camera) {
  30668. if (showUI === void 0) { showUI = true; }
  30669. if (camera === void 0) { camera = null; }
  30670. if (this._enabled) {
  30671. return;
  30672. }
  30673. this._enabled = true;
  30674. if (camera) {
  30675. this._camera = camera;
  30676. }
  30677. else {
  30678. this._camera = this._scene.activeCamera;
  30679. }
  30680. this._showUI = showUI;
  30681. var engine = this._scene.getEngine();
  30682. this._globalDiv = document.createElement("div");
  30683. document.body.appendChild(this._globalDiv);
  30684. this._generateDOMelements();
  30685. window.addEventListener("resize", this._syncPositions);
  30686. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30687. this._syncPositions();
  30688. this._scene.registerBeforeRender(this._syncData);
  30689. this._scene.registerAfterRender(this._syncUI);
  30690. };
  30691. DebugLayer.prototype._clearLabels = function () {
  30692. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30693. for (var index = 0; index < this._scene.meshes.length; index++) {
  30694. var mesh = this._scene.meshes[index];
  30695. mesh.renderOverlay = false;
  30696. }
  30697. };
  30698. DebugLayer.prototype._generateheader = function (root, text) {
  30699. var header = document.createElement("div");
  30700. header.innerHTML = text + "&nbsp;";
  30701. header.style.textAlign = "right";
  30702. header.style.width = "100%";
  30703. header.style.color = "white";
  30704. header.style.backgroundColor = "Black";
  30705. header.style.padding = "5px 5px 4px 0px";
  30706. header.style.marginLeft = "-5px";
  30707. header.style.fontWeight = "bold";
  30708. root.appendChild(header);
  30709. };
  30710. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30711. var label = document.createElement("label");
  30712. label.innerHTML = title;
  30713. label.style.color = color;
  30714. root.appendChild(label);
  30715. root.appendChild(document.createElement("br"));
  30716. };
  30717. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30718. if (tag === void 0) { tag = null; }
  30719. var label = document.createElement("label");
  30720. var boundingBoxesCheckbox = document.createElement("input");
  30721. boundingBoxesCheckbox.type = "checkbox";
  30722. boundingBoxesCheckbox.checked = initialState;
  30723. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30724. task(evt.target, tag);
  30725. });
  30726. label.appendChild(boundingBoxesCheckbox);
  30727. var container = document.createElement("span");
  30728. var leftPart = document.createElement("span");
  30729. var rightPart = document.createElement("span");
  30730. rightPart.style.cssFloat = "right";
  30731. leftPart.innerHTML = leftTitle;
  30732. rightPart.innerHTML = rightTitle;
  30733. rightPart.style.fontSize = "12px";
  30734. rightPart.style.maxWidth = "200px";
  30735. container.appendChild(leftPart);
  30736. container.appendChild(rightPart);
  30737. label.appendChild(container);
  30738. root.appendChild(label);
  30739. root.appendChild(document.createElement("br"));
  30740. };
  30741. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30742. if (tag === void 0) { tag = null; }
  30743. var label = document.createElement("label");
  30744. var checkBox = document.createElement("input");
  30745. checkBox.type = "checkbox";
  30746. checkBox.checked = initialState;
  30747. checkBox.addEventListener("change", function (evt) {
  30748. task(evt.target, tag);
  30749. });
  30750. label.appendChild(checkBox);
  30751. label.appendChild(document.createTextNode(title));
  30752. root.appendChild(label);
  30753. root.appendChild(document.createElement("br"));
  30754. };
  30755. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30756. if (tag === void 0) { tag = null; }
  30757. var button = document.createElement("button");
  30758. button.innerHTML = title;
  30759. button.style.height = "24px";
  30760. button.style.color = "#444444";
  30761. button.style.border = "1px solid white";
  30762. button.className = "debugLayerButton";
  30763. button.addEventListener("click", function (evt) {
  30764. task(evt.target, tag);
  30765. });
  30766. root.appendChild(button);
  30767. root.appendChild(document.createElement("br"));
  30768. };
  30769. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30770. if (tag === void 0) { tag = null; }
  30771. var label = document.createElement("label");
  30772. var boundingBoxesRadio = document.createElement("input");
  30773. boundingBoxesRadio.type = "radio";
  30774. boundingBoxesRadio.name = name;
  30775. boundingBoxesRadio.checked = initialState;
  30776. boundingBoxesRadio.addEventListener("change", function (evt) {
  30777. task(evt.target, tag);
  30778. });
  30779. label.appendChild(boundingBoxesRadio);
  30780. label.appendChild(document.createTextNode(title));
  30781. root.appendChild(label);
  30782. root.appendChild(document.createElement("br"));
  30783. };
  30784. DebugLayer.prototype._generateDOMelements = function () {
  30785. var _this = this;
  30786. this._globalDiv.id = "DebugLayer";
  30787. this._globalDiv.style.position = "absolute";
  30788. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30789. this._globalDiv.style.fontSize = "14px";
  30790. this._globalDiv.style.color = "white";
  30791. // Drawing canvas
  30792. this._drawingCanvas = document.createElement("canvas");
  30793. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30794. this._drawingCanvas.style.position = "absolute";
  30795. this._drawingCanvas.style.pointerEvents = "none";
  30796. this._drawingContext = this._drawingCanvas.getContext("2d");
  30797. this._globalDiv.appendChild(this._drawingCanvas);
  30798. if (this._showUI) {
  30799. var background = "rgba(128, 128, 128, 0.4)";
  30800. var border = "rgb(180, 180, 180) solid 1px";
  30801. // Stats
  30802. this._statsDiv = document.createElement("div");
  30803. this._statsDiv.id = "DebugLayerStats";
  30804. this._statsDiv.style.border = border;
  30805. this._statsDiv.style.position = "absolute";
  30806. this._statsDiv.style.background = background;
  30807. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30808. this._generateheader(this._statsDiv, "STATISTICS");
  30809. this._statsSubsetDiv = document.createElement("div");
  30810. this._statsSubsetDiv.style.paddingTop = "5px";
  30811. this._statsSubsetDiv.style.paddingBottom = "5px";
  30812. this._statsSubsetDiv.style.overflowY = "auto";
  30813. this._statsDiv.appendChild(this._statsSubsetDiv);
  30814. // Tree
  30815. this._treeDiv = document.createElement("div");
  30816. this._treeDiv.id = "DebugLayerTree";
  30817. this._treeDiv.style.border = border;
  30818. this._treeDiv.style.position = "absolute";
  30819. this._treeDiv.style.background = background;
  30820. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30821. this._treeDiv.style.display = "none";
  30822. this._generateheader(this._treeDiv, "MESHES TREE");
  30823. this._treeSubsetDiv = document.createElement("div");
  30824. this._treeSubsetDiv.style.paddingTop = "5px";
  30825. this._treeSubsetDiv.style.paddingRight = "5px";
  30826. this._treeSubsetDiv.style.overflowY = "auto";
  30827. this._treeSubsetDiv.style.maxHeight = "300px";
  30828. this._treeDiv.appendChild(this._treeSubsetDiv);
  30829. this._needToRefreshMeshesTree = true;
  30830. // Logs
  30831. this._logDiv = document.createElement("div");
  30832. this._logDiv.style.border = border;
  30833. this._logDiv.id = "DebugLayerLogs";
  30834. this._logDiv.style.position = "absolute";
  30835. this._logDiv.style.background = background;
  30836. this._logDiv.style.padding = "0px 0px 0px 5px";
  30837. this._logDiv.style.display = "none";
  30838. this._generateheader(this._logDiv, "LOGS");
  30839. this._logSubsetDiv = document.createElement("div");
  30840. this._logSubsetDiv.style.height = "127px";
  30841. this._logSubsetDiv.style.paddingTop = "5px";
  30842. this._logSubsetDiv.style.overflowY = "auto";
  30843. this._logSubsetDiv.style.fontSize = "12px";
  30844. this._logSubsetDiv.style.fontFamily = "consolas";
  30845. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30846. this._logDiv.appendChild(this._logSubsetDiv);
  30847. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30848. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30849. };
  30850. // Options
  30851. this._optionsDiv = document.createElement("div");
  30852. this._optionsDiv.id = "DebugLayerOptions";
  30853. this._optionsDiv.style.border = border;
  30854. this._optionsDiv.style.position = "absolute";
  30855. this._optionsDiv.style.background = background;
  30856. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30857. this._optionsDiv.style.overflowY = "auto";
  30858. this._generateheader(this._optionsDiv, "OPTIONS");
  30859. this._optionsSubsetDiv = document.createElement("div");
  30860. this._optionsSubsetDiv.style.paddingTop = "5px";
  30861. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30862. this._optionsSubsetDiv.style.overflowY = "auto";
  30863. this._optionsSubsetDiv.style.maxHeight = "200px";
  30864. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30865. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30866. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30867. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30868. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30869. _this._displayTree = element.checked;
  30870. _this._needToRefreshMeshesTree = true;
  30871. });
  30872. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30873. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30874. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  30875. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  30876. _this._labelsEnabled = element.checked;
  30877. if (!_this._labelsEnabled) {
  30878. _this._clearLabels();
  30879. }
  30880. });
  30881. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  30882. if (element.checked) {
  30883. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  30884. }
  30885. else {
  30886. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  30887. }
  30888. });
  30889. ;
  30890. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30891. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  30892. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  30893. if (element.checked) {
  30894. _this._scene.forceWireframe = false;
  30895. _this._scene.forcePointsCloud = false;
  30896. }
  30897. });
  30898. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  30899. if (element.checked) {
  30900. _this._scene.forceWireframe = true;
  30901. _this._scene.forcePointsCloud = false;
  30902. }
  30903. });
  30904. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  30905. if (element.checked) {
  30906. _this._scene.forceWireframe = false;
  30907. _this._scene.forcePointsCloud = true;
  30908. }
  30909. });
  30910. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30911. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  30912. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  30913. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  30914. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  30915. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  30916. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  30917. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  30918. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  30919. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  30920. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30921. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  30922. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  30923. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  30924. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  30925. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  30926. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  30927. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  30928. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  30929. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  30930. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  30931. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  30932. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  30933. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  30934. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  30935. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30936. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30937. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  30938. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  30939. if (element.checked) {
  30940. _this._scene.headphone = true;
  30941. }
  30942. });
  30943. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30944. if (element.checked) {
  30945. _this._scene.headphone = false;
  30946. }
  30947. });
  30948. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  30949. _this._scene.audioEnabled = !element.checked;
  30950. });
  30951. }
  30952. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30953. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  30954. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  30955. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30956. this._globalDiv.appendChild(this._statsDiv);
  30957. this._globalDiv.appendChild(this._logDiv);
  30958. this._globalDiv.appendChild(this._optionsDiv);
  30959. this._globalDiv.appendChild(this._treeDiv);
  30960. }
  30961. };
  30962. DebugLayer.prototype._displayStats = function () {
  30963. var scene = this._scene;
  30964. var engine = scene.getEngine();
  30965. var glInfo = engine.getGlInfo();
  30966. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  30967. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30968. + "<b>Count</b><br>"
  30969. + "Total meshes: " + scene.meshes.length + "<br>"
  30970. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  30971. + "Total materials: " + scene.materials.length + "<br>"
  30972. + "Total textures: " + scene.textures.length + "<br>"
  30973. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  30974. + "Active indices: " + scene.getActiveIndices() + "<br>"
  30975. + "Active bones: " + scene.getActiveBones() + "<br>"
  30976. + "Active particles: " + scene.getActiveParticles() + "<br>"
  30977. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  30978. + "<b>Duration</b><br>"
  30979. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  30980. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  30981. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  30982. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  30983. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  30984. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  30985. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  30986. + "</div>"
  30987. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30988. + "<b>Extensions</b><br>"
  30989. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  30990. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  30991. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  30992. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  30993. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  30994. + "<b>Caps.</b><br>"
  30995. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  30996. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  30997. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  30998. + "</div><br>"
  30999. + "<b>Info</b><br>"
  31000. + glInfo.version + "<br>"
  31001. + glInfo.renderer + "<br>";
  31002. if (this.customStatsFunction) {
  31003. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31004. }
  31005. };
  31006. return DebugLayer;
  31007. })();
  31008. BABYLON.DebugLayer = DebugLayer;
  31009. })(BABYLON || (BABYLON = {}));
  31010. var BABYLON;
  31011. (function (BABYLON) {
  31012. var RawTexture = (function (_super) {
  31013. __extends(RawTexture, _super);
  31014. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31015. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31016. if (invertY === void 0) { invertY = false; }
  31017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31018. _super.call(this, null, scene, !generateMipMaps, invertY);
  31019. this.format = format;
  31020. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31021. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31022. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31023. }
  31024. RawTexture.prototype.update = function (data) {
  31025. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31026. };
  31027. // Statics
  31028. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31029. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31030. if (invertY === void 0) { invertY = false; }
  31031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31032. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31033. };
  31034. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31035. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31036. if (invertY === void 0) { invertY = false; }
  31037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31038. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31039. };
  31040. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31041. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31042. if (invertY === void 0) { invertY = false; }
  31043. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31044. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31045. };
  31046. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31047. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31048. if (invertY === void 0) { invertY = false; }
  31049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31050. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31051. };
  31052. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31053. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31054. if (invertY === void 0) { invertY = false; }
  31055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31056. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31057. };
  31058. return RawTexture;
  31059. })(BABYLON.Texture);
  31060. BABYLON.RawTexture = RawTexture;
  31061. })(BABYLON || (BABYLON = {}));
  31062. var BABYLON;
  31063. (function (BABYLON) {
  31064. var IndexedVector2 = (function (_super) {
  31065. __extends(IndexedVector2, _super);
  31066. function IndexedVector2(original, index) {
  31067. _super.call(this, original.x, original.y);
  31068. this.index = index;
  31069. }
  31070. return IndexedVector2;
  31071. })(BABYLON.Vector2);
  31072. var PolygonPoints = (function () {
  31073. function PolygonPoints() {
  31074. this.elements = new Array();
  31075. }
  31076. PolygonPoints.prototype.add = function (originalPoints) {
  31077. var _this = this;
  31078. var result = new Array();
  31079. originalPoints.forEach(function (point) {
  31080. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31081. var newPoint = new IndexedVector2(point, _this.elements.length);
  31082. result.push(newPoint);
  31083. _this.elements.push(newPoint);
  31084. }
  31085. });
  31086. return result;
  31087. };
  31088. PolygonPoints.prototype.computeBounds = function () {
  31089. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31090. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31091. this.elements.forEach(function (point) {
  31092. // x
  31093. if (point.x < lmin.x) {
  31094. lmin.x = point.x;
  31095. }
  31096. else if (point.x > lmax.x) {
  31097. lmax.x = point.x;
  31098. }
  31099. // y
  31100. if (point.y < lmin.y) {
  31101. lmin.y = point.y;
  31102. }
  31103. else if (point.y > lmax.y) {
  31104. lmax.y = point.y;
  31105. }
  31106. });
  31107. return {
  31108. min: lmin,
  31109. max: lmax,
  31110. width: lmax.x - lmin.x,
  31111. height: lmax.y - lmin.y
  31112. };
  31113. };
  31114. return PolygonPoints;
  31115. })();
  31116. var Polygon = (function () {
  31117. function Polygon() {
  31118. }
  31119. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31120. return [
  31121. new BABYLON.Vector2(xmin, ymin),
  31122. new BABYLON.Vector2(xmax, ymin),
  31123. new BABYLON.Vector2(xmax, ymax),
  31124. new BABYLON.Vector2(xmin, ymax)
  31125. ];
  31126. };
  31127. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31128. if (cx === void 0) { cx = 0; }
  31129. if (cy === void 0) { cy = 0; }
  31130. if (numberOfSides === void 0) { numberOfSides = 32; }
  31131. var result = new Array();
  31132. var angle = 0;
  31133. var increment = (Math.PI * 2) / numberOfSides;
  31134. for (var i = 0; i < numberOfSides; i++) {
  31135. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31136. angle -= increment;
  31137. }
  31138. return result;
  31139. };
  31140. Polygon.Parse = function (input) {
  31141. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31142. var i, result = [];
  31143. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31144. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31145. }
  31146. return result;
  31147. };
  31148. Polygon.StartingAt = function (x, y) {
  31149. return BABYLON.Path2.StartingAt(x, y);
  31150. };
  31151. return Polygon;
  31152. })();
  31153. BABYLON.Polygon = Polygon;
  31154. var PolygonMeshBuilder = (function () {
  31155. function PolygonMeshBuilder(name, contours, scene) {
  31156. this._points = new PolygonPoints();
  31157. this._outlinepoints = new PolygonPoints();
  31158. this._holes = [];
  31159. if (!("poly2tri" in window)) {
  31160. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31161. }
  31162. this._name = name;
  31163. this._scene = scene;
  31164. var points;
  31165. if (contours instanceof BABYLON.Path2) {
  31166. points = contours.getPoints();
  31167. }
  31168. else {
  31169. points = contours;
  31170. }
  31171. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31172. this._outlinepoints.add(points);
  31173. }
  31174. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31175. this._swctx.addHole(this._points.add(hole));
  31176. var holepoints = new PolygonPoints();
  31177. holepoints.add(hole);
  31178. this._holes.push(holepoints);
  31179. return this;
  31180. };
  31181. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31182. var _this = this;
  31183. if (updatable === void 0) { updatable = false; }
  31184. var result = new BABYLON.Mesh(this._name, this._scene);
  31185. var normals = [];
  31186. var positions = [];
  31187. var uvs = [];
  31188. var bounds = this._points.computeBounds();
  31189. this._points.elements.forEach(function (p) {
  31190. normals.push(0, 1.0, 0);
  31191. positions.push(p.x, 0, p.y);
  31192. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31193. });
  31194. var indices = [];
  31195. this._swctx.triangulate();
  31196. this._swctx.getTriangles().forEach(function (triangle) {
  31197. triangle.getPoints().forEach(function (point) {
  31198. indices.push(point.index);
  31199. });
  31200. });
  31201. if (depth > 0) {
  31202. var positionscount = (positions.length / 3); //get the current pointcount
  31203. this._points.elements.forEach(function (p) {
  31204. normals.push(0, -1.0, 0);
  31205. positions.push(p.x, -depth, p.y);
  31206. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31207. });
  31208. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31209. var p2;
  31210. var poscounter = 0;
  31211. this._swctx.getTriangles().forEach(function (triangle) {
  31212. triangle.getPoints().forEach(function (point) {
  31213. switch (poscounter) {
  31214. case 0:
  31215. p1 = point;
  31216. break;
  31217. case 1:
  31218. p2 = point;
  31219. break;
  31220. case 2:
  31221. indices.push(point.index + positionscount);
  31222. indices.push(p2.index + positionscount);
  31223. indices.push(p1.index + positionscount);
  31224. poscounter = -1;
  31225. break;
  31226. }
  31227. poscounter++;
  31228. //indices.push((<IndexedVector2>point).index + positionscount);
  31229. });
  31230. });
  31231. //Add the sides
  31232. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31233. this._holes.forEach(function (hole) {
  31234. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31235. });
  31236. }
  31237. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31238. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31239. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31240. result.setIndices(indices);
  31241. return result;
  31242. };
  31243. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31244. var StartIndex = positions.length / 3;
  31245. var ulength = 0;
  31246. for (var i = 0; i < points.elements.length; i++) {
  31247. var p = points.elements[i];
  31248. var p1;
  31249. if ((i + 1) > points.elements.length - 1) {
  31250. p1 = points.elements[0];
  31251. }
  31252. else {
  31253. p1 = points.elements[i + 1];
  31254. }
  31255. positions.push(p.x, 0, p.y);
  31256. positions.push(p.x, -depth, p.y);
  31257. positions.push(p1.x, 0, p1.y);
  31258. positions.push(p1.x, -depth, p1.y);
  31259. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31260. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31261. var v3 = v2.subtract(v1);
  31262. var v4 = new BABYLON.Vector3(0, 1, 0);
  31263. var vn = BABYLON.Vector3.Cross(v3, v4);
  31264. vn = vn.normalize();
  31265. uvs.push(ulength / bounds.width, 0);
  31266. uvs.push(ulength / bounds.width, 1);
  31267. ulength += v3.length();
  31268. uvs.push((ulength / bounds.width), 0);
  31269. uvs.push((ulength / bounds.width), 1);
  31270. if (!flip) {
  31271. normals.push(-vn.x, -vn.y, -vn.z);
  31272. normals.push(-vn.x, -vn.y, -vn.z);
  31273. normals.push(-vn.x, -vn.y, -vn.z);
  31274. normals.push(-vn.x, -vn.y, -vn.z);
  31275. indices.push(StartIndex);
  31276. indices.push(StartIndex + 1);
  31277. indices.push(StartIndex + 2);
  31278. indices.push(StartIndex + 1);
  31279. indices.push(StartIndex + 3);
  31280. indices.push(StartIndex + 2);
  31281. }
  31282. else {
  31283. normals.push(vn.x, vn.y, vn.z);
  31284. normals.push(vn.x, vn.y, vn.z);
  31285. normals.push(vn.x, vn.y, vn.z);
  31286. normals.push(vn.x, vn.y, vn.z);
  31287. indices.push(StartIndex);
  31288. indices.push(StartIndex + 2);
  31289. indices.push(StartIndex + 1);
  31290. indices.push(StartIndex + 1);
  31291. indices.push(StartIndex + 2);
  31292. indices.push(StartIndex + 3);
  31293. }
  31294. StartIndex += 4;
  31295. }
  31296. ;
  31297. };
  31298. return PolygonMeshBuilder;
  31299. })();
  31300. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31301. })(BABYLON || (BABYLON = {}));
  31302. var BABYLON;
  31303. (function (BABYLON) {
  31304. var SimplificationSettings = (function () {
  31305. function SimplificationSettings(quality, distance, optimizeMesh) {
  31306. this.quality = quality;
  31307. this.distance = distance;
  31308. this.optimizeMesh = optimizeMesh;
  31309. }
  31310. return SimplificationSettings;
  31311. })();
  31312. BABYLON.SimplificationSettings = SimplificationSettings;
  31313. var SimplificationQueue = (function () {
  31314. function SimplificationQueue() {
  31315. this.running = false;
  31316. this._simplificationArray = [];
  31317. }
  31318. SimplificationQueue.prototype.addTask = function (task) {
  31319. this._simplificationArray.push(task);
  31320. };
  31321. SimplificationQueue.prototype.executeNext = function () {
  31322. var task = this._simplificationArray.pop();
  31323. if (task) {
  31324. this.running = true;
  31325. this.runSimplification(task);
  31326. }
  31327. else {
  31328. this.running = false;
  31329. }
  31330. };
  31331. SimplificationQueue.prototype.runSimplification = function (task) {
  31332. var _this = this;
  31333. if (task.parallelProcessing) {
  31334. //parallel simplifier
  31335. task.settings.forEach(function (setting) {
  31336. var simplifier = _this.getSimplifier(task);
  31337. simplifier.simplify(setting, function (newMesh) {
  31338. task.mesh.addLODLevel(setting.distance, newMesh);
  31339. newMesh.isVisible = true;
  31340. //check if it is the last
  31341. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31342. //all done, run the success callback.
  31343. task.successCallback();
  31344. }
  31345. _this.executeNext();
  31346. });
  31347. });
  31348. }
  31349. else {
  31350. //single simplifier.
  31351. var simplifier = this.getSimplifier(task);
  31352. var runDecimation = function (setting, callback) {
  31353. simplifier.simplify(setting, function (newMesh) {
  31354. task.mesh.addLODLevel(setting.distance, newMesh);
  31355. newMesh.isVisible = true;
  31356. //run the next quality level
  31357. callback();
  31358. });
  31359. };
  31360. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31361. runDecimation(task.settings[loop.index], function () {
  31362. loop.executeNext();
  31363. });
  31364. }, function () {
  31365. //execution ended, run the success callback.
  31366. if (task.successCallback) {
  31367. task.successCallback();
  31368. }
  31369. _this.executeNext();
  31370. });
  31371. }
  31372. };
  31373. SimplificationQueue.prototype.getSimplifier = function (task) {
  31374. switch (task.simplificationType) {
  31375. case SimplificationType.QUADRATIC:
  31376. default:
  31377. return new QuadraticErrorSimplification(task.mesh);
  31378. }
  31379. };
  31380. return SimplificationQueue;
  31381. })();
  31382. BABYLON.SimplificationQueue = SimplificationQueue;
  31383. /**
  31384. * The implemented types of simplification.
  31385. * At the moment only Quadratic Error Decimation is implemented.
  31386. */
  31387. (function (SimplificationType) {
  31388. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31389. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31390. var SimplificationType = BABYLON.SimplificationType;
  31391. var DecimationTriangle = (function () {
  31392. function DecimationTriangle(vertices) {
  31393. this.vertices = vertices;
  31394. this.error = new Array(4);
  31395. this.deleted = false;
  31396. this.isDirty = false;
  31397. this.deletePending = false;
  31398. this.borderFactor = 0;
  31399. }
  31400. return DecimationTriangle;
  31401. })();
  31402. BABYLON.DecimationTriangle = DecimationTriangle;
  31403. var DecimationVertex = (function () {
  31404. function DecimationVertex(position, id) {
  31405. this.position = position;
  31406. this.id = id;
  31407. this.isBorder = true;
  31408. this.q = new QuadraticMatrix();
  31409. this.triangleCount = 0;
  31410. this.triangleStart = 0;
  31411. this.originalOffsets = [];
  31412. }
  31413. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31414. this.position.copyFrom(newPosition);
  31415. };
  31416. return DecimationVertex;
  31417. })();
  31418. BABYLON.DecimationVertex = DecimationVertex;
  31419. var QuadraticMatrix = (function () {
  31420. function QuadraticMatrix(data) {
  31421. this.data = new Array(10);
  31422. for (var i = 0; i < 10; ++i) {
  31423. if (data && data[i]) {
  31424. this.data[i] = data[i];
  31425. }
  31426. else {
  31427. this.data[i] = 0;
  31428. }
  31429. }
  31430. }
  31431. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31432. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31433. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31434. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31435. return det;
  31436. };
  31437. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31438. for (var i = 0; i < 10; ++i) {
  31439. this.data[i] += matrix.data[i];
  31440. }
  31441. };
  31442. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31443. for (var i = 0; i < 10; ++i) {
  31444. this.data[i] += data[i];
  31445. }
  31446. };
  31447. QuadraticMatrix.prototype.add = function (matrix) {
  31448. var m = new QuadraticMatrix();
  31449. for (var i = 0; i < 10; ++i) {
  31450. m.data[i] = this.data[i] + matrix.data[i];
  31451. }
  31452. return m;
  31453. };
  31454. QuadraticMatrix.FromData = function (a, b, c, d) {
  31455. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31456. };
  31457. //returning an array to avoid garbage collection
  31458. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31459. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31460. };
  31461. return QuadraticMatrix;
  31462. })();
  31463. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31464. var Reference = (function () {
  31465. function Reference(vertexId, triangleId) {
  31466. this.vertexId = vertexId;
  31467. this.triangleId = triangleId;
  31468. }
  31469. return Reference;
  31470. })();
  31471. BABYLON.Reference = Reference;
  31472. /**
  31473. * An implementation of the Quadratic Error simplification algorithm.
  31474. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31475. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31476. * @author RaananW
  31477. */
  31478. var QuadraticErrorSimplification = (function () {
  31479. function QuadraticErrorSimplification(_mesh) {
  31480. this._mesh = _mesh;
  31481. this.initialized = false;
  31482. this.syncIterations = 5000;
  31483. this.aggressiveness = 7;
  31484. this.decimationIterations = 100;
  31485. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31486. }
  31487. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31488. var _this = this;
  31489. this.initDecimatedMesh();
  31490. //iterating through the submeshes array, one after the other.
  31491. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31492. _this.initWithMesh(loop.index, function () {
  31493. _this.runDecimation(settings, loop.index, function () {
  31494. loop.executeNext();
  31495. });
  31496. }, settings.optimizeMesh);
  31497. }, function () {
  31498. setTimeout(function () {
  31499. successCallback(_this._reconstructedMesh);
  31500. }, 0);
  31501. });
  31502. };
  31503. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31504. var _this = this;
  31505. var gCount = 0;
  31506. triangle.vertices.forEach(function (vertex) {
  31507. var count = 0;
  31508. var vPos = vertex.position;
  31509. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31510. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31511. ++count;
  31512. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31513. ++count;
  31514. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31515. ++count;
  31516. if (count > 1) {
  31517. ++gCount;
  31518. }
  31519. ;
  31520. });
  31521. if (gCount > 1) {
  31522. console.log(triangle, gCount);
  31523. }
  31524. return gCount > 1;
  31525. };
  31526. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31527. var _this = this;
  31528. var targetCount = ~~(this.triangles.length * settings.quality);
  31529. var deletedTriangles = 0;
  31530. var triangleCount = this.triangles.length;
  31531. var iterationFunction = function (iteration, callback) {
  31532. setTimeout(function () {
  31533. if (iteration % 5 === 0) {
  31534. _this.updateMesh(iteration === 0);
  31535. }
  31536. for (var i = 0; i < _this.triangles.length; ++i) {
  31537. _this.triangles[i].isDirty = false;
  31538. }
  31539. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31540. var trianglesIterator = function (i) {
  31541. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31542. var t = _this.triangles[tIdx];
  31543. if (!t)
  31544. return;
  31545. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31546. return;
  31547. }
  31548. for (var j = 0; j < 3; ++j) {
  31549. if (t.error[j] < threshold) {
  31550. var deleted0 = [];
  31551. var deleted1 = [];
  31552. var v0 = t.vertices[j];
  31553. var v1 = t.vertices[(j + 1) % 3];
  31554. if (v0.isBorder !== v1.isBorder)
  31555. continue;
  31556. var p = BABYLON.Vector3.Zero();
  31557. var n = BABYLON.Vector3.Zero();
  31558. var uv = BABYLON.Vector2.Zero();
  31559. var color = new BABYLON.Color4(0, 0, 0, 1);
  31560. _this.calculateError(v0, v1, p, n, uv, color);
  31561. var delTr = [];
  31562. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31563. continue;
  31564. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31565. continue;
  31566. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31567. continue;
  31568. var uniqueArray = [];
  31569. delTr.forEach(function (deletedT) {
  31570. if (uniqueArray.indexOf(deletedT) === -1) {
  31571. deletedT.deletePending = true;
  31572. uniqueArray.push(deletedT);
  31573. }
  31574. });
  31575. if (uniqueArray.length % 2 != 0) {
  31576. continue;
  31577. }
  31578. v0.q = v1.q.add(v0.q);
  31579. v0.updatePosition(p);
  31580. var tStart = _this.references.length;
  31581. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31582. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31583. var tCount = _this.references.length - tStart;
  31584. if (tCount <= v0.triangleCount) {
  31585. if (tCount) {
  31586. for (var c = 0; c < tCount; c++) {
  31587. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31588. }
  31589. }
  31590. }
  31591. else {
  31592. v0.triangleStart = tStart;
  31593. }
  31594. v0.triangleCount = tCount;
  31595. break;
  31596. }
  31597. }
  31598. };
  31599. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31600. }, 0);
  31601. };
  31602. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31603. if (triangleCount - deletedTriangles <= targetCount)
  31604. loop.breakLoop();
  31605. else {
  31606. iterationFunction(loop.index, function () {
  31607. loop.executeNext();
  31608. });
  31609. }
  31610. }, function () {
  31611. setTimeout(function () {
  31612. //reconstruct this part of the mesh
  31613. _this.reconstructMesh(submeshIndex);
  31614. successCallback();
  31615. }, 0);
  31616. });
  31617. };
  31618. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31619. var _this = this;
  31620. this.vertices = [];
  31621. this.triangles = [];
  31622. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31623. var indices = this._mesh.getIndices();
  31624. var submesh = this._mesh.subMeshes[submeshIndex];
  31625. var findInVertices = function (positionToSearch) {
  31626. if (optimizeMesh) {
  31627. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31628. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31629. return _this.vertices[ii];
  31630. }
  31631. }
  31632. }
  31633. return null;
  31634. };
  31635. var vertexReferences = [];
  31636. var vertexInit = function (i) {
  31637. var offset = i + submesh.verticesStart;
  31638. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31639. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31640. vertex.originalOffsets.push(offset);
  31641. if (vertex.id == _this.vertices.length) {
  31642. _this.vertices.push(vertex);
  31643. }
  31644. vertexReferences.push(vertex.id);
  31645. };
  31646. //var totalVertices = mesh.getTotalVertices();
  31647. var totalVertices = submesh.verticesCount;
  31648. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31649. var indicesInit = function (i) {
  31650. var offset = (submesh.indexStart / 3) + i;
  31651. var pos = (offset * 3);
  31652. var i0 = indices[pos + 0];
  31653. var i1 = indices[pos + 1];
  31654. var i2 = indices[pos + 2];
  31655. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31656. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31657. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31658. var triangle = new DecimationTriangle([v0, v1, v2]);
  31659. triangle.originalOffset = pos;
  31660. _this.triangles.push(triangle);
  31661. };
  31662. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31663. _this.init(callback);
  31664. });
  31665. });
  31666. };
  31667. QuadraticErrorSimplification.prototype.init = function (callback) {
  31668. var _this = this;
  31669. var triangleInit1 = function (i) {
  31670. var t = _this.triangles[i];
  31671. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31672. for (var j = 0; j < 3; j++) {
  31673. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  31674. }
  31675. };
  31676. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31677. var triangleInit2 = function (i) {
  31678. var t = _this.triangles[i];
  31679. for (var j = 0; j < 3; ++j) {
  31680. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31681. }
  31682. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31683. };
  31684. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31685. _this.initialized = true;
  31686. callback();
  31687. });
  31688. });
  31689. };
  31690. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31691. var newTriangles = [];
  31692. var i;
  31693. for (i = 0; i < this.vertices.length; ++i) {
  31694. this.vertices[i].triangleCount = 0;
  31695. }
  31696. var t;
  31697. var j;
  31698. for (i = 0; i < this.triangles.length; ++i) {
  31699. if (!this.triangles[i].deleted) {
  31700. t = this.triangles[i];
  31701. for (j = 0; j < 3; ++j) {
  31702. t.vertices[j].triangleCount = 1;
  31703. }
  31704. newTriangles.push(t);
  31705. }
  31706. }
  31707. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31708. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31709. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31710. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31711. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31712. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31713. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31714. var vertexCount = 0;
  31715. for (i = 0; i < this.vertices.length; ++i) {
  31716. var vertex = this.vertices[i];
  31717. vertex.id = vertexCount;
  31718. if (vertex.triangleCount) {
  31719. vertex.originalOffsets.forEach(function (originalOffset) {
  31720. newPositionData.push(vertex.position.x);
  31721. newPositionData.push(vertex.position.y);
  31722. newPositionData.push(vertex.position.z);
  31723. newNormalData.push(normalData[originalOffset * 3]);
  31724. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31725. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31726. if (uvs && uvs.length) {
  31727. newUVsData.push(uvs[(originalOffset * 2)]);
  31728. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31729. }
  31730. else if (colorsData && colorsData.length) {
  31731. newColorsData.push(colorsData[(originalOffset * 4)]);
  31732. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31733. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31734. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31735. }
  31736. ++vertexCount;
  31737. });
  31738. }
  31739. }
  31740. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31741. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31742. var submeshesArray = this._reconstructedMesh.subMeshes;
  31743. this._reconstructedMesh.subMeshes = [];
  31744. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31745. var originalIndices = this._mesh.getIndices();
  31746. for (i = 0; i < newTriangles.length; ++i) {
  31747. var t = newTriangles[i];
  31748. //now get the new referencing point for each vertex
  31749. [0, 1, 2].forEach(function (idx) {
  31750. var id = originalIndices[t.originalOffset + idx];
  31751. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31752. if (offset < 0)
  31753. offset = 0;
  31754. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31755. });
  31756. }
  31757. //overwriting the old vertex buffers and indices.
  31758. this._reconstructedMesh.setIndices(newIndicesArray);
  31759. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31760. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31761. if (newUVsData.length > 0)
  31762. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31763. if (newColorsData.length > 0)
  31764. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31765. //create submesh
  31766. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31767. if (submeshIndex > 0) {
  31768. this._reconstructedMesh.subMeshes = [];
  31769. submeshesArray.forEach(function (submesh) {
  31770. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31771. });
  31772. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31773. }
  31774. };
  31775. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31776. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31777. this._reconstructedMesh.material = this._mesh.material;
  31778. this._reconstructedMesh.parent = this._mesh.parent;
  31779. this._reconstructedMesh.isVisible = false;
  31780. };
  31781. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31782. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31783. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31784. if (t.deleted)
  31785. continue;
  31786. var s = this.references[vertex1.triangleStart + i].vertexId;
  31787. var v1 = t.vertices[(s + 1) % 3];
  31788. var v2 = t.vertices[(s + 2) % 3];
  31789. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31790. deletedArray[i] = true;
  31791. delTr.push(t);
  31792. continue;
  31793. }
  31794. var d1 = v1.position.subtract(point);
  31795. d1 = d1.normalize();
  31796. var d2 = v2.position.subtract(point);
  31797. d2 = d2.normalize();
  31798. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31799. return true;
  31800. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31801. deletedArray[i] = false;
  31802. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31803. return true;
  31804. }
  31805. return false;
  31806. };
  31807. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31808. var newDeleted = deletedTriangles;
  31809. for (var i = 0; i < vertex.triangleCount; ++i) {
  31810. var ref = this.references[vertex.triangleStart + i];
  31811. var t = this.triangles[ref.triangleId];
  31812. if (t.deleted)
  31813. continue;
  31814. if (deletedArray[i] && t.deletePending) {
  31815. t.deleted = true;
  31816. newDeleted++;
  31817. continue;
  31818. }
  31819. t.vertices[ref.vertexId] = origVertex;
  31820. t.isDirty = true;
  31821. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31822. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31823. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31824. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31825. this.references.push(ref);
  31826. }
  31827. return newDeleted;
  31828. };
  31829. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31830. for (var i = 0; i < this.vertices.length; ++i) {
  31831. var vCount = [];
  31832. var vId = [];
  31833. var v = this.vertices[i];
  31834. var j;
  31835. for (j = 0; j < v.triangleCount; ++j) {
  31836. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31837. for (var ii = 0; ii < 3; ii++) {
  31838. var ofs = 0;
  31839. var vv = triangle.vertices[ii];
  31840. while (ofs < vCount.length) {
  31841. if (vId[ofs] === vv.id)
  31842. break;
  31843. ++ofs;
  31844. }
  31845. if (ofs === vCount.length) {
  31846. vCount.push(1);
  31847. vId.push(vv.id);
  31848. }
  31849. else {
  31850. vCount[ofs]++;
  31851. }
  31852. }
  31853. }
  31854. for (j = 0; j < vCount.length; ++j) {
  31855. if (vCount[j] === 1) {
  31856. this.vertices[vId[j]].isBorder = true;
  31857. }
  31858. else {
  31859. this.vertices[vId[j]].isBorder = false;
  31860. }
  31861. }
  31862. }
  31863. };
  31864. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31865. if (identifyBorders === void 0) { identifyBorders = false; }
  31866. var i;
  31867. if (!identifyBorders) {
  31868. var newTrianglesVector = [];
  31869. for (i = 0; i < this.triangles.length; ++i) {
  31870. if (!this.triangles[i].deleted) {
  31871. newTrianglesVector.push(this.triangles[i]);
  31872. }
  31873. }
  31874. this.triangles = newTrianglesVector;
  31875. }
  31876. for (i = 0; i < this.vertices.length; ++i) {
  31877. this.vertices[i].triangleCount = 0;
  31878. this.vertices[i].triangleStart = 0;
  31879. }
  31880. var t;
  31881. var j;
  31882. var v;
  31883. for (i = 0; i < this.triangles.length; ++i) {
  31884. t = this.triangles[i];
  31885. for (j = 0; j < 3; ++j) {
  31886. v = t.vertices[j];
  31887. v.triangleCount++;
  31888. }
  31889. }
  31890. var tStart = 0;
  31891. for (i = 0; i < this.vertices.length; ++i) {
  31892. this.vertices[i].triangleStart = tStart;
  31893. tStart += this.vertices[i].triangleCount;
  31894. this.vertices[i].triangleCount = 0;
  31895. }
  31896. var newReferences = new Array(this.triangles.length * 3);
  31897. for (i = 0; i < this.triangles.length; ++i) {
  31898. t = this.triangles[i];
  31899. for (j = 0; j < 3; ++j) {
  31900. v = t.vertices[j];
  31901. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31902. v.triangleCount++;
  31903. }
  31904. }
  31905. this.references = newReferences;
  31906. if (identifyBorders) {
  31907. this.identifyBorder();
  31908. }
  31909. };
  31910. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31911. var x = point.x;
  31912. var y = point.y;
  31913. var z = point.z;
  31914. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  31915. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31916. };
  31917. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31918. var q = vertex1.q.add(vertex2.q);
  31919. var border = vertex1.isBorder && vertex2.isBorder;
  31920. var error = 0;
  31921. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31922. if (qDet !== 0 && !border) {
  31923. if (!pointResult) {
  31924. pointResult = BABYLON.Vector3.Zero();
  31925. }
  31926. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31927. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31928. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31929. error = this.vertexError(q, pointResult);
  31930. }
  31931. else {
  31932. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31933. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31934. var error1 = this.vertexError(q, vertex1.position);
  31935. var error2 = this.vertexError(q, vertex2.position);
  31936. var error3 = this.vertexError(q, p3);
  31937. error = Math.min(error1, error2, error3);
  31938. if (error === error1) {
  31939. if (pointResult) {
  31940. pointResult.copyFrom(vertex1.position);
  31941. }
  31942. }
  31943. else if (error === error2) {
  31944. if (pointResult) {
  31945. pointResult.copyFrom(vertex2.position);
  31946. }
  31947. }
  31948. else {
  31949. if (pointResult) {
  31950. pointResult.copyFrom(p3);
  31951. }
  31952. }
  31953. }
  31954. return error;
  31955. };
  31956. return QuadraticErrorSimplification;
  31957. })();
  31958. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31959. })(BABYLON || (BABYLON = {}));
  31960. var BABYLON;
  31961. (function (BABYLON) {
  31962. var Analyser = (function () {
  31963. function Analyser(scene) {
  31964. this.SMOOTHING = 0.75;
  31965. this.FFT_SIZE = 512;
  31966. this.BARGRAPHAMPLITUDE = 256;
  31967. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  31968. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  31969. this._scene = scene;
  31970. this._audioEngine = BABYLON.Engine.audioEngine;
  31971. if (this._audioEngine.canUseWebAudio) {
  31972. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  31973. this._webAudioAnalyser.minDecibels = -140;
  31974. this._webAudioAnalyser.maxDecibels = 0;
  31975. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31976. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31977. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  31978. }
  31979. }
  31980. Analyser.prototype.getFrequencyBinCount = function () {
  31981. if (this._audioEngine.canUseWebAudio) {
  31982. return this._webAudioAnalyser.frequencyBinCount;
  31983. }
  31984. else {
  31985. return 0;
  31986. }
  31987. };
  31988. Analyser.prototype.getByteFrequencyData = function () {
  31989. if (this._audioEngine.canUseWebAudio) {
  31990. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31991. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31992. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  31993. }
  31994. return this._byteFreqs;
  31995. };
  31996. Analyser.prototype.getByteTimeDomainData = function () {
  31997. if (this._audioEngine.canUseWebAudio) {
  31998. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31999. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32000. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32001. }
  32002. return this._byteTime;
  32003. };
  32004. Analyser.prototype.getFloatFrequencyData = function () {
  32005. if (this._audioEngine.canUseWebAudio) {
  32006. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32007. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32008. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32009. }
  32010. return this._floatFreqs;
  32011. };
  32012. Analyser.prototype.drawDebugCanvas = function () {
  32013. var _this = this;
  32014. if (this._audioEngine.canUseWebAudio) {
  32015. if (!this._debugCanvas) {
  32016. this._debugCanvas = document.createElement("canvas");
  32017. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32018. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32019. this._debugCanvas.style.position = "absolute";
  32020. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32021. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32022. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32023. document.body.appendChild(this._debugCanvas);
  32024. this._registerFunc = function () {
  32025. _this.drawDebugCanvas();
  32026. };
  32027. this._scene.registerBeforeRender(this._registerFunc);
  32028. }
  32029. if (this._registerFunc) {
  32030. var workingArray = this.getByteFrequencyData();
  32031. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32032. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32033. // Draw the frequency domain chart.
  32034. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32035. var value = workingArray[i];
  32036. var percent = value / this.BARGRAPHAMPLITUDE;
  32037. var height = this.DEBUGCANVASSIZE.height * percent;
  32038. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32039. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32040. var hue = i / this.getFrequencyBinCount() * 360;
  32041. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32042. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32043. }
  32044. }
  32045. }
  32046. };
  32047. Analyser.prototype.stopDebugCanvas = function () {
  32048. if (this._debugCanvas) {
  32049. this._scene.unregisterBeforeRender(this._registerFunc);
  32050. this._registerFunc = null;
  32051. document.body.removeChild(this._debugCanvas);
  32052. this._debugCanvas = null;
  32053. this._debugCanvasContext = null;
  32054. }
  32055. };
  32056. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32057. if (this._audioEngine.canUseWebAudio) {
  32058. inputAudioNode.connect(this._webAudioAnalyser);
  32059. this._webAudioAnalyser.connect(outputAudioNode);
  32060. }
  32061. };
  32062. Analyser.prototype.dispose = function () {
  32063. if (this._audioEngine.canUseWebAudio) {
  32064. this._webAudioAnalyser.disconnect();
  32065. }
  32066. };
  32067. return Analyser;
  32068. })();
  32069. BABYLON.Analyser = Analyser;
  32070. })(BABYLON || (BABYLON = {}));
  32071. var BABYLON;
  32072. (function (BABYLON) {
  32073. var DepthRenderer = (function () {
  32074. function DepthRenderer(scene, type) {
  32075. var _this = this;
  32076. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32077. this._viewMatrix = BABYLON.Matrix.Zero();
  32078. this._projectionMatrix = BABYLON.Matrix.Zero();
  32079. this._transformMatrix = BABYLON.Matrix.Zero();
  32080. this._worldViewProjection = BABYLON.Matrix.Zero();
  32081. this._scene = scene;
  32082. var engine = scene.getEngine();
  32083. // Render target
  32084. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32085. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32086. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32087. this._depthMap.refreshRate = 1;
  32088. this._depthMap.renderParticles = false;
  32089. this._depthMap.renderList = null;
  32090. // set default depth value to 1.0 (far away)
  32091. this._depthMap.onClear = function (engine) {
  32092. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32093. };
  32094. // Custom render function
  32095. var renderSubMesh = function (subMesh) {
  32096. var mesh = subMesh.getRenderingMesh();
  32097. var scene = _this._scene;
  32098. var engine = scene.getEngine();
  32099. // Culling
  32100. engine.setState(subMesh.getMaterial().backFaceCulling);
  32101. // Managing instances
  32102. var batch = mesh._getInstancesRenderList(subMesh._id);
  32103. if (batch.mustReturn) {
  32104. return;
  32105. }
  32106. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32107. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32108. engine.enableEffect(_this._effect);
  32109. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32110. var material = subMesh.getMaterial();
  32111. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32112. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32113. // Alpha test
  32114. if (material && material.needAlphaTesting()) {
  32115. var alphaTexture = material.getAlphaTestTexture();
  32116. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32117. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32118. }
  32119. // Bones
  32120. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32121. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32122. }
  32123. // Draw
  32124. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32125. }
  32126. };
  32127. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32128. var index;
  32129. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32130. renderSubMesh(opaqueSubMeshes.data[index]);
  32131. }
  32132. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32133. renderSubMesh(alphaTestSubMeshes.data[index]);
  32134. }
  32135. };
  32136. }
  32137. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32138. var defines = [];
  32139. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32140. var mesh = subMesh.getMesh();
  32141. var scene = mesh.getScene();
  32142. var material = subMesh.getMaterial();
  32143. // Alpha test
  32144. if (material && material.needAlphaTesting()) {
  32145. defines.push("#define ALPHATEST");
  32146. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32147. attribs.push(BABYLON.VertexBuffer.UVKind);
  32148. defines.push("#define UV1");
  32149. }
  32150. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32151. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32152. defines.push("#define UV2");
  32153. }
  32154. }
  32155. // Bones
  32156. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32157. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32158. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32159. defines.push("#define BONES");
  32160. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32161. }
  32162. // Instances
  32163. if (useInstances) {
  32164. defines.push("#define INSTANCES");
  32165. attribs.push("world0");
  32166. attribs.push("world1");
  32167. attribs.push("world2");
  32168. attribs.push("world3");
  32169. }
  32170. // Get correct effect
  32171. var join = defines.join("\n");
  32172. if (this._cachedDefines !== join) {
  32173. this._cachedDefines = join;
  32174. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32175. }
  32176. return this._effect.isReady();
  32177. };
  32178. DepthRenderer.prototype.getDepthMap = function () {
  32179. return this._depthMap;
  32180. };
  32181. // Methods
  32182. DepthRenderer.prototype.dispose = function () {
  32183. this._depthMap.dispose();
  32184. };
  32185. return DepthRenderer;
  32186. })();
  32187. BABYLON.DepthRenderer = DepthRenderer;
  32188. })(BABYLON || (BABYLON = {}));
  32189. var BABYLON;
  32190. (function (BABYLON) {
  32191. var SSAORenderingPipeline = (function (_super) {
  32192. __extends(SSAORenderingPipeline, _super);
  32193. /**
  32194. * @constructor
  32195. * @param {string} name - The rendering pipeline name
  32196. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32197. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  32198. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32199. */
  32200. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32201. var _this = this;
  32202. _super.call(this, scene.getEngine(), name);
  32203. // Members
  32204. /**
  32205. * The PassPostProcess id in the pipeline that contains the original scene color
  32206. * @type {string}
  32207. */
  32208. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32209. /**
  32210. * The SSAO PostProcess id in the pipeline
  32211. * @type {string}
  32212. */
  32213. this.SSAORenderEffect = "SSAORenderEffect";
  32214. /**
  32215. * The horizontal blur PostProcess id in the pipeline
  32216. * @type {string}
  32217. */
  32218. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32219. /**
  32220. * The vertical blur PostProcess id in the pipeline
  32221. * @type {string}
  32222. */
  32223. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32224. /**
  32225. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32226. * @type {string}
  32227. */
  32228. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32229. /**
  32230. * The output strength of the SSAO post-process. Default value is 1.0.
  32231. * @type {number}
  32232. */
  32233. this.totalStrength = 1.0;
  32234. /**
  32235. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32236. * @type {number}
  32237. */
  32238. this.radius = 0.0002;
  32239. /**
  32240. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32241. * Must not be equal to fallOff and superior to fallOff.
  32242. * Default value is 0.0075
  32243. * @type {number}
  32244. */
  32245. this.area = 0.0075;
  32246. /**
  32247. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32248. * Must not be equal to area and inferior to area.
  32249. * Default value is 0.0002
  32250. * @type {number}
  32251. */
  32252. this.fallOff = 0.0002;
  32253. this._firstUpdate = true;
  32254. this._scene = scene;
  32255. // Set up assets
  32256. this._createRandomTexture();
  32257. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32258. var ssaoRatio = ratio.ssaoRatio || ratio;
  32259. var combineRatio = ratio.combineRatio || ratio;
  32260. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32261. this._createSSAOPostProcess(ssaoRatio);
  32262. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32263. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32264. this._createSSAOCombinePostProcess(combineRatio);
  32265. // Set up pipeline
  32266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32267. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32270. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32271. // Finish
  32272. scene.postProcessRenderPipelineManager.addPipeline(this);
  32273. if (cameras)
  32274. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32275. }
  32276. // Public Methods
  32277. /**
  32278. * Returns the horizontal blur PostProcess
  32279. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32280. */
  32281. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32282. return this._blurHPostProcess;
  32283. };
  32284. /**
  32285. * Returns the vertical blur PostProcess
  32286. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32287. */
  32288. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32289. return this._blurVPostProcess;
  32290. };
  32291. /**
  32292. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32293. */
  32294. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32295. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32296. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32297. this._originalColorPostProcess = undefined;
  32298. this._ssaoPostProcess = undefined;
  32299. this._blurHPostProcess = undefined;
  32300. this._blurVPostProcess = undefined;
  32301. this._ssaoCombinePostProcess = undefined;
  32302. this._randomTexture.dispose();
  32303. if (disableDepthRender)
  32304. this._scene.disableDepthRenderer();
  32305. };
  32306. // Private Methods
  32307. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32308. var _this = this;
  32309. var sampleSphere = [
  32310. 0.5381, 0.1856, -0.4319,
  32311. 0.1379, 0.2486, 0.4430,
  32312. 0.3371, 0.5679, -0.0057,
  32313. -0.6999, -0.0451, -0.0019,
  32314. 0.0689, -0.1598, -0.8547,
  32315. 0.0560, 0.0069, -0.1843,
  32316. -0.0146, 0.1402, 0.0762,
  32317. 0.0100, -0.1924, -0.0344,
  32318. -0.3577, -0.5301, -0.4358,
  32319. -0.3169, 0.1063, 0.0158,
  32320. 0.0103, -0.5869, 0.0046,
  32321. -0.0897, -0.4940, 0.3287,
  32322. 0.7119, -0.0154, -0.0918,
  32323. -0.0533, 0.0596, -0.5411,
  32324. 0.0352, -0.0631, 0.5460,
  32325. -0.4776, 0.2847, -0.0271
  32326. ];
  32327. var samplesFactor = 1.0 / 16.0;
  32328. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32329. this._ssaoPostProcess.onApply = function (effect) {
  32330. if (_this._firstUpdate) {
  32331. effect.setArray3("sampleSphere", sampleSphere);
  32332. effect.setFloat("samplesFactor", samplesFactor);
  32333. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32334. _this._firstUpdate = false;
  32335. }
  32336. effect.setFloat("totalStrength", _this.totalStrength);
  32337. effect.setFloat("radius", _this.radius);
  32338. effect.setFloat("area", _this.area);
  32339. effect.setFloat("fallOff", _this.fallOff);
  32340. effect.setTexture("textureSampler", _this._depthTexture);
  32341. effect.setTexture("randomSampler", _this._randomTexture);
  32342. };
  32343. };
  32344. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32345. var _this = this;
  32346. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32347. this._ssaoCombinePostProcess.onApply = function (effect) {
  32348. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32349. };
  32350. };
  32351. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32352. var size = 512;
  32353. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32354. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32355. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32356. var context = this._randomTexture.getContext();
  32357. var rand = function (min, max) {
  32358. return Math.random() * (max - min) + min;
  32359. };
  32360. for (var x = 0; x < size; x++) {
  32361. for (var y = 0; y < size; y++) {
  32362. var randVector = BABYLON.Vector3.Zero();
  32363. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32364. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32365. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32366. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32367. context.fillRect(x, y, 1, 1);
  32368. }
  32369. }
  32370. this._randomTexture.update(false);
  32371. };
  32372. return SSAORenderingPipeline;
  32373. })(BABYLON.PostProcessRenderPipeline);
  32374. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32375. })(BABYLON || (BABYLON = {}));
  32376. var BABYLON;
  32377. (function (BABYLON) {
  32378. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32379. var VolumetricLightScatteringPostProcess = (function (_super) {
  32380. __extends(VolumetricLightScatteringPostProcess, _super);
  32381. /**
  32382. * @constructor
  32383. * @param {string} name - The post-process name
  32384. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  32385. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32386. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32387. * @param {number} samples - The post-process quality, default 100
  32388. * @param {number} samplingMode - The post-process filtering mode
  32389. * @param {BABYLON.Engine} engine - The babylon engine
  32390. * @param {boolean} reusable - If the post-process is reusable
  32391. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32392. */
  32393. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32394. var _this = this;
  32395. if (samples === void 0) { samples = 100; }
  32396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32397. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32398. this._screenCoordinates = BABYLON.Vector2.Zero();
  32399. /**
  32400. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32401. * @type {boolean}
  32402. */
  32403. this.useCustomMeshPosition = false;
  32404. /**
  32405. * If the post-process should inverse the light scattering direction
  32406. * @type {boolean}
  32407. */
  32408. this.invert = true;
  32409. /**
  32410. * Set to true to use the diffuseColor instead of the diffuseTexture
  32411. * @type {boolean}
  32412. */
  32413. this.useDiffuseColor = false;
  32414. /**
  32415. * Array containing the excluded meshes not rendered in the internal pass
  32416. */
  32417. this.excludedMeshes = new Array();
  32418. /**
  32419. * Controls the overall intensity of the post-process
  32420. * @type {number}
  32421. */
  32422. this.exposure = 0.3;
  32423. /**
  32424. * Dissipates each sample's contribution in range [0, 1]
  32425. * @type {number}
  32426. */
  32427. this.decay = 0.96815;
  32428. /**
  32429. * Controls the overall intensity of each sample
  32430. * @type {number}
  32431. */
  32432. this.weight = 0.58767;
  32433. /**
  32434. * Controls the density of each sample
  32435. * @type {number}
  32436. */
  32437. this.density = 0.926;
  32438. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32439. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32440. // Configure mesh
  32441. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32442. // Configure
  32443. this._createPass(scene, ratio.passRatio || ratio);
  32444. this.onApply = function (effect) {
  32445. _this._updateMeshScreenCoordinates(scene);
  32446. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32447. effect.setFloat("exposure", _this.exposure);
  32448. effect.setFloat("decay", _this.decay);
  32449. effect.setFloat("weight", _this.weight);
  32450. effect.setFloat("density", _this.density);
  32451. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32452. };
  32453. }
  32454. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32455. var mesh = subMesh.getMesh();
  32456. var defines = [];
  32457. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32458. var material = subMesh.getMaterial();
  32459. var needUV = false;
  32460. // Render this.mesh as default
  32461. if (mesh === this.mesh) {
  32462. if (this.useDiffuseColor) {
  32463. defines.push("#define DIFFUSE_COLOR_RENDER");
  32464. }
  32465. else if (material) {
  32466. if (material.diffuseTexture !== undefined) {
  32467. defines.push("#define BASIC_RENDER");
  32468. }
  32469. else {
  32470. defines.push("#define DIFFUSE_COLOR_RENDER");
  32471. }
  32472. }
  32473. defines.push("#define NEED_UV");
  32474. needUV = true;
  32475. }
  32476. // Alpha test
  32477. if (material) {
  32478. if (material.needAlphaTesting()) {
  32479. defines.push("#define ALPHATEST");
  32480. }
  32481. if (material.opacityTexture !== undefined) {
  32482. defines.push("#define OPACITY");
  32483. if (material.opacityTexture.getAlphaFromRGB) {
  32484. defines.push("#define OPACITYRGB");
  32485. }
  32486. if (!needUV) {
  32487. defines.push("#define NEED_UV");
  32488. }
  32489. }
  32490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32491. attribs.push(BABYLON.VertexBuffer.UVKind);
  32492. defines.push("#define UV1");
  32493. }
  32494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32496. defines.push("#define UV2");
  32497. }
  32498. }
  32499. // Bones
  32500. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32503. defines.push("#define BONES");
  32504. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32505. }
  32506. // Instances
  32507. if (useInstances) {
  32508. defines.push("#define INSTANCES");
  32509. attribs.push("world0");
  32510. attribs.push("world1");
  32511. attribs.push("world2");
  32512. attribs.push("world3");
  32513. }
  32514. // Get correct effect
  32515. var join = defines.join("\n");
  32516. if (this._cachedDefines !== join) {
  32517. this._cachedDefines = join;
  32518. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32519. }
  32520. return this._volumetricLightScatteringPass.isReady();
  32521. };
  32522. /**
  32523. * Sets the new light position for light scattering effect
  32524. * @param {BABYLON.Vector3} The new custom light position
  32525. */
  32526. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32527. this._customMeshPosition = position;
  32528. };
  32529. /**
  32530. * Returns the light position for light scattering effect
  32531. * @return {BABYLON.Vector3} The custom light position
  32532. */
  32533. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32534. return this._customMeshPosition;
  32535. };
  32536. /**
  32537. * Disposes the internal assets and detaches the post-process from the camera
  32538. */
  32539. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32540. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32541. if (rttIndex !== -1) {
  32542. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32543. }
  32544. this._volumetricLightScatteringRTT.dispose();
  32545. _super.prototype.dispose.call(this, camera);
  32546. };
  32547. /**
  32548. * Returns the render target texture used by the post-process
  32549. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32550. */
  32551. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32552. return this._volumetricLightScatteringRTT;
  32553. };
  32554. // Private methods
  32555. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32556. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32557. return true;
  32558. }
  32559. return false;
  32560. };
  32561. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32562. var _this = this;
  32563. var engine = scene.getEngine();
  32564. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32565. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32566. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32567. this._volumetricLightScatteringRTT.renderList = null;
  32568. this._volumetricLightScatteringRTT.renderParticles = false;
  32569. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32570. // Custom render function for submeshes
  32571. var renderSubMesh = function (subMesh) {
  32572. var mesh = subMesh.getRenderingMesh();
  32573. if (_this._meshExcluded(mesh)) {
  32574. return;
  32575. }
  32576. var scene = mesh.getScene();
  32577. var engine = scene.getEngine();
  32578. // Culling
  32579. engine.setState(subMesh.getMaterial().backFaceCulling);
  32580. // Managing instances
  32581. var batch = mesh._getInstancesRenderList(subMesh._id);
  32582. if (batch.mustReturn) {
  32583. return;
  32584. }
  32585. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32586. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32587. engine.enableEffect(_this._volumetricLightScatteringPass);
  32588. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32589. var material = subMesh.getMaterial();
  32590. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32591. // Alpha test
  32592. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32593. var alphaTexture = material.getAlphaTestTexture();
  32594. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32595. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32596. }
  32597. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32598. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32599. if (alphaTexture) {
  32600. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32601. }
  32602. }
  32603. if (material.opacityTexture !== undefined) {
  32604. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32605. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32606. }
  32607. }
  32608. // Bones
  32609. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32610. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32611. }
  32612. // Draw
  32613. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32614. }
  32615. };
  32616. // Render target texture callbacks
  32617. var savedSceneClearColor;
  32618. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32619. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32620. savedSceneClearColor = scene.clearColor;
  32621. scene.clearColor = sceneClearColor;
  32622. };
  32623. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32624. scene.clearColor = savedSceneClearColor;
  32625. };
  32626. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32627. var engine = scene.getEngine();
  32628. var index;
  32629. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32630. renderSubMesh(opaqueSubMeshes.data[index]);
  32631. }
  32632. engine.setAlphaTesting(true);
  32633. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32634. renderSubMesh(alphaTestSubMeshes.data[index]);
  32635. }
  32636. engine.setAlphaTesting(false);
  32637. if (transparentSubMeshes.length) {
  32638. // Sort sub meshes
  32639. for (index = 0; index < transparentSubMeshes.length; index++) {
  32640. var submesh = transparentSubMeshes.data[index];
  32641. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32642. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32643. }
  32644. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32645. sortedArray.sort(function (a, b) {
  32646. // Alpha index first
  32647. if (a._alphaIndex > b._alphaIndex) {
  32648. return 1;
  32649. }
  32650. if (a._alphaIndex < b._alphaIndex) {
  32651. return -1;
  32652. }
  32653. // Then distance to camera
  32654. if (a._distanceToCamera < b._distanceToCamera) {
  32655. return 1;
  32656. }
  32657. if (a._distanceToCamera > b._distanceToCamera) {
  32658. return -1;
  32659. }
  32660. return 0;
  32661. });
  32662. // Render sub meshes
  32663. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32664. for (index = 0; index < sortedArray.length; index++) {
  32665. renderSubMesh(sortedArray[index]);
  32666. }
  32667. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32668. }
  32669. };
  32670. };
  32671. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32672. var transform = scene.getTransformMatrix();
  32673. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32674. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32675. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32676. if (this.invert)
  32677. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32678. };
  32679. // Static methods
  32680. /**
  32681. * Creates a default mesh for the Volumeric Light Scattering post-process
  32682. * @param {string} The mesh name
  32683. * @param {BABYLON.Scene} The scene where to create the mesh
  32684. * @return {BABYLON.Mesh} the default mesh
  32685. */
  32686. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32687. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32688. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32689. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32690. return mesh;
  32691. };
  32692. return VolumetricLightScatteringPostProcess;
  32693. })(BABYLON.PostProcess);
  32694. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32695. })(BABYLON || (BABYLON = {}));
  32696. var BABYLON;
  32697. (function (BABYLON) {
  32698. var LensRenderingPipeline = (function (_super) {
  32699. __extends(LensRenderingPipeline, _super);
  32700. /**
  32701. * @constructor
  32702. *
  32703. * Effect parameters are as follow:
  32704. * {
  32705. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32706. * edge_blur: number; // from 0 to x (1 for realism)
  32707. * distortion: number; // from 0 to x (1 for realism)
  32708. * grain_amount: number; // from 0 to 1
  32709. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32710. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32711. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32712. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32713. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32714. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32715. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32716. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32717. * }
  32718. * Note: if an effect parameter is unset, effect is disabled
  32719. *
  32720. * @param {string} name - The rendering pipeline name
  32721. * @param {object} parameters - An object containing all parameters (see above)
  32722. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32723. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  32724. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32725. */
  32726. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32727. var _this = this;
  32728. if (ratio === void 0) { ratio = 1.0; }
  32729. _super.call(this, scene.getEngine(), name);
  32730. // Lens effects can be of the following:
  32731. // - chromatic aberration (slight shift of RGB colors)
  32732. // - blur on the edge of the lens
  32733. // - lens distortion
  32734. // - depth-of-field blur & highlights enhancing
  32735. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32736. // - grain effect (noise or custom texture)
  32737. // Two additional texture samplers are needed:
  32738. // - depth map (for depth-of-field)
  32739. // - grain texture
  32740. /**
  32741. * The chromatic aberration PostProcess id in the pipeline
  32742. * @type {string}
  32743. */
  32744. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32745. /**
  32746. * The highlights enhancing PostProcess id in the pipeline
  32747. * @type {string}
  32748. */
  32749. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32750. /**
  32751. * The depth-of-field PostProcess id in the pipeline
  32752. * @type {string}
  32753. */
  32754. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32755. this._scene = scene;
  32756. // Fetch texture samplers
  32757. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32758. if (parameters.grain_texture) {
  32759. this._grainTexture = parameters.grain_texture;
  32760. }
  32761. else {
  32762. this._createGrainTexture();
  32763. }
  32764. // save parameters
  32765. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32766. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32767. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32768. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32769. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32770. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32771. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32772. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32773. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32774. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32775. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32776. // Create effects
  32777. this._createChromaticAberrationPostProcess(ratio);
  32778. this._createHighlightsPostProcess(ratio);
  32779. this._createDepthOfFieldPostProcess(ratio / 4);
  32780. // Set up pipeline
  32781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32782. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32784. if (this._highlightsGain == -1) {
  32785. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32786. }
  32787. // Finish
  32788. scene.postProcessRenderPipelineManager.addPipeline(this);
  32789. if (cameras) {
  32790. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32791. }
  32792. }
  32793. // public methods (self explanatory)
  32794. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32795. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32796. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32797. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32798. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32799. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32800. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32801. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32802. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32803. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32804. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32805. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32806. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32807. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32808. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32809. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32810. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32811. this._highlightsGain = amount;
  32812. };
  32813. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32814. if (this._highlightsGain == -1) {
  32815. this._highlightsGain = 1.0;
  32816. }
  32817. this._highlightsThreshold = amount;
  32818. };
  32819. LensRenderingPipeline.prototype.disableHighlights = function () {
  32820. this._highlightsGain = -1;
  32821. };
  32822. /**
  32823. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32824. */
  32825. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32826. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32827. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32828. this._chromaticAberrationPostProcess = undefined;
  32829. this._highlightsPostProcess = undefined;
  32830. this._depthOfFieldPostProcess = undefined;
  32831. this._grainTexture.dispose();
  32832. if (disableDepthRender)
  32833. this._scene.disableDepthRenderer();
  32834. };
  32835. // colors shifting and distortion
  32836. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32837. var _this = this;
  32838. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32839. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32840. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32841. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32842. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32843. };
  32844. };
  32845. // highlights enhancing
  32846. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32847. var _this = this;
  32848. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32849. this._highlightsPostProcess.onApply = function (effect) {
  32850. effect.setFloat('gain', _this._highlightsGain);
  32851. effect.setFloat('threshold', _this._highlightsThreshold);
  32852. effect.setBool('pentagon', _this._dofPentagon);
  32853. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32854. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32855. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32856. };
  32857. };
  32858. // colors shifting and distortion
  32859. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32860. var _this = this;
  32861. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32862. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32863. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32864. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32865. this._depthOfFieldPostProcess.onApply = function (effect) {
  32866. effect.setTexture("depthSampler", _this._depthTexture);
  32867. effect.setTexture("grainSampler", _this._grainTexture);
  32868. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  32869. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  32870. effect.setFloat('grain_amount', _this._grainAmount);
  32871. effect.setBool('blur_noise', _this._blurNoise);
  32872. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32873. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32874. effect.setFloat('distortion', _this._distortion);
  32875. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  32876. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  32877. effect.setFloat('aperture', _this._dofAperture);
  32878. effect.setFloat('darken', _this._dofDarken);
  32879. effect.setFloat('edge_blur', _this._edgeBlur);
  32880. effect.setBool('highlights', (_this._highlightsGain != -1));
  32881. effect.setFloat('near', _this._scene.activeCamera.minZ);
  32882. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  32883. };
  32884. };
  32885. // creates a black and white random noise texture, 512x512
  32886. LensRenderingPipeline.prototype._createGrainTexture = function () {
  32887. var size = 512;
  32888. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32889. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32890. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32891. var context = this._grainTexture.getContext();
  32892. var rand = function (min, max) {
  32893. return Math.random() * (max - min) + min;
  32894. };
  32895. var value;
  32896. for (var x = 0; x < size; x++) {
  32897. for (var y = 0; y < size; y++) {
  32898. value = Math.floor(rand(0.42, 0.58) * 255);
  32899. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  32900. context.fillRect(x, y, 1, 1);
  32901. }
  32902. }
  32903. this._grainTexture.update(false);
  32904. };
  32905. return LensRenderingPipeline;
  32906. })(BABYLON.PostProcessRenderPipeline);
  32907. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  32908. })(BABYLON || (BABYLON = {}));
  32909. //
  32910. // This post-process allows the modification of rendered colors by using
  32911. // a 'look-up table' (LUT). This effect is also called Color Grading.
  32912. //
  32913. // The object needs to be provided an url to a texture containing the color
  32914. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  32915. // Use an image editing software to tweak the LUT to match your needs.
  32916. //
  32917. // For an example of a color LUT, see here:
  32918. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  32919. // For explanations on color grading, see here:
  32920. // http://udn.epicgames.com/Three/ColorGrading.html
  32921. //
  32922. var BABYLON;
  32923. (function (BABYLON) {
  32924. var ColorCorrectionPostProcess = (function (_super) {
  32925. __extends(ColorCorrectionPostProcess, _super);
  32926. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  32927. var _this = this;
  32928. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  32929. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  32930. this._colorTableTexture.anisotropicFilteringLevel = 1;
  32931. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32932. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32933. this.onApply = function (effect) {
  32934. effect.setTexture("colorTable", _this._colorTableTexture);
  32935. };
  32936. }
  32937. return ColorCorrectionPostProcess;
  32938. })(BABYLON.PostProcess);
  32939. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  32940. })(BABYLON || (BABYLON = {}));
  32941. var BABYLON;
  32942. (function (BABYLON) {
  32943. var AnaglyphFreeCamera = (function (_super) {
  32944. __extends(AnaglyphFreeCamera, _super);
  32945. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  32946. _super.call(this, name, position, scene);
  32947. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32948. }
  32949. return AnaglyphFreeCamera;
  32950. })(BABYLON.FreeCamera);
  32951. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  32952. var AnaglyphArcRotateCamera = (function (_super) {
  32953. __extends(AnaglyphArcRotateCamera, _super);
  32954. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  32955. _super.call(this, name, alpha, beta, radius, target, scene);
  32956. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32957. }
  32958. return AnaglyphArcRotateCamera;
  32959. })(BABYLON.ArcRotateCamera);
  32960. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  32961. var AnaglyphGamepadCamera = (function (_super) {
  32962. __extends(AnaglyphGamepadCamera, _super);
  32963. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  32964. _super.call(this, name, position, scene);
  32965. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32966. }
  32967. return AnaglyphGamepadCamera;
  32968. })(BABYLON.GamepadCamera);
  32969. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  32970. var StereoscopicFreeCamera = (function (_super) {
  32971. __extends(StereoscopicFreeCamera, _super);
  32972. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32973. _super.call(this, name, position, scene);
  32974. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32975. }
  32976. return StereoscopicFreeCamera;
  32977. })(BABYLON.FreeCamera);
  32978. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  32979. var StereoscopicArcRotateCamera = (function (_super) {
  32980. __extends(StereoscopicArcRotateCamera, _super);
  32981. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  32982. _super.call(this, name, alpha, beta, radius, target, scene);
  32983. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32984. }
  32985. return StereoscopicArcRotateCamera;
  32986. })(BABYLON.ArcRotateCamera);
  32987. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  32988. var StereoscopicGamepadCamera = (function (_super) {
  32989. __extends(StereoscopicGamepadCamera, _super);
  32990. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32991. _super.call(this, name, position, scene);
  32992. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32993. }
  32994. return StereoscopicGamepadCamera;
  32995. })(BABYLON.GamepadCamera);
  32996. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  32997. })(BABYLON || (BABYLON = {}));
  32998. var BABYLON;
  32999. (function (BABYLON) {
  33000. var HDRRenderingPipeline = (function (_super) {
  33001. __extends(HDRRenderingPipeline, _super);
  33002. /**
  33003. * @constructor
  33004. * @param {string} name - The rendering pipeline name
  33005. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33006. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  33007. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33008. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33009. */
  33010. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33011. var _this = this;
  33012. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33013. _super.call(this, scene.getEngine(), name);
  33014. /**
  33015. * Public members
  33016. */
  33017. // Gaussian Blur
  33018. /**
  33019. * Gaussian blur coefficient
  33020. * @type {number}
  33021. */
  33022. this.gaussCoeff = 0.3;
  33023. /**
  33024. * Gaussian blur mean
  33025. * @type {number}
  33026. */
  33027. this.gaussMean = 1.0;
  33028. /**
  33029. * Gaussian blur standard deviation
  33030. * @type {number}
  33031. */
  33032. this.gaussStandDev = 0.8;
  33033. // HDR
  33034. /**
  33035. * Exposure, controls the overall intensity of the pipeline
  33036. * @type {number}
  33037. */
  33038. this.exposure = 1.0;
  33039. /**
  33040. * Minimum luminance that the post-process can output. Luminance is >= 0
  33041. * @type {number}
  33042. */
  33043. this.minimumLuminance = 1.0;
  33044. /**
  33045. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33046. * @type {number}
  33047. */
  33048. this.maximumLuminance = 1e20;
  33049. /**
  33050. * Increase rate for luminance: eye adaptation speed to dark
  33051. * @type {number}
  33052. */
  33053. this.luminanceIncreaserate = 0.5;
  33054. /**
  33055. * Decrease rate for luminance: eye adaptation speed to bright
  33056. * @type {number}
  33057. */
  33058. this.luminanceDecreaseRate = 0.5;
  33059. // Bright pass
  33060. /**
  33061. * Minimum luminance needed to compute HDR
  33062. * @type {number}
  33063. */
  33064. this.brightThreshold = 0.8;
  33065. this._needUpdate = true;
  33066. this._scene = scene;
  33067. // Bright pass
  33068. this._createBrightPassPostProcess(scene, ratio);
  33069. // Down sample X4
  33070. this._createDownSampleX4PostProcess(scene, ratio);
  33071. // Create gaussian blur post-processes
  33072. this._createGaussianBlurPostProcess(scene, ratio);
  33073. // Texture adder
  33074. this._createTextureAdderPostProcess(scene, ratio);
  33075. // Luminance generator
  33076. this._createLuminanceGeneratorPostProcess(scene);
  33077. // HDR
  33078. this._createHDRPostProcess(scene, ratio);
  33079. // Pass postprocess
  33080. if (originalPostProcess === null) {
  33081. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33082. }
  33083. else {
  33084. this._originalPostProcess = originalPostProcess;
  33085. }
  33086. // Configure pipeline
  33087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33089. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33091. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33092. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33093. var addDownSamplerPostProcess = function (id) {
  33094. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33095. };
  33096. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33097. addDownSamplerPostProcess(i);
  33098. }
  33099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33100. // Finish
  33101. scene.postProcessRenderPipelineManager.addPipeline(this);
  33102. if (cameras !== null) {
  33103. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33104. }
  33105. this.update();
  33106. }
  33107. /**
  33108. * Tells the pipeline to update its post-processes
  33109. */
  33110. HDRRenderingPipeline.prototype.update = function () {
  33111. this._needUpdate = true;
  33112. };
  33113. /**
  33114. * Returns the current calculated luminance
  33115. */
  33116. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33117. return this._hdrCurrentLuminance;
  33118. };
  33119. /**
  33120. * Returns the currently drawn luminance
  33121. */
  33122. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33123. return this._hdrOutputLuminance;
  33124. };
  33125. /**
  33126. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33127. */
  33128. HDRRenderingPipeline.prototype.dispose = function () {
  33129. this._originalPostProcess = undefined;
  33130. this._brightPassPostProcess = undefined;
  33131. this._downSampleX4PostProcess = undefined;
  33132. this._guassianBlurHPostProcess = undefined;
  33133. this._guassianBlurVPostProcess = undefined;
  33134. this._textureAdderPostProcess = undefined;
  33135. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33136. this._downSamplePostProcesses[i] = undefined;
  33137. }
  33138. this._hdrPostProcess = undefined;
  33139. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33140. };
  33141. /**
  33142. * Creates the HDR post-process and computes the luminance adaptation
  33143. */
  33144. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33145. var _this = this;
  33146. var hdrLastLuminance = 0.0;
  33147. this._hdrOutputLuminance = -1.0;
  33148. this._hdrCurrentLuminance = 1.0;
  33149. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33150. this._hdrPostProcess.onApply = function (effect) {
  33151. if (_this._hdrOutputLuminance < 0.0) {
  33152. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33153. }
  33154. else {
  33155. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33156. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33157. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33158. }
  33159. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33160. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33161. }
  33162. else {
  33163. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33164. }
  33165. }
  33166. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33167. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33168. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33169. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33170. effect.setFloat("exposure", _this.exposure);
  33171. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33172. _this._needUpdate = false;
  33173. };
  33174. };
  33175. /**
  33176. * Texture Adder post-process
  33177. */
  33178. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33179. var _this = this;
  33180. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33181. this._textureAdderPostProcess.onApply = function (effect) {
  33182. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33183. };
  33184. };
  33185. /**
  33186. * Down sample X4 post-process
  33187. */
  33188. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33189. var _this = this;
  33190. var downSampleX4Offsets = new Array(32);
  33191. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33192. this._downSampleX4PostProcess.onApply = function (effect) {
  33193. if (_this._needUpdate) {
  33194. var id = 0;
  33195. for (var i = -2; i < 2; i++) {
  33196. for (var j = -2; j < 2; j++) {
  33197. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33198. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33199. id += 2;
  33200. }
  33201. }
  33202. }
  33203. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33204. };
  33205. };
  33206. /**
  33207. * Bright pass post-process
  33208. */
  33209. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33210. var _this = this;
  33211. var brightOffsets = new Array(8);
  33212. var brightPassCallback = function (effect) {
  33213. if (_this._needUpdate) {
  33214. var sU = (1.0 / _this._brightPassPostProcess.width);
  33215. var sV = (1.0 / _this._brightPassPostProcess.height);
  33216. brightOffsets[0] = -0.5 * sU;
  33217. brightOffsets[1] = 0.5 * sV;
  33218. brightOffsets[2] = 0.5 * sU;
  33219. brightOffsets[3] = 0.5 * sV;
  33220. brightOffsets[4] = -0.5 * sU;
  33221. brightOffsets[5] = -0.5 * sV;
  33222. brightOffsets[6] = 0.5 * sU;
  33223. brightOffsets[7] = -0.5 * sV;
  33224. }
  33225. effect.setArray2("dsOffsets", brightOffsets);
  33226. effect.setFloat("brightThreshold", _this.brightThreshold);
  33227. };
  33228. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33229. this._brightPassPostProcess.onApply = brightPassCallback;
  33230. };
  33231. /**
  33232. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33233. */
  33234. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33235. var _this = this;
  33236. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33237. var luminanceOffsets = new Array(8);
  33238. var downSampleOffsets = new Array(18);
  33239. var halfDestPixelSize;
  33240. this._downSamplePostProcesses = new Array(lumSteps);
  33241. // Utils for luminance
  33242. var luminanceUpdateSourceOffsets = function (width, height) {
  33243. var sU = (1.0 / width);
  33244. var sV = (1.0 / height);
  33245. luminanceOffsets[0] = -0.5 * sU;
  33246. luminanceOffsets[1] = 0.5 * sV;
  33247. luminanceOffsets[2] = 0.5 * sU;
  33248. luminanceOffsets[3] = 0.5 * sV;
  33249. luminanceOffsets[4] = -0.5 * sU;
  33250. luminanceOffsets[5] = -0.5 * sV;
  33251. luminanceOffsets[6] = 0.5 * sU;
  33252. luminanceOffsets[7] = -0.5 * sV;
  33253. };
  33254. var luminanceUpdateDestOffsets = function (width, height) {
  33255. var id = 0;
  33256. for (var x = -1; x < 2; x++) {
  33257. for (var y = -1; y < 2; y++) {
  33258. downSampleOffsets[id] = (x) / width;
  33259. downSampleOffsets[id + 1] = (y) / height;
  33260. id += 2;
  33261. }
  33262. }
  33263. };
  33264. // Luminance callback
  33265. var luminanceCallback = function (effect) {
  33266. if (_this._needUpdate) {
  33267. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33268. }
  33269. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33270. effect.setArray2("lumOffsets", luminanceOffsets);
  33271. };
  33272. // Down sample callbacks
  33273. var downSampleCallback = function (indice) {
  33274. var i = indice;
  33275. return function (effect) {
  33276. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33277. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33278. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33279. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33280. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33281. effect.setArray2("dsOffsets", downSampleOffsets);
  33282. };
  33283. };
  33284. var downSampleAfterRenderCallback = function (effect) {
  33285. // Unpack result
  33286. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33287. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  33288. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33289. };
  33290. // Create luminance post-process
  33291. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33292. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  33293. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33294. // Create down sample post-processes
  33295. for (var i = lumSteps - 2; i >= 0; i--) {
  33296. var length = Math.pow(3, i);
  33297. ratio = { width: length, height: length };
  33298. var defines = "#define DOWN_SAMPLE\n";
  33299. if (i === 0) {
  33300. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33301. }
  33302. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33303. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33304. if (i === 0) {
  33305. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33306. }
  33307. }
  33308. };
  33309. /**
  33310. * Gaussian blur post-processes. Horizontal and Vertical
  33311. */
  33312. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33313. var _this = this;
  33314. var blurOffsetsW = new Array(9);
  33315. var blurOffsetsH = new Array(9);
  33316. var blurWeights = new Array(9);
  33317. var uniforms = ["blurOffsets", "blurWeights"];
  33318. // Utils for gaussian blur
  33319. var calculateBlurOffsets = function (height) {
  33320. var lastOutputDimensions = {
  33321. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33322. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33323. };
  33324. for (var i = 0; i < 9; i++) {
  33325. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33326. if (height) {
  33327. blurOffsetsH[i] = value;
  33328. }
  33329. else {
  33330. blurOffsetsW[i] = value;
  33331. }
  33332. }
  33333. };
  33334. var calculateWeights = function () {
  33335. var x = 0.0;
  33336. for (var i = 0; i < 9; i++) {
  33337. x = (i - 4.0) / 4.0;
  33338. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  33339. }
  33340. };
  33341. // Callback
  33342. var gaussianBlurCallback = function (height) {
  33343. return function (effect) {
  33344. if (_this._needUpdate) {
  33345. calculateWeights();
  33346. calculateBlurOffsets(height);
  33347. }
  33348. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33349. effect.setArray("blurWeights", blurWeights);
  33350. };
  33351. };
  33352. // Create horizontal gaussian blur post-processes
  33353. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33354. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33355. // Create vertical gaussian blur post-process
  33356. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33357. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33358. };
  33359. // Luminance generator
  33360. HDRRenderingPipeline.LUM_STEPS = 6;
  33361. return HDRRenderingPipeline;
  33362. })(BABYLON.PostProcessRenderPipeline);
  33363. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33364. })(BABYLON || (BABYLON = {}));
  33365. var BABYLON;
  33366. (function (BABYLON) {
  33367. var FaceAdjacencies = (function () {
  33368. function FaceAdjacencies() {
  33369. this.edges = new Array();
  33370. this.edgesConnectedCount = 0;
  33371. }
  33372. return FaceAdjacencies;
  33373. })();
  33374. var EdgesRenderer = (function () {
  33375. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33376. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33377. if (epsilon === void 0) { epsilon = 0.95; }
  33378. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33379. this._linesPositions = new Array();
  33380. this._linesNormals = new Array();
  33381. this._linesIndices = new Array();
  33382. this._buffers = new Array();
  33383. this._checkVerticesInsteadOfIndices = false;
  33384. this._source = source;
  33385. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33386. this._epsilon = epsilon;
  33387. this._prepareRessources();
  33388. this._generateEdgesLines();
  33389. }
  33390. EdgesRenderer.prototype._prepareRessources = function () {
  33391. if (this._lineShader) {
  33392. return;
  33393. }
  33394. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33395. attributes: ["position", "normal"],
  33396. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33397. });
  33398. this._lineShader.disableDepthWrite = true;
  33399. this._lineShader.backFaceCulling = false;
  33400. };
  33401. EdgesRenderer.prototype.dispose = function () {
  33402. this._vb0.dispose();
  33403. this._vb1.dispose();
  33404. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33405. this._lineShader.dispose();
  33406. };
  33407. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33408. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33409. return 0;
  33410. }
  33411. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33412. return 1;
  33413. }
  33414. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33415. return 2;
  33416. }
  33417. return -1;
  33418. };
  33419. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33420. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33421. return 0;
  33422. }
  33423. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33424. return 1;
  33425. }
  33426. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33427. return 2;
  33428. }
  33429. return -1;
  33430. };
  33431. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33432. var needToCreateLine;
  33433. if (edge === undefined) {
  33434. needToCreateLine = true;
  33435. }
  33436. else {
  33437. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33438. needToCreateLine = dotProduct < this._epsilon;
  33439. }
  33440. if (needToCreateLine) {
  33441. var offset = this._linesPositions.length / 3;
  33442. var normal = p0.subtract(p1);
  33443. normal.normalize();
  33444. // Positions
  33445. this._linesPositions.push(p0.x);
  33446. this._linesPositions.push(p0.y);
  33447. this._linesPositions.push(p0.z);
  33448. this._linesPositions.push(p0.x);
  33449. this._linesPositions.push(p0.y);
  33450. this._linesPositions.push(p0.z);
  33451. this._linesPositions.push(p1.x);
  33452. this._linesPositions.push(p1.y);
  33453. this._linesPositions.push(p1.z);
  33454. this._linesPositions.push(p1.x);
  33455. this._linesPositions.push(p1.y);
  33456. this._linesPositions.push(p1.z);
  33457. // Normals
  33458. this._linesNormals.push(p1.x);
  33459. this._linesNormals.push(p1.y);
  33460. this._linesNormals.push(p1.z);
  33461. this._linesNormals.push(-1);
  33462. this._linesNormals.push(p1.x);
  33463. this._linesNormals.push(p1.y);
  33464. this._linesNormals.push(p1.z);
  33465. this._linesNormals.push(1);
  33466. this._linesNormals.push(p0.x);
  33467. this._linesNormals.push(p0.y);
  33468. this._linesNormals.push(p0.z);
  33469. this._linesNormals.push(-1);
  33470. this._linesNormals.push(p0.x);
  33471. this._linesNormals.push(p0.y);
  33472. this._linesNormals.push(p0.z);
  33473. this._linesNormals.push(1);
  33474. // Indices
  33475. this._linesIndices.push(offset);
  33476. this._linesIndices.push(offset + 1);
  33477. this._linesIndices.push(offset + 2);
  33478. this._linesIndices.push(offset);
  33479. this._linesIndices.push(offset + 2);
  33480. this._linesIndices.push(offset + 3);
  33481. }
  33482. };
  33483. EdgesRenderer.prototype._generateEdgesLines = function () {
  33484. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33485. var indices = this._source.getIndices();
  33486. // First let's find adjacencies
  33487. var adjacencies = new Array();
  33488. var faceNormals = new Array();
  33489. var index;
  33490. var faceAdjacencies;
  33491. // Prepare faces
  33492. for (index = 0; index < indices.length; index += 3) {
  33493. faceAdjacencies = new FaceAdjacencies();
  33494. var p0Index = indices[index];
  33495. var p1Index = indices[index + 1];
  33496. var p2Index = indices[index + 2];
  33497. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33498. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33499. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33500. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33501. faceNormal.normalize();
  33502. faceNormals.push(faceNormal);
  33503. adjacencies.push(faceAdjacencies);
  33504. }
  33505. // Scan
  33506. for (index = 0; index < adjacencies.length; index++) {
  33507. faceAdjacencies = adjacencies[index];
  33508. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33509. var otherFaceAdjacencies = adjacencies[otherIndex];
  33510. if (faceAdjacencies.edgesConnectedCount === 3) {
  33511. break;
  33512. }
  33513. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33514. continue;
  33515. }
  33516. var otherP0 = indices[otherIndex * 3];
  33517. var otherP1 = indices[otherIndex * 3 + 1];
  33518. var otherP2 = indices[otherIndex * 3 + 2];
  33519. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33520. var otherEdgeIndex;
  33521. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33522. continue;
  33523. }
  33524. switch (edgeIndex) {
  33525. case 0:
  33526. if (this._checkVerticesInsteadOfIndices) {
  33527. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33528. }
  33529. else {
  33530. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33531. }
  33532. break;
  33533. case 1:
  33534. if (this._checkVerticesInsteadOfIndices) {
  33535. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33536. }
  33537. else {
  33538. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33539. }
  33540. break;
  33541. case 2:
  33542. if (this._checkVerticesInsteadOfIndices) {
  33543. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33544. }
  33545. else {
  33546. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33547. }
  33548. break;
  33549. }
  33550. if (otherEdgeIndex === -1) {
  33551. continue;
  33552. }
  33553. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33554. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33555. faceAdjacencies.edgesConnectedCount++;
  33556. otherFaceAdjacencies.edgesConnectedCount++;
  33557. if (faceAdjacencies.edgesConnectedCount === 3) {
  33558. break;
  33559. }
  33560. }
  33561. }
  33562. }
  33563. // Create lines
  33564. for (index = 0; index < adjacencies.length; index++) {
  33565. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  33566. var current = adjacencies[index];
  33567. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33568. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33569. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33570. }
  33571. // Merge into a single mesh
  33572. var engine = this._source.getScene().getEngine();
  33573. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33574. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33575. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33576. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33577. this._ib = engine.createIndexBuffer(this._linesIndices);
  33578. this._indicesCount = this._linesIndices.length;
  33579. };
  33580. EdgesRenderer.prototype.render = function () {
  33581. if (!this._lineShader.isReady()) {
  33582. return;
  33583. }
  33584. var scene = this._source.getScene();
  33585. var engine = scene.getEngine();
  33586. this._lineShader._preBind();
  33587. // VBOs
  33588. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33589. scene.resetCachedMaterial();
  33590. this._lineShader.setColor4("color", this._source.edgesColor);
  33591. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33592. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33593. this._lineShader.bind(this._source.getWorldMatrix());
  33594. // Draw order
  33595. engine.draw(true, 0, this._indicesCount);
  33596. this._lineShader.unbind();
  33597. engine.setDepthWrite(true);
  33598. };
  33599. return EdgesRenderer;
  33600. })();
  33601. BABYLON.EdgesRenderer = EdgesRenderer;
  33602. })(BABYLON || (BABYLON = {}));
  33603. var BABYLON;
  33604. (function (BABYLON) {
  33605. (function (TonemappingOperator) {
  33606. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  33607. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  33608. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  33609. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  33610. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  33611. var TonemappingOperator = BABYLON.TonemappingOperator;
  33612. ;
  33613. var TonemapPostProcess = (function (_super) {
  33614. __extends(TonemapPostProcess, _super);
  33615. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  33616. var _this = this;
  33617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33618. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33619. this._operator = operator;
  33620. this._exposureAdjustment = exposureAdjustment;
  33621. var params = ["_ExposureAdjustment"];
  33622. var defines = "#define ";
  33623. if (operator === TonemappingOperator.Hable)
  33624. defines += "HABLE_TONEMAPPING";
  33625. else if (operator === TonemappingOperator.Reinhard)
  33626. defines += "REINHARD_TONEMAPPING";
  33627. else if (operator === TonemappingOperator.HejiDawson)
  33628. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  33629. else if (operator === TonemappingOperator.Photographic)
  33630. defines += "PHOTOGRAPHIC_TONEMAPPING";
  33631. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  33632. this.onApply = function (effect) {
  33633. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  33634. };
  33635. }
  33636. return TonemapPostProcess;
  33637. })(BABYLON.PostProcess);
  33638. BABYLON.TonemapPostProcess = TonemapPostProcess;
  33639. })(BABYLON || (BABYLON = {}));
  33640. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\n#ifdef ROUGHNESS\r\nuniform float roughness;\r\n#endif\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, glossiness);\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, glossiness);\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness *= specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\t\tbias = roughness;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  33641. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var u=i.TransformCoordinates(o,h),l=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(l,1)&&(u=u.scale(1/l)),u},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(o,n,r){var s,e,a,h=i.Normalize(o),u=i.Normalize(r),l=f.X,m=f.Y,x=0,y=0,c=0,p=0,z=0,M=0,w=0,d=-1,I=0,D=0;t.Tools.WithinEpsilon(u.z,0,t.Engine.Epsilon)?M=1:t.Tools.WithinEpsilon(u.x,0,t.Engine.Epsilon)?p=1:(w=u.z/u.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),e=new i(p,z,M),e.normalize(),a=i.Cross(u,e),a.normalize(),s=i.Cross(h,e),s.normalize(),i.Dot(u,s)<0&&(d=1),D=i.Dot(h,e),D=Math.min(1,Math.max(-1,D)),c=Math.acos(D)*d,i.Dot(e,l)<0&&(c=Math.PI+c,e=e.scaleInPlace(-1),a=a.scaleInPlace(-1),I++);var S,v;return p=0,z=0,M=0,d=-1,t.Tools.WithinEpsilon(u.z,0,t.Engine.Epsilon)?p=1:(w=e.z/e.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),S=new i(p,z,M),S.normalize(),v=i.Cross(S,e),v.normalize(),s=i.Cross(u,S),s.normalize(),i.Dot(e,s)<0&&(d=1),D=i.Dot(u,S),D=Math.min(1,Math.max(-1,D)),y=Math.acos(D)*d,i.Dot(v,m)<0&&(y=Math.PI+y,v=v.scaleInPlace(-1),S=S.scaleInPlace(-1),I++),d=-1,s=i.Cross(l,e),s.normalize(),i.Dot(s,m)<0&&(d=1),D=i.Dot(e,l),D=Math.min(1,Math.max(-1,D)),x=-Math.acos(D)*d,0>D&&2>I&&(x=Math.PI+x),new i(y,x,c)},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.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,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  33642. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33643. module.exports = BABYLON;
  33644. };