babylon.2.2.max.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680
  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 v = Vector3.Normalize(axis2);
  847. var w = Vector3.Normalize(axis3);
  848. // world axis
  849. var X = Axis.X;
  850. var Y = Axis.Y;
  851. var Z = Axis.Z;
  852. // equation unknowns and vars
  853. var yaw = 0.0;
  854. var pitch = 0.0;
  855. var roll = 0.0;
  856. var x = 0.0;
  857. var y = 0.0;
  858. var z = 0.0;
  859. var t = 0.0;
  860. var sign = -1.0;
  861. var pi = Math.PI;
  862. var nbRevert = 0;
  863. var cross;
  864. var dot = 0.0;
  865. // step 1 : rotation around w
  866. // Rv3(u) = u1, and u1 belongs to plane xOz
  867. // Rv3(w) = w1 = w invariant
  868. var u1;
  869. var v1;
  870. if (w.z == 0) {
  871. z = 1.0;
  872. }
  873. else if (w.x == 0) {
  874. x = 1.0;
  875. }
  876. else {
  877. t = w.z / w.x;
  878. x = -t * Math.sqrt(1 / (1 + t * t));
  879. z = Math.sqrt(1 / (1 + t * t));
  880. }
  881. u1 = new Vector3(x, y, z);
  882. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  883. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  884. if (Vector3.Dot(w, cross) < 0) {
  885. sign = 1;
  886. }
  887. dot = Vector3.Dot(u, u1);
  888. roll = Math.acos(dot) * sign;
  889. if (Vector3.Dot(u1, X) < 0) {
  890. roll = Math.PI + roll;
  891. u1 = u1.scaleInPlace(-1);
  892. v1 = v1.scaleInPlace(-1);
  893. nbRevert++;
  894. }
  895. // step 2 : rotate around u1
  896. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  897. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  898. var w2;
  899. var v2;
  900. x = 0.0;
  901. y = 0.0;
  902. z = 0.0;
  903. sign = -1;
  904. if (w.z == 0) {
  905. x = 1.0;
  906. }
  907. else {
  908. t = u1.z / u1.x;
  909. x = -t * Math.sqrt(1 / (1 + t * t));
  910. z = Math.sqrt(1 / (1 + t * t));
  911. }
  912. w2 = new Vector3(x, y, z);
  913. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  914. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  915. if (Vector3.Dot(u1, cross) < 0) {
  916. sign = 1;
  917. }
  918. dot = Vector3.Dot(w, w2);
  919. pitch = Math.acos(dot) * sign;
  920. if (Vector3.Dot(v2, Y) < 0) {
  921. pitch = Math.PI + pitch;
  922. v2 = v2.scaleInPlace(-1);
  923. w2 = w2.scaleInPlace(-1);
  924. nbRevert++;
  925. }
  926. // step 3 : rotate around v2
  927. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  928. sign = -1;
  929. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  930. if (Vector3.Dot(cross, Y) < 0) {
  931. sign = 1;
  932. }
  933. dot = Vector3.Dot(u1, X);
  934. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  935. if (dot < 0 && nbRevert < 2) {
  936. yaw = Math.PI + yaw;
  937. }
  938. return new Vector3(pitch, yaw, roll);
  939. };
  940. return Vector3;
  941. })();
  942. BABYLON.Vector3 = Vector3;
  943. //Vector4 class created for EulerAngle class conversion to Quaternion
  944. var Vector4 = (function () {
  945. function Vector4(x, y, z, w) {
  946. this.x = x;
  947. this.y = y;
  948. this.z = z;
  949. this.w = w;
  950. }
  951. Vector4.prototype.toString = function () {
  952. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  953. };
  954. // Operators
  955. Vector4.prototype.asArray = function () {
  956. var result = [];
  957. this.toArray(result, 0);
  958. return result;
  959. };
  960. Vector4.prototype.toArray = function (array, index) {
  961. if (index === undefined) {
  962. index = 0;
  963. }
  964. array[index] = this.x;
  965. array[index + 1] = this.y;
  966. array[index + 2] = this.z;
  967. array[index + 3] = this.w;
  968. return this;
  969. };
  970. Vector4.prototype.addInPlace = function (otherVector) {
  971. this.x += otherVector.x;
  972. this.y += otherVector.y;
  973. this.z += otherVector.z;
  974. this.w += otherVector.w;
  975. return this;
  976. };
  977. Vector4.prototype.add = function (otherVector) {
  978. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  979. };
  980. Vector4.prototype.addToRef = function (otherVector, result) {
  981. result.x = this.x + otherVector.x;
  982. result.y = this.y + otherVector.y;
  983. result.z = this.z + otherVector.z;
  984. result.w = this.w + otherVector.w;
  985. return this;
  986. };
  987. Vector4.prototype.subtractInPlace = function (otherVector) {
  988. this.x -= otherVector.x;
  989. this.y -= otherVector.y;
  990. this.z -= otherVector.z;
  991. this.w -= otherVector.w;
  992. return this;
  993. };
  994. Vector4.prototype.subtract = function (otherVector) {
  995. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  996. };
  997. Vector4.prototype.subtractToRef = function (otherVector, result) {
  998. result.x = this.x - otherVector.x;
  999. result.y = this.y - otherVector.y;
  1000. result.z = this.z - otherVector.z;
  1001. result.w = this.w - otherVector.w;
  1002. return this;
  1003. };
  1004. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1005. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1006. };
  1007. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = this.x - x;
  1009. result.y = this.y - y;
  1010. result.z = this.z - z;
  1011. result.w = this.w - w;
  1012. return this;
  1013. };
  1014. Vector4.prototype.negate = function () {
  1015. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1016. };
  1017. Vector4.prototype.scaleInPlace = function (scale) {
  1018. this.x *= scale;
  1019. this.y *= scale;
  1020. this.z *= scale;
  1021. this.w *= scale;
  1022. return this;
  1023. };
  1024. Vector4.prototype.scale = function (scale) {
  1025. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1026. };
  1027. Vector4.prototype.scaleToRef = function (scale, result) {
  1028. result.x = this.x * scale;
  1029. result.y = this.y * scale;
  1030. result.z = this.z * scale;
  1031. result.w = this.w * scale;
  1032. };
  1033. Vector4.prototype.equals = function (otherVector) {
  1034. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1035. };
  1036. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1037. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1038. return otherVector
  1039. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1040. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1041. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1042. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1043. };
  1044. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1045. return this.x === x && this.y === y && this.z === z && this.w === w;
  1046. };
  1047. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1048. this.x *= otherVector.x;
  1049. this.y *= otherVector.y;
  1050. this.z *= otherVector.z;
  1051. this.w *= otherVector.w;
  1052. return this;
  1053. };
  1054. Vector4.prototype.multiply = function (otherVector) {
  1055. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1056. };
  1057. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1058. result.x = this.x * otherVector.x;
  1059. result.y = this.y * otherVector.y;
  1060. result.z = this.z * otherVector.z;
  1061. result.w = this.w * otherVector.w;
  1062. return this;
  1063. };
  1064. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1065. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1066. };
  1067. Vector4.prototype.divide = function (otherVector) {
  1068. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1069. };
  1070. Vector4.prototype.divideToRef = function (otherVector, result) {
  1071. result.x = this.x / otherVector.x;
  1072. result.y = this.y / otherVector.y;
  1073. result.z = this.z / otherVector.z;
  1074. result.w = this.w / otherVector.w;
  1075. return this;
  1076. };
  1077. Vector4.prototype.MinimizeInPlace = function (other) {
  1078. if (other.x < this.x)
  1079. this.x = other.x;
  1080. if (other.y < this.y)
  1081. this.y = other.y;
  1082. if (other.z < this.z)
  1083. this.z = other.z;
  1084. if (other.w < this.w)
  1085. this.w = other.w;
  1086. return this;
  1087. };
  1088. Vector4.prototype.MaximizeInPlace = function (other) {
  1089. if (other.x > this.x)
  1090. this.x = other.x;
  1091. if (other.y > this.y)
  1092. this.y = other.y;
  1093. if (other.z > this.z)
  1094. this.z = other.z;
  1095. if (other.w > this.w)
  1096. this.w = other.w;
  1097. return this;
  1098. };
  1099. // Properties
  1100. Vector4.prototype.length = function () {
  1101. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1102. };
  1103. Vector4.prototype.lengthSquared = function () {
  1104. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1105. };
  1106. // Methods
  1107. Vector4.prototype.normalize = function () {
  1108. var len = this.length();
  1109. if (len === 0)
  1110. return this;
  1111. var num = 1.0 / len;
  1112. this.x *= num;
  1113. this.y *= num;
  1114. this.z *= num;
  1115. this.w *= num;
  1116. return this;
  1117. };
  1118. Vector4.prototype.clone = function () {
  1119. return new Vector4(this.x, this.y, this.z, this.w);
  1120. };
  1121. Vector4.prototype.copyFrom = function (source) {
  1122. this.x = source.x;
  1123. this.y = source.y;
  1124. this.z = source.z;
  1125. this.w = source.w;
  1126. return this;
  1127. };
  1128. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1129. this.x = x;
  1130. this.y = y;
  1131. this.z = z;
  1132. this.w = w;
  1133. return this;
  1134. };
  1135. // Statics
  1136. Vector4.FromArray = function (array, offset) {
  1137. if (!offset) {
  1138. offset = 0;
  1139. }
  1140. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1141. };
  1142. Vector4.FromArrayToRef = function (array, offset, result) {
  1143. result.x = array[offset];
  1144. result.y = array[offset + 1];
  1145. result.z = array[offset + 2];
  1146. result.w = array[offset + 3];
  1147. };
  1148. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1149. result.x = array[offset];
  1150. result.y = array[offset + 1];
  1151. result.z = array[offset + 2];
  1152. result.w = array[offset + 3];
  1153. };
  1154. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1155. result.x = x;
  1156. result.y = y;
  1157. result.z = z;
  1158. result.w = w;
  1159. };
  1160. Vector4.Zero = function () {
  1161. return new Vector4(0, 0, 0, 0);
  1162. };
  1163. Vector4.Normalize = function (vector) {
  1164. var result = Vector4.Zero();
  1165. Vector4.NormalizeToRef(vector, result);
  1166. return result;
  1167. };
  1168. Vector4.NormalizeToRef = function (vector, result) {
  1169. result.copyFrom(vector);
  1170. result.normalize();
  1171. };
  1172. Vector4.Minimize = function (left, right) {
  1173. var min = left.clone();
  1174. min.MinimizeInPlace(right);
  1175. return min;
  1176. };
  1177. Vector4.Maximize = function (left, right) {
  1178. var max = left.clone();
  1179. max.MaximizeInPlace(right);
  1180. return max;
  1181. };
  1182. Vector4.Distance = function (value1, value2) {
  1183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1184. };
  1185. Vector4.DistanceSquared = function (value1, value2) {
  1186. var x = value1.x - value2.x;
  1187. var y = value1.y - value2.y;
  1188. var z = value1.z - value2.z;
  1189. var w = value1.w - value2.w;
  1190. return (x * x) + (y * y) + (z * z) + (w * w);
  1191. };
  1192. Vector4.Center = function (value1, value2) {
  1193. var center = value1.add(value2);
  1194. center.scaleInPlace(0.5);
  1195. return center;
  1196. };
  1197. return Vector4;
  1198. })();
  1199. BABYLON.Vector4 = Vector4;
  1200. var Quaternion = (function () {
  1201. function Quaternion(x, y, z, w) {
  1202. if (x === void 0) { x = 0; }
  1203. if (y === void 0) { y = 0; }
  1204. if (z === void 0) { z = 0; }
  1205. if (w === void 0) { w = 1; }
  1206. this.x = x;
  1207. this.y = y;
  1208. this.z = z;
  1209. this.w = w;
  1210. }
  1211. Quaternion.prototype.toString = function () {
  1212. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1213. };
  1214. Quaternion.prototype.asArray = function () {
  1215. return [this.x, this.y, this.z, this.w];
  1216. };
  1217. Quaternion.prototype.equals = function (otherQuaternion) {
  1218. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1219. };
  1220. Quaternion.prototype.clone = function () {
  1221. return new Quaternion(this.x, this.y, this.z, this.w);
  1222. };
  1223. Quaternion.prototype.copyFrom = function (other) {
  1224. this.x = other.x;
  1225. this.y = other.y;
  1226. this.z = other.z;
  1227. this.w = other.w;
  1228. return this;
  1229. };
  1230. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1231. this.x = x;
  1232. this.y = y;
  1233. this.z = z;
  1234. this.w = w;
  1235. return this;
  1236. };
  1237. Quaternion.prototype.add = function (other) {
  1238. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1239. };
  1240. Quaternion.prototype.subtract = function (other) {
  1241. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1242. };
  1243. Quaternion.prototype.scale = function (value) {
  1244. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1245. };
  1246. Quaternion.prototype.multiply = function (q1) {
  1247. var result = new Quaternion(0, 0, 0, 1.0);
  1248. this.multiplyToRef(q1, result);
  1249. return result;
  1250. };
  1251. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1252. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1253. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1254. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1255. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1256. result.copyFromFloats(x, y, z, w);
  1257. return this;
  1258. };
  1259. Quaternion.prototype.length = function () {
  1260. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1261. };
  1262. Quaternion.prototype.normalize = function () {
  1263. var length = 1.0 / this.length();
  1264. this.x *= length;
  1265. this.y *= length;
  1266. this.z *= length;
  1267. this.w *= length;
  1268. return this;
  1269. };
  1270. Quaternion.prototype.toEulerAngles = function () {
  1271. var result = Vector3.Zero();
  1272. this.toEulerAnglesToRef(result);
  1273. return result;
  1274. };
  1275. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1276. //result is an EulerAngles in the in the z-x-z convention
  1277. var qx = this.x;
  1278. var qy = this.y;
  1279. var qz = this.z;
  1280. var qw = this.w;
  1281. var qxy = qx * qy;
  1282. var qxz = qx * qz;
  1283. var qwy = qw * qy;
  1284. var qwz = qw * qz;
  1285. var qwx = qw * qx;
  1286. var qyz = qy * qz;
  1287. var sqx = qx * qx;
  1288. var sqy = qy * qy;
  1289. var determinant = sqx + sqy;
  1290. if (determinant !== 0.000 && determinant !== 1.000) {
  1291. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1292. result.y = Math.acos(1 - 2 * determinant);
  1293. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1294. }
  1295. else {
  1296. if (determinant === 0.0) {
  1297. result.x = 0.0;
  1298. result.y = 0.0;
  1299. 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)
  1300. }
  1301. else {
  1302. 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)
  1303. result.y = Math.PI;
  1304. result.z = 0.0;
  1305. }
  1306. }
  1307. return this;
  1308. };
  1309. Quaternion.prototype.toRotationMatrix = function (result) {
  1310. var xx = this.x * this.x;
  1311. var yy = this.y * this.y;
  1312. var zz = this.z * this.z;
  1313. var xy = this.x * this.y;
  1314. var zw = this.z * this.w;
  1315. var zx = this.z * this.x;
  1316. var yw = this.y * this.w;
  1317. var yz = this.y * this.z;
  1318. var xw = this.x * this.w;
  1319. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1320. result.m[1] = 2.0 * (xy + zw);
  1321. result.m[2] = 2.0 * (zx - yw);
  1322. result.m[3] = 0;
  1323. result.m[4] = 2.0 * (xy - zw);
  1324. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1325. result.m[6] = 2.0 * (yz + xw);
  1326. result.m[7] = 0;
  1327. result.m[8] = 2.0 * (zx + yw);
  1328. result.m[9] = 2.0 * (yz - xw);
  1329. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1330. result.m[11] = 0;
  1331. result.m[12] = 0;
  1332. result.m[13] = 0;
  1333. result.m[14] = 0;
  1334. result.m[15] = 1.0;
  1335. return this;
  1336. };
  1337. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1338. Quaternion.FromRotationMatrixToRef(matrix, this);
  1339. return this;
  1340. };
  1341. // Statics
  1342. Quaternion.FromRotationMatrix = function (matrix) {
  1343. var result = new Quaternion();
  1344. Quaternion.FromRotationMatrixToRef(matrix, result);
  1345. return result;
  1346. };
  1347. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1348. var data = matrix.m;
  1349. var m11 = data[0], m12 = data[4], m13 = data[8];
  1350. var m21 = data[1], m22 = data[5], m23 = data[9];
  1351. var m31 = data[2], m32 = data[6], m33 = data[10];
  1352. var trace = m11 + m22 + m33;
  1353. var s;
  1354. if (trace > 0) {
  1355. s = 0.5 / Math.sqrt(trace + 1.0);
  1356. result.w = 0.25 / s;
  1357. result.x = (m32 - m23) * s;
  1358. result.y = (m13 - m31) * s;
  1359. result.z = (m21 - m12) * s;
  1360. }
  1361. else if (m11 > m22 && m11 > m33) {
  1362. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1363. result.w = (m32 - m23) / s;
  1364. result.x = 0.25 * s;
  1365. result.y = (m12 + m21) / s;
  1366. result.z = (m13 + m31) / s;
  1367. }
  1368. else if (m22 > m33) {
  1369. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1370. result.w = (m13 - m31) / s;
  1371. result.x = (m12 + m21) / s;
  1372. result.y = 0.25 * s;
  1373. result.z = (m23 + m32) / s;
  1374. }
  1375. else {
  1376. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1377. result.w = (m21 - m12) / s;
  1378. result.x = (m13 + m31) / s;
  1379. result.y = (m23 + m32) / s;
  1380. result.z = 0.25 * s;
  1381. }
  1382. };
  1383. Quaternion.Inverse = function (q) {
  1384. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1385. };
  1386. Quaternion.Identity = function () {
  1387. return new Quaternion(0, 0, 0, 1);
  1388. };
  1389. Quaternion.RotationAxis = function (axis, angle) {
  1390. var result = new Quaternion();
  1391. var sin = Math.sin(angle / 2);
  1392. result.w = Math.cos(angle / 2);
  1393. result.x = axis.x * sin;
  1394. result.y = axis.y * sin;
  1395. result.z = axis.z * sin;
  1396. return result;
  1397. };
  1398. Quaternion.FromArray = function (array, offset) {
  1399. if (!offset) {
  1400. offset = 0;
  1401. }
  1402. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1403. };
  1404. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1405. var result = new Quaternion();
  1406. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1407. return result;
  1408. };
  1409. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1410. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1411. var halfRoll = roll * 0.5;
  1412. var halfPitch = pitch * 0.5;
  1413. var halfYaw = yaw * 0.5;
  1414. var sinRoll = Math.sin(halfRoll);
  1415. var cosRoll = Math.cos(halfRoll);
  1416. var sinPitch = Math.sin(halfPitch);
  1417. var cosPitch = Math.cos(halfPitch);
  1418. var sinYaw = Math.sin(halfYaw);
  1419. var cosYaw = Math.cos(halfYaw);
  1420. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1421. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1422. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1423. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1424. };
  1425. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1426. var result = new Quaternion();
  1427. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1428. return result;
  1429. };
  1430. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1431. // Produces a quaternion from Euler angles in the z-x-z orientation
  1432. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1433. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1434. var halfBeta = beta * 0.5;
  1435. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1436. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1437. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1438. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1439. };
  1440. Quaternion.Slerp = function (left, right, amount) {
  1441. var num2;
  1442. var num3;
  1443. var num = amount;
  1444. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1445. var flag = false;
  1446. if (num4 < 0) {
  1447. flag = true;
  1448. num4 = -num4;
  1449. }
  1450. if (num4 > 0.999999) {
  1451. num3 = 1 - num;
  1452. num2 = flag ? -num : num;
  1453. }
  1454. else {
  1455. var num5 = Math.acos(num4);
  1456. var num6 = (1.0 / Math.sin(num5));
  1457. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1458. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1459. }
  1460. 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));
  1461. };
  1462. return Quaternion;
  1463. })();
  1464. BABYLON.Quaternion = Quaternion;
  1465. var Matrix = (function () {
  1466. function Matrix() {
  1467. this.m = new Float32Array(16);
  1468. }
  1469. // Properties
  1470. Matrix.prototype.isIdentity = function () {
  1471. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1472. return false;
  1473. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1474. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1475. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1476. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1477. return false;
  1478. return true;
  1479. };
  1480. Matrix.prototype.determinant = function () {
  1481. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1482. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1483. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1484. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1485. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1486. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1487. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1488. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1489. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1490. };
  1491. // Methods
  1492. Matrix.prototype.toArray = function () {
  1493. return this.m;
  1494. };
  1495. Matrix.prototype.asArray = function () {
  1496. return this.toArray();
  1497. };
  1498. Matrix.prototype.invert = function () {
  1499. this.invertToRef(this);
  1500. return this;
  1501. };
  1502. Matrix.prototype.reset = function () {
  1503. for (var index = 0; index < 16; index++) {
  1504. this.m[index] = 0;
  1505. }
  1506. return this;
  1507. };
  1508. Matrix.prototype.add = function (other) {
  1509. var result = new Matrix();
  1510. this.addToRef(other, result);
  1511. return result;
  1512. };
  1513. Matrix.prototype.addToRef = function (other, result) {
  1514. for (var index = 0; index < 16; index++) {
  1515. result.m[index] = this.m[index] + other.m[index];
  1516. }
  1517. return this;
  1518. };
  1519. Matrix.prototype.addToSelf = function (other) {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] += other.m[index];
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.invertToRef = function (other) {
  1526. var l1 = this.m[0];
  1527. var l2 = this.m[1];
  1528. var l3 = this.m[2];
  1529. var l4 = this.m[3];
  1530. var l5 = this.m[4];
  1531. var l6 = this.m[5];
  1532. var l7 = this.m[6];
  1533. var l8 = this.m[7];
  1534. var l9 = this.m[8];
  1535. var l10 = this.m[9];
  1536. var l11 = this.m[10];
  1537. var l12 = this.m[11];
  1538. var l13 = this.m[12];
  1539. var l14 = this.m[13];
  1540. var l15 = this.m[14];
  1541. var l16 = this.m[15];
  1542. var l17 = (l11 * l16) - (l12 * l15);
  1543. var l18 = (l10 * l16) - (l12 * l14);
  1544. var l19 = (l10 * l15) - (l11 * l14);
  1545. var l20 = (l9 * l16) - (l12 * l13);
  1546. var l21 = (l9 * l15) - (l11 * l13);
  1547. var l22 = (l9 * l14) - (l10 * l13);
  1548. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1549. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1550. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1551. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1552. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1553. var l28 = (l7 * l16) - (l8 * l15);
  1554. var l29 = (l6 * l16) - (l8 * l14);
  1555. var l30 = (l6 * l15) - (l7 * l14);
  1556. var l31 = (l5 * l16) - (l8 * l13);
  1557. var l32 = (l5 * l15) - (l7 * l13);
  1558. var l33 = (l5 * l14) - (l6 * l13);
  1559. var l34 = (l7 * l12) - (l8 * l11);
  1560. var l35 = (l6 * l12) - (l8 * l10);
  1561. var l36 = (l6 * l11) - (l7 * l10);
  1562. var l37 = (l5 * l12) - (l8 * l9);
  1563. var l38 = (l5 * l11) - (l7 * l9);
  1564. var l39 = (l5 * l10) - (l6 * l9);
  1565. other.m[0] = l23 * l27;
  1566. other.m[4] = l24 * l27;
  1567. other.m[8] = l25 * l27;
  1568. other.m[12] = l26 * l27;
  1569. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1570. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1571. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1572. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1573. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1574. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1575. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1576. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1577. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1578. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1579. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1580. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1581. return this;
  1582. };
  1583. Matrix.prototype.invertToRefSIMD = function (other) {
  1584. var src = this.m;
  1585. var dest = other.m;
  1586. var row0, row1, row2, row3;
  1587. var tmp1;
  1588. var minor0, minor1, minor2, minor3;
  1589. var det;
  1590. // Load the 4 rows
  1591. var src0 = SIMD.float32x4.load(src, 0);
  1592. var src1 = SIMD.float32x4.load(src, 4);
  1593. var src2 = SIMD.float32x4.load(src, 8);
  1594. var src3 = SIMD.float32x4.load(src, 12);
  1595. // Transpose the source matrix. Sort of. Not a true transpose operation
  1596. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1597. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1598. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1599. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1600. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1601. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1602. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1603. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1604. // This is a true transposition, but it will lead to an incorrect result
  1605. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1606. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1607. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1608. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1609. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1610. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1611. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1612. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1613. // ----
  1614. tmp1 = SIMD.float32x4.mul(row2, row3);
  1615. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1616. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1617. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1618. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1619. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1620. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1621. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1622. // ----
  1623. tmp1 = SIMD.float32x4.mul(row1, row2);
  1624. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1625. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1626. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1627. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1628. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1629. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1630. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1631. // ----
  1632. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1633. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1634. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1635. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1636. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1637. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1638. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1639. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1640. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1641. // ----
  1642. tmp1 = SIMD.float32x4.mul(row0, row1);
  1643. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1644. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1645. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1646. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1647. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1648. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1649. // ----
  1650. tmp1 = SIMD.float32x4.mul(row0, row3);
  1651. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1652. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1653. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1655. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1656. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1657. // ----
  1658. tmp1 = SIMD.float32x4.mul(row0, row2);
  1659. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1660. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1661. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1662. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1663. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1664. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1665. // Compute determinant
  1666. det = SIMD.float32x4.mul(row0, minor0);
  1667. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1668. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1669. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1670. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1671. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1672. // These shuffles aren't necessary if the faulty transposition is done
  1673. // up at the top of this function.
  1674. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1675. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1676. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1677. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1678. // Compute final values by multiplying with 1/det
  1679. minor0 = SIMD.float32x4.mul(det, minor0);
  1680. minor1 = SIMD.float32x4.mul(det, minor1);
  1681. minor2 = SIMD.float32x4.mul(det, minor2);
  1682. minor3 = SIMD.float32x4.mul(det, minor3);
  1683. SIMD.float32x4.store(dest, 0, minor0);
  1684. SIMD.float32x4.store(dest, 4, minor1);
  1685. SIMD.float32x4.store(dest, 8, minor2);
  1686. SIMD.float32x4.store(dest, 12, minor3);
  1687. return this;
  1688. };
  1689. Matrix.prototype.setTranslation = function (vector3) {
  1690. this.m[12] = vector3.x;
  1691. this.m[13] = vector3.y;
  1692. this.m[14] = vector3.z;
  1693. return this;
  1694. };
  1695. Matrix.prototype.multiply = function (other) {
  1696. var result = new Matrix();
  1697. this.multiplyToRef(other, result);
  1698. return result;
  1699. };
  1700. Matrix.prototype.copyFrom = function (other) {
  1701. for (var index = 0; index < 16; index++) {
  1702. this.m[index] = other.m[index];
  1703. }
  1704. return this;
  1705. };
  1706. Matrix.prototype.copyToArray = function (array, offset) {
  1707. if (offset === void 0) { offset = 0; }
  1708. for (var index = 0; index < 16; index++) {
  1709. array[offset + index] = this.m[index];
  1710. }
  1711. return this;
  1712. };
  1713. Matrix.prototype.multiplyToRef = function (other, result) {
  1714. this.multiplyToArray(other, result.m, 0);
  1715. return this;
  1716. };
  1717. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1718. var tm0 = this.m[0];
  1719. var tm1 = this.m[1];
  1720. var tm2 = this.m[2];
  1721. var tm3 = this.m[3];
  1722. var tm4 = this.m[4];
  1723. var tm5 = this.m[5];
  1724. var tm6 = this.m[6];
  1725. var tm7 = this.m[7];
  1726. var tm8 = this.m[8];
  1727. var tm9 = this.m[9];
  1728. var tm10 = this.m[10];
  1729. var tm11 = this.m[11];
  1730. var tm12 = this.m[12];
  1731. var tm13 = this.m[13];
  1732. var tm14 = this.m[14];
  1733. var tm15 = this.m[15];
  1734. var om0 = other.m[0];
  1735. var om1 = other.m[1];
  1736. var om2 = other.m[2];
  1737. var om3 = other.m[3];
  1738. var om4 = other.m[4];
  1739. var om5 = other.m[5];
  1740. var om6 = other.m[6];
  1741. var om7 = other.m[7];
  1742. var om8 = other.m[8];
  1743. var om9 = other.m[9];
  1744. var om10 = other.m[10];
  1745. var om11 = other.m[11];
  1746. var om12 = other.m[12];
  1747. var om13 = other.m[13];
  1748. var om14 = other.m[14];
  1749. var om15 = other.m[15];
  1750. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1751. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1752. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1753. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1754. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1755. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1756. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1757. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1758. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1759. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1760. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1761. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1762. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1763. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1764. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1765. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1766. return this;
  1767. };
  1768. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1769. if (offset === void 0) { offset = 0; }
  1770. var tm = this.m;
  1771. var om = other.m;
  1772. var om0 = SIMD.float32x4.load(om, 0);
  1773. var om1 = SIMD.float32x4.load(om, 4);
  1774. var om2 = SIMD.float32x4.load(om, 8);
  1775. var om3 = SIMD.float32x4.load(om, 12);
  1776. var tm0 = SIMD.float32x4.load(tm, 0);
  1777. 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)))));
  1778. var tm1 = SIMD.float32x4.load(tm, 4);
  1779. 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)))));
  1780. var tm2 = SIMD.float32x4.load(tm, 8);
  1781. 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)))));
  1782. var tm3 = SIMD.float32x4.load(tm, 12);
  1783. 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)))));
  1784. };
  1785. Matrix.prototype.equals = function (value) {
  1786. return value &&
  1787. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1788. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1789. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1790. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1791. };
  1792. Matrix.prototype.clone = function () {
  1793. 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]);
  1794. };
  1795. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1796. translation.x = this.m[12];
  1797. translation.y = this.m[13];
  1798. translation.z = this.m[14];
  1799. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1800. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1801. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1802. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1803. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1804. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1805. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1806. rotation.x = 0;
  1807. rotation.y = 0;
  1808. rotation.z = 0;
  1809. rotation.w = 1;
  1810. return false;
  1811. }
  1812. 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);
  1813. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1814. return true;
  1815. };
  1816. // Statics
  1817. Matrix.FromArray = function (array, offset) {
  1818. var result = new Matrix();
  1819. if (!offset) {
  1820. offset = 0;
  1821. }
  1822. Matrix.FromArrayToRef(array, offset, result);
  1823. return result;
  1824. };
  1825. Matrix.FromArrayToRef = function (array, offset, result) {
  1826. for (var index = 0; index < 16; index++) {
  1827. result.m[index] = array[index + offset];
  1828. }
  1829. };
  1830. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1831. for (var index = 0; index < 16; index++) {
  1832. result.m[index] = array[index + offset] * scale;
  1833. }
  1834. };
  1835. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1836. result.m[0] = initialM11;
  1837. result.m[1] = initialM12;
  1838. result.m[2] = initialM13;
  1839. result.m[3] = initialM14;
  1840. result.m[4] = initialM21;
  1841. result.m[5] = initialM22;
  1842. result.m[6] = initialM23;
  1843. result.m[7] = initialM24;
  1844. result.m[8] = initialM31;
  1845. result.m[9] = initialM32;
  1846. result.m[10] = initialM33;
  1847. result.m[11] = initialM34;
  1848. result.m[12] = initialM41;
  1849. result.m[13] = initialM42;
  1850. result.m[14] = initialM43;
  1851. result.m[15] = initialM44;
  1852. };
  1853. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1854. var result = new Matrix();
  1855. result.m[0] = initialM11;
  1856. result.m[1] = initialM12;
  1857. result.m[2] = initialM13;
  1858. result.m[3] = initialM14;
  1859. result.m[4] = initialM21;
  1860. result.m[5] = initialM22;
  1861. result.m[6] = initialM23;
  1862. result.m[7] = initialM24;
  1863. result.m[8] = initialM31;
  1864. result.m[9] = initialM32;
  1865. result.m[10] = initialM33;
  1866. result.m[11] = initialM34;
  1867. result.m[12] = initialM41;
  1868. result.m[13] = initialM42;
  1869. result.m[14] = initialM43;
  1870. result.m[15] = initialM44;
  1871. return result;
  1872. };
  1873. Matrix.Compose = function (scale, rotation, translation) {
  1874. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1875. var rotationMatrix = Matrix.Identity();
  1876. rotation.toRotationMatrix(rotationMatrix);
  1877. result = result.multiply(rotationMatrix);
  1878. result.setTranslation(translation);
  1879. return result;
  1880. };
  1881. Matrix.Identity = function () {
  1882. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1883. };
  1884. Matrix.IdentityToRef = function (result) {
  1885. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1886. };
  1887. Matrix.Zero = function () {
  1888. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1889. };
  1890. Matrix.RotationX = function (angle) {
  1891. var result = new Matrix();
  1892. Matrix.RotationXToRef(angle, result);
  1893. return result;
  1894. };
  1895. Matrix.Invert = function (source) {
  1896. var result = new Matrix();
  1897. source.invertToRef(result);
  1898. return result;
  1899. };
  1900. Matrix.RotationXToRef = function (angle, result) {
  1901. var s = Math.sin(angle);
  1902. var c = Math.cos(angle);
  1903. result.m[0] = 1.0;
  1904. result.m[15] = 1.0;
  1905. result.m[5] = c;
  1906. result.m[10] = c;
  1907. result.m[9] = -s;
  1908. result.m[6] = s;
  1909. result.m[1] = 0;
  1910. result.m[2] = 0;
  1911. result.m[3] = 0;
  1912. result.m[4] = 0;
  1913. result.m[7] = 0;
  1914. result.m[8] = 0;
  1915. result.m[11] = 0;
  1916. result.m[12] = 0;
  1917. result.m[13] = 0;
  1918. result.m[14] = 0;
  1919. };
  1920. Matrix.RotationY = function (angle) {
  1921. var result = new Matrix();
  1922. Matrix.RotationYToRef(angle, result);
  1923. return result;
  1924. };
  1925. Matrix.RotationYToRef = function (angle, result) {
  1926. var s = Math.sin(angle);
  1927. var c = Math.cos(angle);
  1928. result.m[5] = 1.0;
  1929. result.m[15] = 1.0;
  1930. result.m[0] = c;
  1931. result.m[2] = -s;
  1932. result.m[8] = s;
  1933. result.m[10] = c;
  1934. result.m[1] = 0;
  1935. result.m[3] = 0;
  1936. result.m[4] = 0;
  1937. result.m[6] = 0;
  1938. result.m[7] = 0;
  1939. result.m[9] = 0;
  1940. result.m[11] = 0;
  1941. result.m[12] = 0;
  1942. result.m[13] = 0;
  1943. result.m[14] = 0;
  1944. };
  1945. Matrix.RotationZ = function (angle) {
  1946. var result = new Matrix();
  1947. Matrix.RotationZToRef(angle, result);
  1948. return result;
  1949. };
  1950. Matrix.RotationZToRef = function (angle, result) {
  1951. var s = Math.sin(angle);
  1952. var c = Math.cos(angle);
  1953. result.m[10] = 1.0;
  1954. result.m[15] = 1.0;
  1955. result.m[0] = c;
  1956. result.m[1] = s;
  1957. result.m[4] = -s;
  1958. result.m[5] = c;
  1959. result.m[2] = 0;
  1960. result.m[3] = 0;
  1961. result.m[6] = 0;
  1962. result.m[7] = 0;
  1963. result.m[8] = 0;
  1964. result.m[9] = 0;
  1965. result.m[11] = 0;
  1966. result.m[12] = 0;
  1967. result.m[13] = 0;
  1968. result.m[14] = 0;
  1969. };
  1970. Matrix.RotationAxis = function (axis, angle) {
  1971. var s = Math.sin(-angle);
  1972. var c = Math.cos(-angle);
  1973. var c1 = 1 - c;
  1974. axis.normalize();
  1975. var result = Matrix.Zero();
  1976. result.m[0] = (axis.x * axis.x) * c1 + c;
  1977. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1978. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1979. result.m[3] = 0.0;
  1980. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1981. result.m[5] = (axis.y * axis.y) * c1 + c;
  1982. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1983. result.m[7] = 0.0;
  1984. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1985. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1986. result.m[10] = (axis.z * axis.z) * c1 + c;
  1987. result.m[11] = 0.0;
  1988. result.m[15] = 1.0;
  1989. return result;
  1990. };
  1991. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1992. var result = new Matrix();
  1993. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1994. return result;
  1995. };
  1996. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1997. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1998. this._tempQuaternion.toRotationMatrix(result);
  1999. };
  2000. Matrix.Scaling = function (x, y, z) {
  2001. var result = Matrix.Zero();
  2002. Matrix.ScalingToRef(x, y, z, result);
  2003. return result;
  2004. };
  2005. Matrix.ScalingToRef = function (x, y, z, result) {
  2006. result.m[0] = x;
  2007. result.m[1] = 0;
  2008. result.m[2] = 0;
  2009. result.m[3] = 0;
  2010. result.m[4] = 0;
  2011. result.m[5] = y;
  2012. result.m[6] = 0;
  2013. result.m[7] = 0;
  2014. result.m[8] = 0;
  2015. result.m[9] = 0;
  2016. result.m[10] = z;
  2017. result.m[11] = 0;
  2018. result.m[12] = 0;
  2019. result.m[13] = 0;
  2020. result.m[14] = 0;
  2021. result.m[15] = 1.0;
  2022. };
  2023. Matrix.Translation = function (x, y, z) {
  2024. var result = Matrix.Identity();
  2025. Matrix.TranslationToRef(x, y, z, result);
  2026. return result;
  2027. };
  2028. Matrix.TranslationToRef = function (x, y, z, result) {
  2029. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2030. };
  2031. Matrix.LookAtLH = function (eye, target, up) {
  2032. var result = Matrix.Zero();
  2033. Matrix.LookAtLHToRef(eye, target, up, result);
  2034. return result;
  2035. };
  2036. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2037. // Z axis
  2038. target.subtractToRef(eye, this._zAxis);
  2039. this._zAxis.normalize();
  2040. // X axis
  2041. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2042. this._xAxis.normalize();
  2043. // Y axis
  2044. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2045. this._yAxis.normalize();
  2046. // Eye angles
  2047. var ex = -Vector3.Dot(this._xAxis, eye);
  2048. var ey = -Vector3.Dot(this._yAxis, eye);
  2049. var ez = -Vector3.Dot(this._zAxis, eye);
  2050. 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);
  2051. };
  2052. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2053. var out = result.m;
  2054. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2055. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2056. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2057. // cc.kmVec3Subtract(f, pCenter, pEye);
  2058. var f = SIMD.float32x4.sub(center, eye);
  2059. // cc.kmVec3Normalize(f, f);
  2060. var tmp = SIMD.float32x4.mul(f, f);
  2061. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2062. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2063. // cc.kmVec3Assign(up, pUp);
  2064. // cc.kmVec3Normalize(up, up);
  2065. tmp = SIMD.float32x4.mul(up, up);
  2066. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2067. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2068. // cc.kmVec3Cross(s, f, up);
  2069. 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)));
  2070. // cc.kmVec3Normalize(s, s);
  2071. tmp = SIMD.float32x4.mul(s, s);
  2072. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2073. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2074. // cc.kmVec3Cross(u, s, f);
  2075. 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)));
  2076. // cc.kmVec3Normalize(s, s);
  2077. tmp = SIMD.float32x4.mul(s, s);
  2078. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2079. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2080. var zero = SIMD.float32x4.splat(0.0);
  2081. s = SIMD.float32x4.neg(s);
  2082. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2083. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2084. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2085. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2086. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2087. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2088. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2089. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2090. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2091. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2092. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2093. var b3 = SIMD.float32x4.neg(eye);
  2094. b3 = SIMD.float32x4.withW(b3, 1.0);
  2095. 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)))));
  2096. 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)))));
  2097. 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)))));
  2098. 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)))));
  2099. };
  2100. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2101. var matrix = Matrix.Zero();
  2102. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2103. return matrix;
  2104. };
  2105. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2106. var hw = 2.0 / width;
  2107. var hh = 2.0 / height;
  2108. var id = 1.0 / (zfar - znear);
  2109. var nid = znear / (znear - zfar);
  2110. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2111. };
  2112. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2113. var matrix = Matrix.Zero();
  2114. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2115. return matrix;
  2116. };
  2117. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2118. result.m[0] = 2.0 / (right - left);
  2119. result.m[1] = result.m[2] = result.m[3] = 0;
  2120. result.m[5] = 2.0 / (top - bottom);
  2121. result.m[4] = result.m[6] = result.m[7] = 0;
  2122. result.m[10] = -1.0 / (znear - zfar);
  2123. result.m[8] = result.m[9] = result.m[11] = 0;
  2124. result.m[12] = (left + right) / (left - right);
  2125. result.m[13] = (top + bottom) / (bottom - top);
  2126. result.m[14] = znear / (znear - zfar);
  2127. result.m[15] = 1.0;
  2128. };
  2129. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2130. var matrix = Matrix.Zero();
  2131. matrix.m[0] = (2.0 * znear) / width;
  2132. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2133. matrix.m[5] = (2.0 * znear) / height;
  2134. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2135. matrix.m[10] = -zfar / (znear - zfar);
  2136. matrix.m[8] = matrix.m[9] = 0.0;
  2137. matrix.m[11] = 1.0;
  2138. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2139. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2140. return matrix;
  2141. };
  2142. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2143. var matrix = Matrix.Zero();
  2144. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2145. return matrix;
  2146. };
  2147. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2148. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2149. var tan = 1.0 / (Math.tan(fov * 0.5));
  2150. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2151. if (v_fixed) {
  2152. result.m[0] = tan / aspect;
  2153. }
  2154. else {
  2155. result.m[0] = tan;
  2156. }
  2157. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2158. if (v_fixed) {
  2159. result.m[5] = tan;
  2160. }
  2161. else {
  2162. result.m[5] = tan * aspect;
  2163. }
  2164. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2165. result.m[8] = result.m[9] = 0.0;
  2166. result.m[10] = -zfar / (znear - zfar);
  2167. result.m[11] = 1.0;
  2168. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2169. result.m[14] = (znear * zfar) / (znear - zfar);
  2170. };
  2171. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2172. var cw = viewport.width;
  2173. var ch = viewport.height;
  2174. var cx = viewport.x;
  2175. var cy = viewport.y;
  2176. 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);
  2177. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2178. };
  2179. Matrix.GetAsMatrix2x2 = function (matrix) {
  2180. return new Float32Array([
  2181. matrix.m[0], matrix.m[1],
  2182. matrix.m[4], matrix.m[5]
  2183. ]);
  2184. };
  2185. Matrix.GetAsMatrix3x3 = function (matrix) {
  2186. return new Float32Array([
  2187. matrix.m[0], matrix.m[1], matrix.m[2],
  2188. matrix.m[4], matrix.m[5], matrix.m[6],
  2189. matrix.m[8], matrix.m[9], matrix.m[10]
  2190. ]);
  2191. };
  2192. Matrix.Transpose = function (matrix) {
  2193. var result = new Matrix();
  2194. result.m[0] = matrix.m[0];
  2195. result.m[1] = matrix.m[4];
  2196. result.m[2] = matrix.m[8];
  2197. result.m[3] = matrix.m[12];
  2198. result.m[4] = matrix.m[1];
  2199. result.m[5] = matrix.m[5];
  2200. result.m[6] = matrix.m[9];
  2201. result.m[7] = matrix.m[13];
  2202. result.m[8] = matrix.m[2];
  2203. result.m[9] = matrix.m[6];
  2204. result.m[10] = matrix.m[10];
  2205. result.m[11] = matrix.m[14];
  2206. result.m[12] = matrix.m[3];
  2207. result.m[13] = matrix.m[7];
  2208. result.m[14] = matrix.m[11];
  2209. result.m[15] = matrix.m[15];
  2210. return result;
  2211. };
  2212. Matrix.Reflection = function (plane) {
  2213. var matrix = new Matrix();
  2214. Matrix.ReflectionToRef(plane, matrix);
  2215. return matrix;
  2216. };
  2217. Matrix.ReflectionToRef = function (plane, result) {
  2218. plane.normalize();
  2219. var x = plane.normal.x;
  2220. var y = plane.normal.y;
  2221. var z = plane.normal.z;
  2222. var temp = -2 * x;
  2223. var temp2 = -2 * y;
  2224. var temp3 = -2 * z;
  2225. result.m[0] = (temp * x) + 1;
  2226. result.m[1] = temp2 * x;
  2227. result.m[2] = temp3 * x;
  2228. result.m[3] = 0.0;
  2229. result.m[4] = temp * y;
  2230. result.m[5] = (temp2 * y) + 1;
  2231. result.m[6] = temp3 * y;
  2232. result.m[7] = 0.0;
  2233. result.m[8] = temp * z;
  2234. result.m[9] = temp2 * z;
  2235. result.m[10] = (temp3 * z) + 1;
  2236. result.m[11] = 0.0;
  2237. result.m[12] = temp * plane.d;
  2238. result.m[13] = temp2 * plane.d;
  2239. result.m[14] = temp3 * plane.d;
  2240. result.m[15] = 1.0;
  2241. };
  2242. Matrix._tempQuaternion = new Quaternion();
  2243. Matrix._xAxis = Vector3.Zero();
  2244. Matrix._yAxis = Vector3.Zero();
  2245. Matrix._zAxis = Vector3.Zero();
  2246. return Matrix;
  2247. })();
  2248. BABYLON.Matrix = Matrix;
  2249. var Plane = (function () {
  2250. function Plane(a, b, c, d) {
  2251. this.normal = new Vector3(a, b, c);
  2252. this.d = d;
  2253. }
  2254. Plane.prototype.asArray = function () {
  2255. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2256. };
  2257. // Methods
  2258. Plane.prototype.clone = function () {
  2259. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2260. };
  2261. Plane.prototype.normalize = function () {
  2262. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2263. var magnitude = 0;
  2264. if (norm !== 0) {
  2265. magnitude = 1.0 / norm;
  2266. }
  2267. this.normal.x *= magnitude;
  2268. this.normal.y *= magnitude;
  2269. this.normal.z *= magnitude;
  2270. this.d *= magnitude;
  2271. return this;
  2272. };
  2273. Plane.prototype.transform = function (transformation) {
  2274. var transposedMatrix = Matrix.Transpose(transformation);
  2275. var x = this.normal.x;
  2276. var y = this.normal.y;
  2277. var z = this.normal.z;
  2278. var d = this.d;
  2279. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2280. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2281. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2282. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2283. return new Plane(normalX, normalY, normalZ, finalD);
  2284. };
  2285. Plane.prototype.dotCoordinate = function (point) {
  2286. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2287. };
  2288. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2289. var x1 = point2.x - point1.x;
  2290. var y1 = point2.y - point1.y;
  2291. var z1 = point2.z - point1.z;
  2292. var x2 = point3.x - point1.x;
  2293. var y2 = point3.y - point1.y;
  2294. var z2 = point3.z - point1.z;
  2295. var yz = (y1 * z2) - (z1 * y2);
  2296. var xz = (z1 * x2) - (x1 * z2);
  2297. var xy = (x1 * y2) - (y1 * x2);
  2298. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2299. var invPyth;
  2300. if (pyth !== 0) {
  2301. invPyth = 1.0 / pyth;
  2302. }
  2303. else {
  2304. invPyth = 0;
  2305. }
  2306. this.normal.x = yz * invPyth;
  2307. this.normal.y = xz * invPyth;
  2308. this.normal.z = xy * invPyth;
  2309. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2310. return this;
  2311. };
  2312. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2313. var dot = Vector3.Dot(this.normal, direction);
  2314. return (dot <= epsilon);
  2315. };
  2316. Plane.prototype.signedDistanceTo = function (point) {
  2317. return Vector3.Dot(point, this.normal) + this.d;
  2318. };
  2319. // Statics
  2320. Plane.FromArray = function (array) {
  2321. return new Plane(array[0], array[1], array[2], array[3]);
  2322. };
  2323. Plane.FromPoints = function (point1, point2, point3) {
  2324. var result = new Plane(0, 0, 0, 0);
  2325. result.copyFromPoints(point1, point2, point3);
  2326. return result;
  2327. };
  2328. Plane.FromPositionAndNormal = function (origin, normal) {
  2329. var result = new Plane(0, 0, 0, 0);
  2330. normal.normalize();
  2331. result.normal = normal;
  2332. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2333. return result;
  2334. };
  2335. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2336. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2337. return Vector3.Dot(point, normal) + d;
  2338. };
  2339. return Plane;
  2340. })();
  2341. BABYLON.Plane = Plane;
  2342. var Viewport = (function () {
  2343. function Viewport(x, y, width, height) {
  2344. this.x = x;
  2345. this.y = y;
  2346. this.width = width;
  2347. this.height = height;
  2348. }
  2349. Viewport.prototype.toGlobal = function (engine) {
  2350. var width = engine.getRenderWidth();
  2351. var height = engine.getRenderHeight();
  2352. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2353. };
  2354. return Viewport;
  2355. })();
  2356. BABYLON.Viewport = Viewport;
  2357. var Frustum = (function () {
  2358. function Frustum() {
  2359. }
  2360. Frustum.GetPlanes = function (transform) {
  2361. var frustumPlanes = [];
  2362. for (var index = 0; index < 6; index++) {
  2363. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2364. }
  2365. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2366. return frustumPlanes;
  2367. };
  2368. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2369. // Near
  2370. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2371. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2372. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2373. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2374. frustumPlanes[0].normalize();
  2375. // Far
  2376. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2377. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2378. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2379. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2380. frustumPlanes[1].normalize();
  2381. // Left
  2382. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2383. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2384. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2385. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2386. frustumPlanes[2].normalize();
  2387. // Right
  2388. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2389. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2390. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2391. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2392. frustumPlanes[3].normalize();
  2393. // Top
  2394. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2395. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2396. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2397. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2398. frustumPlanes[4].normalize();
  2399. // Bottom
  2400. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2401. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2402. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2403. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2404. frustumPlanes[5].normalize();
  2405. };
  2406. return Frustum;
  2407. })();
  2408. BABYLON.Frustum = Frustum;
  2409. var Ray = (function () {
  2410. function Ray(origin, direction, length) {
  2411. if (length === void 0) { length = Number.MAX_VALUE; }
  2412. this.origin = origin;
  2413. this.direction = direction;
  2414. this.length = length;
  2415. }
  2416. // Methods
  2417. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2418. var d = 0.0;
  2419. var maxValue = Number.MAX_VALUE;
  2420. if (Math.abs(this.direction.x) < 0.0000001) {
  2421. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2422. return false;
  2423. }
  2424. }
  2425. else {
  2426. var inv = 1.0 / this.direction.x;
  2427. var min = (minimum.x - this.origin.x) * inv;
  2428. var max = (maximum.x - this.origin.x) * inv;
  2429. if (max === -Infinity) {
  2430. max = Infinity;
  2431. }
  2432. if (min > max) {
  2433. var temp = min;
  2434. min = max;
  2435. max = temp;
  2436. }
  2437. d = Math.max(min, d);
  2438. maxValue = Math.min(max, maxValue);
  2439. if (d > maxValue) {
  2440. return false;
  2441. }
  2442. }
  2443. if (Math.abs(this.direction.y) < 0.0000001) {
  2444. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2445. return false;
  2446. }
  2447. }
  2448. else {
  2449. inv = 1.0 / this.direction.y;
  2450. min = (minimum.y - this.origin.y) * inv;
  2451. max = (maximum.y - this.origin.y) * inv;
  2452. if (max === -Infinity) {
  2453. max = Infinity;
  2454. }
  2455. if (min > max) {
  2456. temp = min;
  2457. min = max;
  2458. max = temp;
  2459. }
  2460. d = Math.max(min, d);
  2461. maxValue = Math.min(max, maxValue);
  2462. if (d > maxValue) {
  2463. return false;
  2464. }
  2465. }
  2466. if (Math.abs(this.direction.z) < 0.0000001) {
  2467. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2468. return false;
  2469. }
  2470. }
  2471. else {
  2472. inv = 1.0 / this.direction.z;
  2473. min = (minimum.z - this.origin.z) * inv;
  2474. max = (maximum.z - this.origin.z) * inv;
  2475. if (max === -Infinity) {
  2476. max = Infinity;
  2477. }
  2478. if (min > max) {
  2479. temp = min;
  2480. min = max;
  2481. max = temp;
  2482. }
  2483. d = Math.max(min, d);
  2484. maxValue = Math.min(max, maxValue);
  2485. if (d > maxValue) {
  2486. return false;
  2487. }
  2488. }
  2489. return true;
  2490. };
  2491. Ray.prototype.intersectsBox = function (box) {
  2492. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2493. };
  2494. Ray.prototype.intersectsSphere = function (sphere) {
  2495. var x = sphere.center.x - this.origin.x;
  2496. var y = sphere.center.y - this.origin.y;
  2497. var z = sphere.center.z - this.origin.z;
  2498. var pyth = (x * x) + (y * y) + (z * z);
  2499. var rr = sphere.radius * sphere.radius;
  2500. if (pyth <= rr) {
  2501. return true;
  2502. }
  2503. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2504. if (dot < 0.0) {
  2505. return false;
  2506. }
  2507. var temp = pyth - (dot * dot);
  2508. return temp <= rr;
  2509. };
  2510. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2511. if (!this._edge1) {
  2512. this._edge1 = Vector3.Zero();
  2513. this._edge2 = Vector3.Zero();
  2514. this._pvec = Vector3.Zero();
  2515. this._tvec = Vector3.Zero();
  2516. this._qvec = Vector3.Zero();
  2517. }
  2518. vertex1.subtractToRef(vertex0, this._edge1);
  2519. vertex2.subtractToRef(vertex0, this._edge2);
  2520. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2521. var det = Vector3.Dot(this._edge1, this._pvec);
  2522. if (det === 0) {
  2523. return null;
  2524. }
  2525. var invdet = 1 / det;
  2526. this.origin.subtractToRef(vertex0, this._tvec);
  2527. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2528. if (bu < 0 || bu > 1.0) {
  2529. return null;
  2530. }
  2531. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2532. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2533. if (bv < 0 || bu + bv > 1.0) {
  2534. return null;
  2535. }
  2536. //check if the distance is longer than the predefined length.
  2537. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2538. if (distance > this.length) {
  2539. return null;
  2540. }
  2541. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2542. };
  2543. // Statics
  2544. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2545. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2546. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2547. var direction = end.subtract(start);
  2548. direction.normalize();
  2549. return new Ray(start, direction);
  2550. };
  2551. /**
  2552. * 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
  2553. * transformed to the given world matrix.
  2554. * @param origin The origin point
  2555. * @param end The end point
  2556. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2557. */
  2558. Ray.CreateNewFromTo = function (origin, end, world) {
  2559. if (world === void 0) { world = Matrix.Identity(); }
  2560. var direction = end.subtract(origin);
  2561. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2562. direction.normalize();
  2563. return Ray.Transform(new Ray(origin, direction, length), world);
  2564. };
  2565. Ray.Transform = function (ray, matrix) {
  2566. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2567. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2568. return new Ray(newOrigin, newDirection, ray.length);
  2569. };
  2570. return Ray;
  2571. })();
  2572. BABYLON.Ray = Ray;
  2573. (function (Space) {
  2574. Space[Space["LOCAL"] = 0] = "LOCAL";
  2575. Space[Space["WORLD"] = 1] = "WORLD";
  2576. })(BABYLON.Space || (BABYLON.Space = {}));
  2577. var Space = BABYLON.Space;
  2578. var Axis = (function () {
  2579. function Axis() {
  2580. }
  2581. Axis.X = new Vector3(1, 0, 0);
  2582. Axis.Y = new Vector3(0, 1, 0);
  2583. Axis.Z = new Vector3(0, 0, 1);
  2584. return Axis;
  2585. })();
  2586. BABYLON.Axis = Axis;
  2587. ;
  2588. var BezierCurve = (function () {
  2589. function BezierCurve() {
  2590. }
  2591. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2592. // Extract X (which is equal to time here)
  2593. var f0 = 1 - 3 * x2 + 3 * x1;
  2594. var f1 = 3 * x2 - 6 * x1;
  2595. var f2 = 3 * x1;
  2596. var refinedT = t;
  2597. for (var i = 0; i < 5; i++) {
  2598. var refinedT2 = refinedT * refinedT;
  2599. var refinedT3 = refinedT2 * refinedT;
  2600. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2601. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2602. refinedT -= (x - t) * slope;
  2603. refinedT = Math.min(1, Math.max(0, refinedT));
  2604. }
  2605. // Resolve cubic bezier for the given x
  2606. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2607. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2608. Math.pow(refinedT, 3);
  2609. };
  2610. return BezierCurve;
  2611. })();
  2612. BABYLON.BezierCurve = BezierCurve;
  2613. (function (Orientation) {
  2614. Orientation[Orientation["CW"] = 0] = "CW";
  2615. Orientation[Orientation["CCW"] = 1] = "CCW";
  2616. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2617. var Orientation = BABYLON.Orientation;
  2618. var Angle = (function () {
  2619. function Angle(radians) {
  2620. var _this = this;
  2621. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2622. this.radians = function () { return _this._radians; };
  2623. this._radians = radians;
  2624. if (this._radians < 0)
  2625. this._radians += (2 * Math.PI);
  2626. }
  2627. Angle.BetweenTwoPoints = function (a, b) {
  2628. var delta = b.subtract(a);
  2629. var theta = Math.atan2(delta.y, delta.x);
  2630. return new Angle(theta);
  2631. };
  2632. Angle.FromRadians = function (radians) {
  2633. return new Angle(radians);
  2634. };
  2635. Angle.FromDegrees = function (degrees) {
  2636. return new Angle(degrees * Math.PI / 180);
  2637. };
  2638. return Angle;
  2639. })();
  2640. BABYLON.Angle = Angle;
  2641. var Arc2 = (function () {
  2642. function Arc2(startPoint, midPoint, endPoint) {
  2643. this.startPoint = startPoint;
  2644. this.midPoint = midPoint;
  2645. this.endPoint = endPoint;
  2646. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2647. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2648. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2649. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2650. 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);
  2651. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2652. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2653. var a1 = this.startAngle.degrees();
  2654. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2655. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2656. // angles correction
  2657. if (a2 - a1 > +180.0)
  2658. a2 -= 360.0;
  2659. if (a2 - a1 < -180.0)
  2660. a2 += 360.0;
  2661. if (a3 - a2 > +180.0)
  2662. a3 -= 360.0;
  2663. if (a3 - a2 < -180.0)
  2664. a3 += 360.0;
  2665. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2666. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2667. }
  2668. return Arc2;
  2669. })();
  2670. BABYLON.Arc2 = Arc2;
  2671. var PathCursor = (function () {
  2672. function PathCursor(path) {
  2673. this.path = path;
  2674. this._onchange = new Array();
  2675. this.value = 0;
  2676. this.animations = new Array();
  2677. }
  2678. PathCursor.prototype.getPoint = function () {
  2679. var point = this.path.getPointAtLengthPosition(this.value);
  2680. return new Vector3(point.x, 0, point.y);
  2681. };
  2682. PathCursor.prototype.moveAhead = function (step) {
  2683. if (step === void 0) { step = 0.002; }
  2684. this.move(step);
  2685. return this;
  2686. };
  2687. PathCursor.prototype.moveBack = function (step) {
  2688. if (step === void 0) { step = 0.002; }
  2689. this.move(-step);
  2690. return this;
  2691. };
  2692. PathCursor.prototype.move = function (step) {
  2693. if (Math.abs(step) > 1) {
  2694. throw "step size should be less than 1.";
  2695. }
  2696. this.value += step;
  2697. this.ensureLimits();
  2698. this.raiseOnChange();
  2699. return this;
  2700. };
  2701. PathCursor.prototype.ensureLimits = function () {
  2702. while (this.value > 1) {
  2703. this.value -= 1;
  2704. }
  2705. while (this.value < 0) {
  2706. this.value += 1;
  2707. }
  2708. return this;
  2709. };
  2710. // used by animation engine
  2711. PathCursor.prototype.markAsDirty = function (propertyName) {
  2712. this.ensureLimits();
  2713. this.raiseOnChange();
  2714. return this;
  2715. };
  2716. PathCursor.prototype.raiseOnChange = function () {
  2717. var _this = this;
  2718. this._onchange.forEach(function (f) { return f(_this); });
  2719. return this;
  2720. };
  2721. PathCursor.prototype.onchange = function (f) {
  2722. this._onchange.push(f);
  2723. return this;
  2724. };
  2725. return PathCursor;
  2726. })();
  2727. BABYLON.PathCursor = PathCursor;
  2728. var Path2 = (function () {
  2729. function Path2(x, y) {
  2730. this._points = new Array();
  2731. this._length = 0;
  2732. this.closed = false;
  2733. this._points.push(new Vector2(x, y));
  2734. }
  2735. Path2.prototype.addLineTo = function (x, y) {
  2736. if (closed) {
  2737. BABYLON.Tools.Error("cannot add lines to closed paths");
  2738. return this;
  2739. }
  2740. var newPoint = new Vector2(x, y);
  2741. var previousPoint = this._points[this._points.length - 1];
  2742. this._points.push(newPoint);
  2743. this._length += newPoint.subtract(previousPoint).length();
  2744. return this;
  2745. };
  2746. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2747. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2748. if (closed) {
  2749. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2750. return this;
  2751. }
  2752. var startPoint = this._points[this._points.length - 1];
  2753. var midPoint = new Vector2(midX, midY);
  2754. var endPoint = new Vector2(endX, endY);
  2755. var arc = new Arc2(startPoint, midPoint, endPoint);
  2756. var increment = arc.angle.radians() / numberOfSegments;
  2757. if (arc.orientation === Orientation.CW)
  2758. increment *= -1;
  2759. var currentAngle = arc.startAngle.radians() + increment;
  2760. for (var i = 0; i < numberOfSegments; i++) {
  2761. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2762. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2763. this.addLineTo(x, y);
  2764. currentAngle += increment;
  2765. }
  2766. return this;
  2767. };
  2768. Path2.prototype.close = function () {
  2769. this.closed = true;
  2770. return this;
  2771. };
  2772. Path2.prototype.length = function () {
  2773. var result = this._length;
  2774. if (!this.closed) {
  2775. var lastPoint = this._points[this._points.length - 1];
  2776. var firstPoint = this._points[0];
  2777. result += (firstPoint.subtract(lastPoint).length());
  2778. }
  2779. return result;
  2780. };
  2781. Path2.prototype.getPoints = function () {
  2782. return this._points;
  2783. };
  2784. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2785. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2786. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2787. return Vector2.Zero();
  2788. }
  2789. var lengthPosition = normalizedLengthPosition * this.length();
  2790. var previousOffset = 0;
  2791. for (var i = 0; i < this._points.length; i++) {
  2792. var j = (i + 1) % this._points.length;
  2793. var a = this._points[i];
  2794. var b = this._points[j];
  2795. var bToA = b.subtract(a);
  2796. var nextOffset = (bToA.length() + previousOffset);
  2797. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2798. var dir = bToA.normalize();
  2799. var localOffset = lengthPosition - previousOffset;
  2800. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2801. }
  2802. previousOffset = nextOffset;
  2803. }
  2804. BABYLON.Tools.Error("internal error");
  2805. return Vector2.Zero();
  2806. };
  2807. Path2.StartingAt = function (x, y) {
  2808. return new Path2(x, y);
  2809. };
  2810. return Path2;
  2811. })();
  2812. BABYLON.Path2 = Path2;
  2813. var Path3D = (function () {
  2814. function Path3D(path, firstNormal) {
  2815. this.path = path;
  2816. this._curve = new Array();
  2817. this._distances = new Array();
  2818. this._tangents = new Array();
  2819. this._normals = new Array();
  2820. this._binormals = new Array();
  2821. for (var p = 0; p < path.length; p++) {
  2822. this._curve[p] = path[p].clone(); // hard copy
  2823. }
  2824. this._compute(firstNormal);
  2825. }
  2826. Path3D.prototype.getCurve = function () {
  2827. return this._curve;
  2828. };
  2829. Path3D.prototype.getTangents = function () {
  2830. return this._tangents;
  2831. };
  2832. Path3D.prototype.getNormals = function () {
  2833. return this._normals;
  2834. };
  2835. Path3D.prototype.getBinormals = function () {
  2836. return this._binormals;
  2837. };
  2838. Path3D.prototype.getDistances = function () {
  2839. return this._distances;
  2840. };
  2841. Path3D.prototype.update = function (path, firstNormal) {
  2842. for (var p = 0; p < path.length; p++) {
  2843. this._curve[p].x = path[p].x;
  2844. this._curve[p].y = path[p].y;
  2845. this._curve[p].z = path[p].z;
  2846. }
  2847. this._compute(firstNormal);
  2848. return this;
  2849. };
  2850. // private function compute() : computes tangents, normals and binormals
  2851. Path3D.prototype._compute = function (firstNormal) {
  2852. var l = this._curve.length;
  2853. // first and last tangents
  2854. this._tangents[0] = this._getFirstNonNullVector(0);
  2855. this._tangents[0].normalize();
  2856. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2857. this._tangents[l - 1].normalize();
  2858. // normals and binormals at first point : arbitrary vector with _normalVector()
  2859. var tg0 = this._tangents[0];
  2860. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2861. this._normals[0] = pp0;
  2862. this._normals[0].normalize();
  2863. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2864. this._binormals[0].normalize();
  2865. this._distances[0] = 0;
  2866. // normals and binormals : next points
  2867. var prev; // previous vector (segment)
  2868. var cur; // current vector (segment)
  2869. var curTang; // current tangent
  2870. var prevNorm; // previous normal
  2871. var prevBinor; // previous binormal
  2872. for (var i = 1; i < l; i++) {
  2873. // tangents
  2874. prev = this._getLastNonNullVector(i);
  2875. if (i < l - 1) {
  2876. cur = this._getFirstNonNullVector(i);
  2877. this._tangents[i] = prev.add(cur);
  2878. this._tangents[i].normalize();
  2879. }
  2880. this._distances[i] = this._distances[i - 1] + prev.length();
  2881. // normals and binormals
  2882. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2883. curTang = this._tangents[i];
  2884. prevNorm = this._normals[i - 1];
  2885. prevBinor = this._binormals[i - 1];
  2886. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2887. this._normals[i].normalize();
  2888. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2889. this._binormals[i].normalize();
  2890. }
  2891. };
  2892. // private function getFirstNonNullVector(index)
  2893. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2894. Path3D.prototype._getFirstNonNullVector = function (index) {
  2895. var i = 1;
  2896. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2897. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2898. i++;
  2899. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2900. }
  2901. return nNVector;
  2902. };
  2903. // private function getLastNonNullVector(index)
  2904. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2905. Path3D.prototype._getLastNonNullVector = function (index) {
  2906. var i = 1;
  2907. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2908. while (nLVector.length() == 0 && index > i + 1) {
  2909. i++;
  2910. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2911. }
  2912. return nLVector;
  2913. };
  2914. // private function normalVector(v0, vt, va) :
  2915. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2916. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2917. Path3D.prototype._normalVector = function (v0, vt, va) {
  2918. var normal0;
  2919. if (va === undefined || va === null) {
  2920. var point;
  2921. if (vt.y !== 1) {
  2922. point = new Vector3(0, -1, 0);
  2923. }
  2924. else if (vt.x !== 1) {
  2925. point = new Vector3(1, 0, 0);
  2926. }
  2927. else if (vt.z !== 1) {
  2928. point = new Vector3(0, 0, 1);
  2929. }
  2930. normal0 = Vector3.Cross(vt, point);
  2931. }
  2932. else {
  2933. normal0 = Vector3.Cross(vt, va);
  2934. Vector3.CrossToRef(normal0, vt, normal0);
  2935. }
  2936. normal0.normalize();
  2937. return normal0;
  2938. };
  2939. return Path3D;
  2940. })();
  2941. BABYLON.Path3D = Path3D;
  2942. var Curve3 = (function () {
  2943. function Curve3(points) {
  2944. this._length = 0;
  2945. this._points = points;
  2946. this._length = this._computeLength(points);
  2947. }
  2948. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2949. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2950. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2951. var bez = new Array();
  2952. var equation = function (t, val0, val1, val2) {
  2953. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2954. return res;
  2955. };
  2956. for (var i = 0; i <= nbPoints; i++) {
  2957. 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)));
  2958. }
  2959. return new Curve3(bez);
  2960. };
  2961. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2962. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2963. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2964. var bez = new Array();
  2965. var equation = function (t, val0, val1, val2, val3) {
  2966. 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;
  2967. return res;
  2968. };
  2969. for (var i = 0; i <= nbPoints; i++) {
  2970. 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)));
  2971. }
  2972. return new Curve3(bez);
  2973. };
  2974. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2975. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2976. var hermite = new Array();
  2977. var step = 1 / nbPoints;
  2978. for (var i = 0; i <= nbPoints; i++) {
  2979. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2980. }
  2981. return new Curve3(hermite);
  2982. };
  2983. Curve3.prototype.getPoints = function () {
  2984. return this._points;
  2985. };
  2986. Curve3.prototype.length = function () {
  2987. return this._length;
  2988. };
  2989. Curve3.prototype.continue = function (curve) {
  2990. var lastPoint = this._points[this._points.length - 1];
  2991. var continuedPoints = this._points.slice();
  2992. var curvePoints = curve.getPoints();
  2993. for (var i = 1; i < curvePoints.length; i++) {
  2994. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2995. }
  2996. var continuedCurve = new Curve3(continuedPoints);
  2997. return continuedCurve;
  2998. };
  2999. Curve3.prototype._computeLength = function (path) {
  3000. var l = 0;
  3001. for (var i = 1; i < path.length; i++) {
  3002. l += (path[i].subtract(path[i - 1])).length();
  3003. }
  3004. return l;
  3005. };
  3006. return Curve3;
  3007. })();
  3008. BABYLON.Curve3 = Curve3;
  3009. // Vertex formats
  3010. var PositionNormalVertex = (function () {
  3011. function PositionNormalVertex(position, normal) {
  3012. if (position === void 0) { position = Vector3.Zero(); }
  3013. if (normal === void 0) { normal = Vector3.Up(); }
  3014. this.position = position;
  3015. this.normal = normal;
  3016. }
  3017. PositionNormalVertex.prototype.clone = function () {
  3018. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3019. };
  3020. return PositionNormalVertex;
  3021. })();
  3022. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3023. var PositionNormalTextureVertex = (function () {
  3024. function PositionNormalTextureVertex(position, normal, uv) {
  3025. if (position === void 0) { position = Vector3.Zero(); }
  3026. if (normal === void 0) { normal = Vector3.Up(); }
  3027. if (uv === void 0) { uv = Vector2.Zero(); }
  3028. this.position = position;
  3029. this.normal = normal;
  3030. this.uv = uv;
  3031. }
  3032. PositionNormalTextureVertex.prototype.clone = function () {
  3033. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3034. };
  3035. return PositionNormalTextureVertex;
  3036. })();
  3037. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3038. // SIMD
  3039. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3040. var previousInvertToRef = Matrix.prototype.invertToRef;
  3041. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3042. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3043. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3044. var SIMDHelper = (function () {
  3045. function SIMDHelper() {
  3046. }
  3047. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3048. get: function () {
  3049. return SIMDHelper._isEnabled;
  3050. },
  3051. enumerable: true,
  3052. configurable: true
  3053. });
  3054. SIMDHelper.DisableSIMD = function () {
  3055. // Replace functions
  3056. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3057. Matrix.prototype.invertToRef = previousInvertToRef;
  3058. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3059. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3060. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3061. SIMDHelper._isEnabled = false;
  3062. };
  3063. SIMDHelper.EnableSIMD = function () {
  3064. if (window.SIMD === undefined) {
  3065. return;
  3066. }
  3067. // Replace functions
  3068. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3069. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3070. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3071. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3072. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3073. Object.defineProperty(Vector3.prototype, "x", {
  3074. get: function () { return this._data[0]; },
  3075. set: function (value) {
  3076. if (!this._data) {
  3077. this._data = new Float32Array(3);
  3078. }
  3079. this._data[0] = value;
  3080. }
  3081. });
  3082. Object.defineProperty(Vector3.prototype, "y", {
  3083. get: function () { return this._data[1]; },
  3084. set: function (value) {
  3085. this._data[1] = value;
  3086. }
  3087. });
  3088. Object.defineProperty(Vector3.prototype, "z", {
  3089. get: function () { return this._data[2]; },
  3090. set: function (value) {
  3091. this._data[2] = value;
  3092. }
  3093. });
  3094. SIMDHelper._isEnabled = true;
  3095. };
  3096. SIMDHelper._isEnabled = false;
  3097. return SIMDHelper;
  3098. })();
  3099. BABYLON.SIMDHelper = SIMDHelper;
  3100. })(BABYLON || (BABYLON = {}));
  3101. var BABYLON;
  3102. (function (BABYLON) {
  3103. var Database = (function () {
  3104. function Database(urlToScene, callbackManifestChecked) {
  3105. // Handling various flavors of prefixed version of IndexedDB
  3106. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3107. this.callbackManifestChecked = callbackManifestChecked;
  3108. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3109. this.db = null;
  3110. this.enableSceneOffline = false;
  3111. this.enableTexturesOffline = false;
  3112. this.manifestVersionFound = 0;
  3113. this.mustUpdateRessources = false;
  3114. this.hasReachedQuota = false;
  3115. if (!Database.IDBStorageEnabled) {
  3116. this.callbackManifestChecked(true);
  3117. }
  3118. else {
  3119. this.checkManifestFile();
  3120. }
  3121. }
  3122. Database.prototype.checkManifestFile = function () {
  3123. var _this = this;
  3124. function noManifestFile() {
  3125. that.enableSceneOffline = false;
  3126. that.enableTexturesOffline = false;
  3127. that.callbackManifestChecked(false);
  3128. }
  3129. var that = this;
  3130. var manifestURL = this.currentSceneUrl + ".manifest";
  3131. var xhr = new XMLHttpRequest();
  3132. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3133. xhr.open("GET", manifestURLTimeStamped, true);
  3134. xhr.addEventListener("load", function () {
  3135. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3136. try {
  3137. var manifestFile = JSON.parse(xhr.response);
  3138. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3139. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3140. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3141. _this.manifestVersionFound = manifestFile.version;
  3142. }
  3143. if (_this.callbackManifestChecked) {
  3144. _this.callbackManifestChecked(true);
  3145. }
  3146. }
  3147. catch (ex) {
  3148. noManifestFile();
  3149. }
  3150. }
  3151. else {
  3152. noManifestFile();
  3153. }
  3154. }, false);
  3155. xhr.addEventListener("error", function (event) {
  3156. noManifestFile();
  3157. }, false);
  3158. try {
  3159. xhr.send();
  3160. }
  3161. catch (ex) {
  3162. BABYLON.Tools.Error("Error on XHR send request.");
  3163. that.callbackManifestChecked(false);
  3164. }
  3165. };
  3166. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3167. var _this = this;
  3168. function handleError() {
  3169. that.isSupported = false;
  3170. if (errorCallback)
  3171. errorCallback();
  3172. }
  3173. var that = this;
  3174. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3175. // Your browser doesn't support IndexedDB
  3176. this.isSupported = false;
  3177. if (errorCallback)
  3178. errorCallback();
  3179. }
  3180. else {
  3181. // If the DB hasn't been opened or created yet
  3182. if (!this.db) {
  3183. this.hasReachedQuota = false;
  3184. this.isSupported = true;
  3185. var request = this.idbFactory.open("babylonjs", 1);
  3186. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3187. request.onerror = function (event) {
  3188. handleError();
  3189. };
  3190. // executes when a version change transaction cannot complete due to other active transactions
  3191. request.onblocked = function (event) {
  3192. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3193. handleError();
  3194. };
  3195. // DB has been opened successfully
  3196. request.onsuccess = function (event) {
  3197. _this.db = request.result;
  3198. successCallback();
  3199. };
  3200. // Initialization of the DB. Creating Scenes & Textures stores
  3201. request.onupgradeneeded = function (event) {
  3202. _this.db = (event.target).result;
  3203. try {
  3204. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3205. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3206. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3207. }
  3208. catch (ex) {
  3209. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3210. handleError();
  3211. }
  3212. };
  3213. }
  3214. else {
  3215. if (successCallback)
  3216. successCallback();
  3217. }
  3218. }
  3219. };
  3220. Database.prototype.loadImageFromDB = function (url, image) {
  3221. var _this = this;
  3222. var completeURL = Database.ReturnFullUrlLocation(url);
  3223. var saveAndLoadImage = function () {
  3224. if (!_this.hasReachedQuota && _this.db !== null) {
  3225. // the texture is not yet in the DB, let's try to save it
  3226. _this._saveImageIntoDBAsync(completeURL, image);
  3227. }
  3228. else {
  3229. image.src = url;
  3230. }
  3231. };
  3232. if (!this.mustUpdateRessources) {
  3233. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3234. }
  3235. else {
  3236. saveAndLoadImage();
  3237. }
  3238. };
  3239. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3240. if (this.isSupported && this.db !== null) {
  3241. var texture;
  3242. var transaction = this.db.transaction(["textures"]);
  3243. transaction.onabort = function (event) {
  3244. image.src = url;
  3245. };
  3246. transaction.oncomplete = function (event) {
  3247. var blobTextureURL;
  3248. if (texture) {
  3249. var URL = window.URL || window.webkitURL;
  3250. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3251. image.onerror = function () {
  3252. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3253. image.src = url;
  3254. };
  3255. image.src = blobTextureURL;
  3256. }
  3257. else {
  3258. notInDBCallback();
  3259. }
  3260. };
  3261. var getRequest = transaction.objectStore("textures").get(url);
  3262. getRequest.onsuccess = function (event) {
  3263. texture = (event.target).result;
  3264. };
  3265. getRequest.onerror = function (event) {
  3266. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3267. image.src = url;
  3268. };
  3269. }
  3270. else {
  3271. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3272. image.src = url;
  3273. }
  3274. };
  3275. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3276. var _this = this;
  3277. if (this.isSupported) {
  3278. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3279. var generateBlobUrl = function () {
  3280. var blobTextureURL;
  3281. if (blob) {
  3282. var URL = window.URL || window.webkitURL;
  3283. try {
  3284. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3285. }
  3286. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3287. catch (ex) {
  3288. blobTextureURL = URL.createObjectURL(blob);
  3289. }
  3290. }
  3291. image.src = blobTextureURL;
  3292. };
  3293. if (Database.IsUASupportingBlobStorage) {
  3294. var xhr = new XMLHttpRequest(), blob;
  3295. xhr.open("GET", url, true);
  3296. xhr.responseType = "blob";
  3297. xhr.addEventListener("load", function () {
  3298. if (xhr.status === 200) {
  3299. // Blob as response (XHR2)
  3300. blob = xhr.response;
  3301. var transaction = _this.db.transaction(["textures"], "readwrite");
  3302. // the transaction could abort because of a QuotaExceededError error
  3303. transaction.onabort = function (event) {
  3304. try {
  3305. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3306. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3307. this.hasReachedQuota = true;
  3308. }
  3309. }
  3310. catch (ex) { }
  3311. generateBlobUrl();
  3312. };
  3313. transaction.oncomplete = function (event) {
  3314. generateBlobUrl();
  3315. };
  3316. var newTexture = { textureUrl: url, data: blob };
  3317. try {
  3318. // Put the blob into the dabase
  3319. var addRequest = transaction.objectStore("textures").put(newTexture);
  3320. addRequest.onsuccess = function (event) {
  3321. };
  3322. addRequest.onerror = function (event) {
  3323. generateBlobUrl();
  3324. };
  3325. }
  3326. catch (ex) {
  3327. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3328. if (ex.code === 25) {
  3329. Database.IsUASupportingBlobStorage = false;
  3330. }
  3331. image.src = url;
  3332. }
  3333. }
  3334. else {
  3335. image.src = url;
  3336. }
  3337. }, false);
  3338. xhr.addEventListener("error", function (event) {
  3339. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3340. image.src = url;
  3341. }, false);
  3342. xhr.send();
  3343. }
  3344. else {
  3345. image.src = url;
  3346. }
  3347. }
  3348. else {
  3349. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3350. image.src = url;
  3351. }
  3352. };
  3353. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3354. var _this = this;
  3355. var updateVersion = function (event) {
  3356. // the version is not yet in the DB or we need to update it
  3357. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3358. };
  3359. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3360. };
  3361. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3362. var _this = this;
  3363. if (this.isSupported) {
  3364. var version;
  3365. try {
  3366. var transaction = this.db.transaction(["versions"]);
  3367. transaction.oncomplete = function (event) {
  3368. if (version) {
  3369. // If the version in the JSON file is > than the version in DB
  3370. if (_this.manifestVersionFound > version.data) {
  3371. _this.mustUpdateRessources = true;
  3372. updateInDBCallback();
  3373. }
  3374. else {
  3375. callback(version.data);
  3376. }
  3377. }
  3378. else {
  3379. _this.mustUpdateRessources = true;
  3380. updateInDBCallback();
  3381. }
  3382. };
  3383. transaction.onabort = function (event) {
  3384. callback(-1);
  3385. };
  3386. var getRequest = transaction.objectStore("versions").get(url);
  3387. getRequest.onsuccess = function (event) {
  3388. version = (event.target).result;
  3389. };
  3390. getRequest.onerror = function (event) {
  3391. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3392. callback(-1);
  3393. };
  3394. }
  3395. catch (ex) {
  3396. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3397. callback(-1);
  3398. }
  3399. }
  3400. else {
  3401. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3402. callback(-1);
  3403. }
  3404. };
  3405. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3406. var _this = this;
  3407. if (this.isSupported && !this.hasReachedQuota) {
  3408. try {
  3409. // Open a transaction to the database
  3410. var transaction = this.db.transaction(["versions"], "readwrite");
  3411. // the transaction could abort because of a QuotaExceededError error
  3412. transaction.onabort = function (event) {
  3413. try {
  3414. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3415. _this.hasReachedQuota = true;
  3416. }
  3417. }
  3418. catch (ex) { }
  3419. callback(-1);
  3420. };
  3421. transaction.oncomplete = function (event) {
  3422. callback(_this.manifestVersionFound);
  3423. };
  3424. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3425. // Put the scene into the database
  3426. var addRequest = transaction.objectStore("versions").put(newVersion);
  3427. addRequest.onsuccess = function (event) {
  3428. };
  3429. addRequest.onerror = function (event) {
  3430. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3431. };
  3432. }
  3433. catch (ex) {
  3434. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3435. callback(-1);
  3436. }
  3437. }
  3438. else {
  3439. callback(-1);
  3440. }
  3441. };
  3442. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3443. var _this = this;
  3444. var completeUrl = Database.ReturnFullUrlLocation(url);
  3445. var saveAndLoadFile = function (event) {
  3446. // the scene is not yet in the DB, let's try to save it
  3447. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3448. };
  3449. this._checkVersionFromDB(completeUrl, function (version) {
  3450. if (version !== -1) {
  3451. if (!_this.mustUpdateRessources) {
  3452. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3453. }
  3454. else {
  3455. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3456. }
  3457. }
  3458. else {
  3459. errorCallback();
  3460. }
  3461. });
  3462. };
  3463. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3464. if (this.isSupported) {
  3465. var targetStore;
  3466. if (url.indexOf(".babylon") !== -1) {
  3467. targetStore = "scenes";
  3468. }
  3469. else {
  3470. targetStore = "textures";
  3471. }
  3472. var file;
  3473. var transaction = this.db.transaction([targetStore]);
  3474. transaction.oncomplete = function (event) {
  3475. if (file) {
  3476. callback(file.data);
  3477. }
  3478. else {
  3479. notInDBCallback();
  3480. }
  3481. };
  3482. transaction.onabort = function (event) {
  3483. notInDBCallback();
  3484. };
  3485. var getRequest = transaction.objectStore(targetStore).get(url);
  3486. getRequest.onsuccess = function (event) {
  3487. file = (event.target).result;
  3488. };
  3489. getRequest.onerror = function (event) {
  3490. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3491. notInDBCallback();
  3492. };
  3493. }
  3494. else {
  3495. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3496. callback();
  3497. }
  3498. };
  3499. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3500. var _this = this;
  3501. if (this.isSupported) {
  3502. var targetStore;
  3503. if (url.indexOf(".babylon") !== -1) {
  3504. targetStore = "scenes";
  3505. }
  3506. else {
  3507. targetStore = "textures";
  3508. }
  3509. // Create XHR
  3510. var xhr = new XMLHttpRequest(), fileData;
  3511. xhr.open("GET", url, true);
  3512. if (useArrayBuffer) {
  3513. xhr.responseType = "arraybuffer";
  3514. }
  3515. xhr.onprogress = progressCallback;
  3516. xhr.addEventListener("load", function () {
  3517. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3518. // Blob as response (XHR2)
  3519. //fileData = xhr.responseText;
  3520. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3521. if (!_this.hasReachedQuota) {
  3522. // Open a transaction to the database
  3523. var transaction = _this.db.transaction([targetStore], "readwrite");
  3524. // the transaction could abort because of a QuotaExceededError error
  3525. transaction.onabort = function (event) {
  3526. try {
  3527. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3528. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3529. this.hasReachedQuota = true;
  3530. }
  3531. }
  3532. catch (ex) { }
  3533. callback(fileData);
  3534. };
  3535. transaction.oncomplete = function (event) {
  3536. callback(fileData);
  3537. };
  3538. var newFile;
  3539. if (targetStore === "scenes") {
  3540. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3541. }
  3542. else {
  3543. newFile = { textureUrl: url, data: fileData };
  3544. }
  3545. try {
  3546. // Put the scene into the database
  3547. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3548. addRequest.onsuccess = function (event) {
  3549. };
  3550. addRequest.onerror = function (event) {
  3551. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3552. };
  3553. }
  3554. catch (ex) {
  3555. callback(fileData);
  3556. }
  3557. }
  3558. else {
  3559. callback(fileData);
  3560. }
  3561. }
  3562. else {
  3563. callback();
  3564. }
  3565. }, false);
  3566. xhr.addEventListener("error", function (event) {
  3567. BABYLON.Tools.Error("error on XHR request.");
  3568. callback();
  3569. }, false);
  3570. xhr.send();
  3571. }
  3572. else {
  3573. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3574. callback();
  3575. }
  3576. };
  3577. Database.IsUASupportingBlobStorage = true;
  3578. Database.IDBStorageEnabled = true;
  3579. Database.parseURL = function (url) {
  3580. var a = document.createElement('a');
  3581. a.href = url;
  3582. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3583. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3584. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3585. return absLocation;
  3586. };
  3587. Database.ReturnFullUrlLocation = function (url) {
  3588. if (url.indexOf("http:/") === -1) {
  3589. return (Database.parseURL(window.location.href) + url);
  3590. }
  3591. else {
  3592. return url;
  3593. }
  3594. };
  3595. return Database;
  3596. })();
  3597. BABYLON.Database = Database;
  3598. })(BABYLON || (BABYLON = {}));
  3599. var BABYLON;
  3600. (function (BABYLON) {
  3601. var Internals;
  3602. (function (Internals) {
  3603. /*
  3604. * Based on jsTGALoader - Javascript loader for TGA file
  3605. * By Vincent Thibault
  3606. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3607. */
  3608. var TGATools = (function () {
  3609. function TGATools() {
  3610. }
  3611. TGATools.GetTGAHeader = function (data) {
  3612. var offset = 0;
  3613. var header = {
  3614. id_length: data[offset++],
  3615. colormap_type: data[offset++],
  3616. image_type: data[offset++],
  3617. colormap_index: data[offset++] | data[offset++] << 8,
  3618. colormap_length: data[offset++] | data[offset++] << 8,
  3619. colormap_size: data[offset++],
  3620. origin: [
  3621. data[offset++] | data[offset++] << 8,
  3622. data[offset++] | data[offset++] << 8
  3623. ],
  3624. width: data[offset++] | data[offset++] << 8,
  3625. height: data[offset++] | data[offset++] << 8,
  3626. pixel_size: data[offset++],
  3627. flags: data[offset++]
  3628. };
  3629. return header;
  3630. };
  3631. TGATools.UploadContent = function (gl, data) {
  3632. // Not enough data to contain header ?
  3633. if (data.length < 19) {
  3634. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3635. return;
  3636. }
  3637. // Read Header
  3638. var offset = 18;
  3639. var header = TGATools.GetTGAHeader(data);
  3640. // Assume it's a valid Targa file.
  3641. if (header.id_length + offset > data.length) {
  3642. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3643. return;
  3644. }
  3645. // Skip not needed data
  3646. offset += header.id_length;
  3647. var use_rle = false;
  3648. var use_pal = false;
  3649. var use_rgb = false;
  3650. var use_grey = false;
  3651. // Get some informations.
  3652. switch (header.image_type) {
  3653. case TGATools._TYPE_RLE_INDEXED:
  3654. use_rle = true;
  3655. case TGATools._TYPE_INDEXED:
  3656. use_pal = true;
  3657. break;
  3658. case TGATools._TYPE_RLE_RGB:
  3659. use_rle = true;
  3660. case TGATools._TYPE_RGB:
  3661. use_rgb = true;
  3662. break;
  3663. case TGATools._TYPE_RLE_GREY:
  3664. use_rle = true;
  3665. case TGATools._TYPE_GREY:
  3666. use_grey = true;
  3667. break;
  3668. }
  3669. var pixel_data;
  3670. var numAlphaBits = header.flags & 0xf;
  3671. var pixel_size = header.pixel_size >> 3;
  3672. var pixel_total = header.width * header.height * pixel_size;
  3673. // Read palettes
  3674. var palettes;
  3675. if (use_pal) {
  3676. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3677. }
  3678. // Read LRE
  3679. if (use_rle) {
  3680. pixel_data = new Uint8Array(pixel_total);
  3681. var c, count, i;
  3682. var localOffset = 0;
  3683. var pixels = new Uint8Array(pixel_size);
  3684. while (offset < pixel_total && localOffset < pixel_total) {
  3685. c = data[offset++];
  3686. count = (c & 0x7f) + 1;
  3687. // RLE pixels
  3688. if (c & 0x80) {
  3689. // Bind pixel tmp array
  3690. for (i = 0; i < pixel_size; ++i) {
  3691. pixels[i] = data[offset++];
  3692. }
  3693. // Copy pixel array
  3694. for (i = 0; i < count; ++i) {
  3695. pixel_data.set(pixels, localOffset + i * pixel_size);
  3696. }
  3697. localOffset += pixel_size * count;
  3698. }
  3699. else {
  3700. count *= pixel_size;
  3701. for (i = 0; i < count; ++i) {
  3702. pixel_data[localOffset + i] = data[offset++];
  3703. }
  3704. localOffset += count;
  3705. }
  3706. }
  3707. }
  3708. else {
  3709. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3710. }
  3711. // Load to texture
  3712. var x_start, y_start, x_step, y_step, y_end, x_end;
  3713. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3714. default:
  3715. case TGATools._ORIGIN_UL:
  3716. x_start = 0;
  3717. x_step = 1;
  3718. x_end = header.width;
  3719. y_start = 0;
  3720. y_step = 1;
  3721. y_end = header.height;
  3722. break;
  3723. case TGATools._ORIGIN_BL:
  3724. x_start = 0;
  3725. x_step = 1;
  3726. x_end = header.width;
  3727. y_start = header.height - 1;
  3728. y_step = -1;
  3729. y_end = -1;
  3730. break;
  3731. case TGATools._ORIGIN_UR:
  3732. x_start = header.width - 1;
  3733. x_step = -1;
  3734. x_end = -1;
  3735. y_start = 0;
  3736. y_step = 1;
  3737. y_end = header.height;
  3738. break;
  3739. case TGATools._ORIGIN_BR:
  3740. x_start = header.width - 1;
  3741. x_step = -1;
  3742. x_end = -1;
  3743. y_start = header.height - 1;
  3744. y_step = -1;
  3745. y_end = -1;
  3746. break;
  3747. }
  3748. // Load the specify method
  3749. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3750. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3751. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3752. };
  3753. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3754. var image = pixel_data, colormap = palettes;
  3755. var width = header.width, height = header.height;
  3756. var color, i = 0, x, y;
  3757. var imageData = new Uint8Array(width * height * 4);
  3758. for (y = y_start; y !== y_end; y += y_step) {
  3759. for (x = x_start; x !== x_end; x += x_step, i++) {
  3760. color = image[i];
  3761. imageData[(x + width * y) * 4 + 3] = 255;
  3762. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3763. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3764. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3765. }
  3766. }
  3767. return imageData;
  3768. };
  3769. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3770. var image = pixel_data;
  3771. var width = header.width, height = header.height;
  3772. var color, i = 0, x, y;
  3773. var imageData = new Uint8Array(width * height * 4);
  3774. for (y = y_start; y !== y_end; y += y_step) {
  3775. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3776. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3777. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3778. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3779. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3780. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3781. }
  3782. }
  3783. return imageData;
  3784. };
  3785. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3786. var image = pixel_data;
  3787. var width = header.width, height = header.height;
  3788. var i = 0, x, y;
  3789. var imageData = new Uint8Array(width * height * 4);
  3790. for (y = y_start; y !== y_end; y += y_step) {
  3791. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3792. imageData[(x + width * y) * 4 + 3] = 255;
  3793. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3794. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3795. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3796. }
  3797. }
  3798. return imageData;
  3799. };
  3800. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3801. var image = pixel_data;
  3802. var width = header.width, height = header.height;
  3803. var i = 0, x, y;
  3804. var imageData = new Uint8Array(width * height * 4);
  3805. for (y = y_start; y !== y_end; y += y_step) {
  3806. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3807. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3808. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3809. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3810. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3811. }
  3812. }
  3813. return imageData;
  3814. };
  3815. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3816. var image = pixel_data;
  3817. var width = header.width, height = header.height;
  3818. var color, i = 0, x, y;
  3819. var imageData = new Uint8Array(width * height * 4);
  3820. for (y = y_start; y !== y_end; y += y_step) {
  3821. for (x = x_start; x !== x_end; x += x_step, i++) {
  3822. color = image[i];
  3823. imageData[(x + width * y) * 4 + 0] = color;
  3824. imageData[(x + width * y) * 4 + 1] = color;
  3825. imageData[(x + width * y) * 4 + 2] = color;
  3826. imageData[(x + width * y) * 4 + 3] = 255;
  3827. }
  3828. }
  3829. return imageData;
  3830. };
  3831. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3832. var image = pixel_data;
  3833. var width = header.width, height = header.height;
  3834. var i = 0, x, y;
  3835. var imageData = new Uint8Array(width * height * 4);
  3836. for (y = y_start; y !== y_end; y += y_step) {
  3837. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3838. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3839. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3840. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3841. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3842. }
  3843. }
  3844. return imageData;
  3845. };
  3846. TGATools._TYPE_NO_DATA = 0;
  3847. TGATools._TYPE_INDEXED = 1;
  3848. TGATools._TYPE_RGB = 2;
  3849. TGATools._TYPE_GREY = 3;
  3850. TGATools._TYPE_RLE_INDEXED = 9;
  3851. TGATools._TYPE_RLE_RGB = 10;
  3852. TGATools._TYPE_RLE_GREY = 11;
  3853. TGATools._ORIGIN_MASK = 0x30;
  3854. TGATools._ORIGIN_SHIFT = 0x04;
  3855. TGATools._ORIGIN_BL = 0x00;
  3856. TGATools._ORIGIN_BR = 0x01;
  3857. TGATools._ORIGIN_UL = 0x02;
  3858. TGATools._ORIGIN_UR = 0x03;
  3859. return TGATools;
  3860. })();
  3861. Internals.TGATools = TGATools;
  3862. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3863. })(BABYLON || (BABYLON = {}));
  3864. var BABYLON;
  3865. (function (BABYLON) {
  3866. var Internals;
  3867. (function (Internals) {
  3868. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3869. // All values and structures referenced from:
  3870. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3871. var DDS_MAGIC = 0x20534444;
  3872. 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;
  3873. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3874. 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;
  3875. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3876. function FourCCToInt32(value) {
  3877. return value.charCodeAt(0) +
  3878. (value.charCodeAt(1) << 8) +
  3879. (value.charCodeAt(2) << 16) +
  3880. (value.charCodeAt(3) << 24);
  3881. }
  3882. function Int32ToFourCC(value) {
  3883. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3884. }
  3885. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3886. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3887. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3888. var headerLengthInt = 31; // The header length in 32 bit ints
  3889. // Offsets into the header array
  3890. var off_magic = 0;
  3891. var off_size = 1;
  3892. var off_flags = 2;
  3893. var off_height = 3;
  3894. var off_width = 4;
  3895. var off_mipmapCount = 7;
  3896. var off_pfFlags = 20;
  3897. var off_pfFourCC = 21;
  3898. var off_RGBbpp = 22;
  3899. var off_RMask = 23;
  3900. var off_GMask = 24;
  3901. var off_BMask = 25;
  3902. var off_AMask = 26;
  3903. var off_caps1 = 27;
  3904. var off_caps2 = 28;
  3905. ;
  3906. var DDSTools = (function () {
  3907. function DDSTools() {
  3908. }
  3909. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3910. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3911. var mipmapCount = 1;
  3912. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3913. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3914. }
  3915. return {
  3916. width: header[off_width],
  3917. height: header[off_height],
  3918. mipmapCount: mipmapCount,
  3919. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3920. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3921. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3922. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3923. };
  3924. };
  3925. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3926. var byteArray = new Uint8Array(dataLength);
  3927. var srcData = new Uint8Array(arrayBuffer);
  3928. var index = 0;
  3929. for (var y = height - 1; y >= 0; y--) {
  3930. for (var x = 0; x < width; x++) {
  3931. var srcPos = dataOffset + (x + y * width) * 4;
  3932. byteArray[index + 2] = srcData[srcPos];
  3933. byteArray[index + 1] = srcData[srcPos + 1];
  3934. byteArray[index] = srcData[srcPos + 2];
  3935. byteArray[index + 3] = srcData[srcPos + 3];
  3936. index += 4;
  3937. }
  3938. }
  3939. return byteArray;
  3940. };
  3941. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3942. var byteArray = new Uint8Array(dataLength);
  3943. var srcData = new Uint8Array(arrayBuffer);
  3944. var index = 0;
  3945. for (var y = height - 1; y >= 0; y--) {
  3946. for (var x = 0; x < width; x++) {
  3947. var srcPos = dataOffset + (x + y * width) * 3;
  3948. byteArray[index + 2] = srcData[srcPos];
  3949. byteArray[index + 1] = srcData[srcPos + 1];
  3950. byteArray[index] = srcData[srcPos + 2];
  3951. index += 3;
  3952. }
  3953. }
  3954. return byteArray;
  3955. };
  3956. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3957. var byteArray = new Uint8Array(dataLength);
  3958. var srcData = new Uint8Array(arrayBuffer);
  3959. var index = 0;
  3960. for (var y = height - 1; y >= 0; y--) {
  3961. for (var x = 0; x < width; x++) {
  3962. var srcPos = dataOffset + (x + y * width);
  3963. byteArray[index] = srcData[srcPos];
  3964. index++;
  3965. }
  3966. }
  3967. return byteArray;
  3968. };
  3969. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3970. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3971. if (header[off_magic] != DDS_MAGIC) {
  3972. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3973. return;
  3974. }
  3975. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3976. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3977. return;
  3978. }
  3979. if (info.isFourCC) {
  3980. fourCC = header[off_pfFourCC];
  3981. switch (fourCC) {
  3982. case FOURCC_DXT1:
  3983. blockBytes = 8;
  3984. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3985. break;
  3986. case FOURCC_DXT3:
  3987. blockBytes = 16;
  3988. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3989. break;
  3990. case FOURCC_DXT5:
  3991. blockBytes = 16;
  3992. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3993. break;
  3994. default:
  3995. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3996. return;
  3997. }
  3998. }
  3999. mipmapCount = 1;
  4000. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4001. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4002. }
  4003. var bpp = header[off_RGBbpp];
  4004. for (var face = 0; face < faces; face++) {
  4005. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4006. width = header[off_width];
  4007. height = header[off_height];
  4008. dataOffset = header[off_size] + 4;
  4009. for (i = 0; i < mipmapCount; ++i) {
  4010. if (info.isRGB) {
  4011. if (bpp == 24) {
  4012. dataLength = width * height * 3;
  4013. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4014. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4015. }
  4016. else {
  4017. dataLength = width * height * 4;
  4018. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4019. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4020. }
  4021. }
  4022. else if (info.isLuminance) {
  4023. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4024. var unpaddedRowSize = width;
  4025. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4026. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4027. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4028. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4029. }
  4030. else {
  4031. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4032. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4033. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4034. }
  4035. dataOffset += dataLength;
  4036. width *= 0.5;
  4037. height *= 0.5;
  4038. width = Math.max(1.0, width);
  4039. height = Math.max(1.0, height);
  4040. }
  4041. }
  4042. };
  4043. return DDSTools;
  4044. })();
  4045. Internals.DDSTools = DDSTools;
  4046. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4047. })(BABYLON || (BABYLON = {}));
  4048. var BABYLON;
  4049. (function (BABYLON) {
  4050. var SmartArray = (function () {
  4051. function SmartArray(capacity) {
  4052. this.length = 0;
  4053. this._duplicateId = 0;
  4054. this.data = new Array(capacity);
  4055. this._id = SmartArray._GlobalId++;
  4056. }
  4057. SmartArray.prototype.push = function (value) {
  4058. this.data[this.length++] = value;
  4059. if (this.length > this.data.length) {
  4060. this.data.length *= 2;
  4061. }
  4062. if (!value.__smartArrayFlags) {
  4063. value.__smartArrayFlags = {};
  4064. }
  4065. value.__smartArrayFlags[this._id] = this._duplicateId;
  4066. };
  4067. SmartArray.prototype.pushNoDuplicate = function (value) {
  4068. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4069. return;
  4070. }
  4071. this.push(value);
  4072. };
  4073. SmartArray.prototype.sort = function (compareFn) {
  4074. this.data.sort(compareFn);
  4075. };
  4076. SmartArray.prototype.reset = function () {
  4077. this.length = 0;
  4078. this._duplicateId++;
  4079. };
  4080. SmartArray.prototype.concat = function (array) {
  4081. if (array.length === 0) {
  4082. return;
  4083. }
  4084. if (this.length + array.length > this.data.length) {
  4085. this.data.length = (this.length + array.length) * 2;
  4086. }
  4087. for (var index = 0; index < array.length; index++) {
  4088. this.data[this.length++] = (array.data || array)[index];
  4089. }
  4090. };
  4091. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4092. if (array.length === 0) {
  4093. return;
  4094. }
  4095. if (this.length + array.length > this.data.length) {
  4096. this.data.length = (this.length + array.length) * 2;
  4097. }
  4098. for (var index = 0; index < array.length; index++) {
  4099. var item = (array.data || array)[index];
  4100. this.pushNoDuplicate(item);
  4101. }
  4102. };
  4103. SmartArray.prototype.indexOf = function (value) {
  4104. var position = this.data.indexOf(value);
  4105. if (position >= this.length) {
  4106. return -1;
  4107. }
  4108. return position;
  4109. };
  4110. // Statics
  4111. SmartArray._GlobalId = 0;
  4112. return SmartArray;
  4113. })();
  4114. BABYLON.SmartArray = SmartArray;
  4115. })(BABYLON || (BABYLON = {}));
  4116. var BABYLON;
  4117. (function (BABYLON) {
  4118. var SmartCollection = (function () {
  4119. function SmartCollection(capacity) {
  4120. if (capacity === void 0) { capacity = 10; }
  4121. this.count = 0;
  4122. this._initialCapacity = capacity;
  4123. this.items = {};
  4124. this._keys = new Array(this._initialCapacity);
  4125. }
  4126. SmartCollection.prototype.add = function (key, item) {
  4127. if (this.items[key] != undefined) {
  4128. return -1;
  4129. }
  4130. this.items[key] = item;
  4131. //literal keys are always strings, but we keep source type of key in _keys array
  4132. this._keys[this.count++] = key;
  4133. if (this.count > this._keys.length) {
  4134. this._keys.length *= 2;
  4135. }
  4136. return this.count;
  4137. };
  4138. SmartCollection.prototype.remove = function (key) {
  4139. if (this.items[key] == undefined) {
  4140. return -1;
  4141. }
  4142. return this.removeItemOfIndex(this.indexOf(key));
  4143. };
  4144. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4145. if (index < this.count && index > -1) {
  4146. delete this.items[this._keys[index]];
  4147. //here, shifting by hand is better optimised than .splice
  4148. while (index < this.count) {
  4149. this._keys[index] = this._keys[index + 1];
  4150. index++;
  4151. }
  4152. }
  4153. else {
  4154. return -1;
  4155. }
  4156. return --this.count;
  4157. };
  4158. SmartCollection.prototype.indexOf = function (key) {
  4159. for (var i = 0; i !== this.count; i++) {
  4160. if (this._keys[i] === key) {
  4161. return i;
  4162. }
  4163. }
  4164. return -1;
  4165. };
  4166. SmartCollection.prototype.item = function (key) {
  4167. return this.items[key];
  4168. };
  4169. SmartCollection.prototype.getAllKeys = function () {
  4170. if (this.count > 0) {
  4171. var keys = new Array(this.count);
  4172. for (var i = 0; i < this.count; i++) {
  4173. keys[i] = this._keys[i];
  4174. }
  4175. return keys;
  4176. }
  4177. else {
  4178. return undefined;
  4179. }
  4180. };
  4181. SmartCollection.prototype.getKeyByIndex = function (index) {
  4182. if (index < this.count && index > -1) {
  4183. return this._keys[index];
  4184. }
  4185. else {
  4186. return undefined;
  4187. }
  4188. };
  4189. SmartCollection.prototype.getItemByIndex = function (index) {
  4190. if (index < this.count && index > -1) {
  4191. return this.items[this._keys[index]];
  4192. }
  4193. else {
  4194. return undefined;
  4195. }
  4196. };
  4197. SmartCollection.prototype.empty = function () {
  4198. if (this.count > 0) {
  4199. this.count = 0;
  4200. this.items = {};
  4201. this._keys = new Array(this._initialCapacity);
  4202. }
  4203. };
  4204. SmartCollection.prototype.forEach = function (block) {
  4205. var key;
  4206. for (key in this.items) {
  4207. if (this.items.hasOwnProperty(key)) {
  4208. block(this.items[key]);
  4209. }
  4210. }
  4211. };
  4212. return SmartCollection;
  4213. })();
  4214. BABYLON.SmartCollection = SmartCollection;
  4215. })(BABYLON || (BABYLON = {}));
  4216. var BABYLON;
  4217. (function (BABYLON) {
  4218. // Screenshots
  4219. var screenshotCanvas;
  4220. var cloneValue = function (source, destinationObject) {
  4221. if (!source)
  4222. return null;
  4223. if (source instanceof BABYLON.Mesh) {
  4224. return null;
  4225. }
  4226. if (source instanceof BABYLON.SubMesh) {
  4227. return source.clone(destinationObject);
  4228. }
  4229. else if (source.clone) {
  4230. return source.clone();
  4231. }
  4232. return null;
  4233. };
  4234. var Tools = (function () {
  4235. function Tools() {
  4236. }
  4237. Tools.ToHex = function (i) {
  4238. var str = i.toString(16);
  4239. if (i <= 15) {
  4240. return ("0" + str).toUpperCase();
  4241. }
  4242. return str.toUpperCase();
  4243. };
  4244. Tools.SetImmediate = function (action) {
  4245. if (window.setImmediate) {
  4246. window.setImmediate(action);
  4247. }
  4248. else {
  4249. setTimeout(action, 1);
  4250. }
  4251. };
  4252. Tools.IsExponantOfTwo = function (value) {
  4253. var count = 1;
  4254. do {
  4255. count *= 2;
  4256. } while (count < value);
  4257. return count === value;
  4258. };
  4259. Tools.GetExponantOfTwo = function (value, max) {
  4260. var count = 1;
  4261. do {
  4262. count *= 2;
  4263. } while (count < value);
  4264. if (count > max)
  4265. count = max;
  4266. return count;
  4267. };
  4268. Tools.GetFilename = function (path) {
  4269. var index = path.lastIndexOf("/");
  4270. if (index < 0)
  4271. return path;
  4272. return path.substring(index + 1);
  4273. };
  4274. Tools.GetDOMTextContent = function (element) {
  4275. var result = "";
  4276. var child = element.firstChild;
  4277. while (child) {
  4278. if (child.nodeType === 3) {
  4279. result += child.textContent;
  4280. }
  4281. child = child.nextSibling;
  4282. }
  4283. return result;
  4284. };
  4285. Tools.ToDegrees = function (angle) {
  4286. return angle * 180 / Math.PI;
  4287. };
  4288. Tools.ToRadians = function (angle) {
  4289. return angle * Math.PI / 180;
  4290. };
  4291. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4292. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4293. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4294. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4295. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4296. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4297. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4298. }
  4299. return {
  4300. minimum: minimum,
  4301. maximum: maximum
  4302. };
  4303. };
  4304. Tools.ExtractMinAndMax = function (positions, start, count) {
  4305. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4306. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4307. for (var index = start; index < start + count; index++) {
  4308. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4309. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4310. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4311. }
  4312. return {
  4313. minimum: minimum,
  4314. maximum: maximum
  4315. };
  4316. };
  4317. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4318. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4319. return undefined;
  4320. return Array.isArray(obj) ? obj : [obj];
  4321. };
  4322. // Misc.
  4323. Tools.GetPointerPrefix = function () {
  4324. var eventPrefix = "pointer";
  4325. // Check if hand.js is referenced or if the browser natively supports pointer events
  4326. if (!navigator.pointerEnabled) {
  4327. eventPrefix = "mouse";
  4328. }
  4329. return eventPrefix;
  4330. };
  4331. Tools.QueueNewFrame = function (func) {
  4332. if (window.requestAnimationFrame)
  4333. window.requestAnimationFrame(func);
  4334. else if (window.msRequestAnimationFrame)
  4335. window.msRequestAnimationFrame(func);
  4336. else if (window.webkitRequestAnimationFrame)
  4337. window.webkitRequestAnimationFrame(func);
  4338. else if (window.mozRequestAnimationFrame)
  4339. window.mozRequestAnimationFrame(func);
  4340. else if (window.oRequestAnimationFrame)
  4341. window.oRequestAnimationFrame(func);
  4342. else {
  4343. window.setTimeout(func, 16);
  4344. }
  4345. };
  4346. Tools.RequestFullscreen = function (element) {
  4347. if (element.requestFullscreen)
  4348. element.requestFullscreen();
  4349. else if (element.msRequestFullscreen)
  4350. element.msRequestFullscreen();
  4351. else if (element.webkitRequestFullscreen)
  4352. element.webkitRequestFullscreen();
  4353. else if (element.mozRequestFullScreen)
  4354. element.mozRequestFullScreen();
  4355. };
  4356. Tools.ExitFullscreen = function () {
  4357. if (document.exitFullscreen) {
  4358. document.exitFullscreen();
  4359. }
  4360. else if (document.mozCancelFullScreen) {
  4361. document.mozCancelFullScreen();
  4362. }
  4363. else if (document.webkitCancelFullScreen) {
  4364. document.webkitCancelFullScreen();
  4365. }
  4366. else if (document.msCancelFullScreen) {
  4367. document.msCancelFullScreen();
  4368. }
  4369. };
  4370. // External files
  4371. Tools.CleanUrl = function (url) {
  4372. url = url.replace(/#/mg, "%23");
  4373. return url;
  4374. };
  4375. Tools.LoadImage = function (url, onload, onerror, database) {
  4376. url = Tools.CleanUrl(url);
  4377. var img = new Image();
  4378. if (url.substr(0, 5) !== "data:")
  4379. img.crossOrigin = 'anonymous';
  4380. img.onload = function () {
  4381. onload(img);
  4382. };
  4383. img.onerror = function (err) {
  4384. Tools.Error("Error while trying to load texture: " + url);
  4385. 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";
  4386. onload(img);
  4387. };
  4388. var noIndexedDB = function () {
  4389. img.src = url;
  4390. };
  4391. var loadFromIndexedDB = function () {
  4392. database.loadImageFromDB(url, img);
  4393. };
  4394. //ANY database to do!
  4395. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4396. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4397. }
  4398. else {
  4399. if (url.indexOf("file:") === -1) {
  4400. noIndexedDB();
  4401. }
  4402. else {
  4403. try {
  4404. var textureName = url.substring(5);
  4405. var blobURL;
  4406. try {
  4407. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4408. }
  4409. catch (ex) {
  4410. // Chrome doesn't support oneTimeOnly parameter
  4411. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4412. }
  4413. img.src = blobURL;
  4414. }
  4415. catch (e) {
  4416. img.src = null;
  4417. }
  4418. }
  4419. }
  4420. return img;
  4421. };
  4422. //ANY
  4423. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4424. url = Tools.CleanUrl(url);
  4425. var noIndexedDB = function () {
  4426. var request = new XMLHttpRequest();
  4427. var loadUrl = Tools.BaseUrl + url;
  4428. request.open('GET', loadUrl, true);
  4429. if (useArrayBuffer) {
  4430. request.responseType = "arraybuffer";
  4431. }
  4432. request.onprogress = progressCallBack;
  4433. request.onreadystatechange = function () {
  4434. if (request.readyState === 4) {
  4435. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4436. callback(!useArrayBuffer ? request.responseText : request.response);
  4437. }
  4438. else {
  4439. if (onError) {
  4440. onError();
  4441. }
  4442. else {
  4443. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4444. }
  4445. }
  4446. }
  4447. };
  4448. request.send(null);
  4449. };
  4450. var loadFromIndexedDB = function () {
  4451. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4452. };
  4453. if (url.indexOf("file:") !== -1) {
  4454. var fileName = url.substring(5);
  4455. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4456. }
  4457. else {
  4458. // Caching all files
  4459. if (database && database.enableSceneOffline) {
  4460. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4461. }
  4462. else {
  4463. noIndexedDB();
  4464. }
  4465. }
  4466. };
  4467. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4468. var reader = new FileReader();
  4469. reader.onload = function (e) {
  4470. //target doesn't have result from ts 1.3
  4471. callback(e.target['result']);
  4472. };
  4473. reader.onprogress = progressCallback;
  4474. reader.readAsDataURL(fileToLoad);
  4475. };
  4476. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4477. var reader = new FileReader();
  4478. reader.onerror = function (e) {
  4479. Tools.Log("Error while reading file: " + fileToLoad.name);
  4480. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4481. };
  4482. reader.onload = function (e) {
  4483. //target doesn't have result from ts 1.3
  4484. callback(e.target['result']);
  4485. };
  4486. reader.onprogress = progressCallBack;
  4487. if (!useArrayBuffer) {
  4488. // Asynchronous read
  4489. reader.readAsText(fileToLoad);
  4490. }
  4491. else {
  4492. reader.readAsArrayBuffer(fileToLoad);
  4493. }
  4494. };
  4495. // Misc.
  4496. Tools.Clamp = function (value, min, max) {
  4497. if (min === void 0) { min = 0; }
  4498. if (max === void 0) { max = 1; }
  4499. return Math.min(max, Math.max(min, value));
  4500. };
  4501. // Returns -1 when value is a negative number and
  4502. // +1 when value is a positive number.
  4503. Tools.Sign = function (value) {
  4504. value = +value; // convert to a number
  4505. if (value === 0 || isNaN(value))
  4506. return value;
  4507. return value > 0 ? 1 : -1;
  4508. };
  4509. Tools.Format = function (value, decimals) {
  4510. if (decimals === void 0) { decimals = 2; }
  4511. return value.toFixed(decimals);
  4512. };
  4513. Tools.CheckExtends = function (v, min, max) {
  4514. if (v.x < min.x)
  4515. min.x = v.x;
  4516. if (v.y < min.y)
  4517. min.y = v.y;
  4518. if (v.z < min.z)
  4519. min.z = v.z;
  4520. if (v.x > max.x)
  4521. max.x = v.x;
  4522. if (v.y > max.y)
  4523. max.y = v.y;
  4524. if (v.z > max.z)
  4525. max.z = v.z;
  4526. };
  4527. Tools.WithinEpsilon = function (a, b, epsilon) {
  4528. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4529. var num = a - b;
  4530. return -epsilon <= num && num <= epsilon;
  4531. };
  4532. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4533. for (var prop in source) {
  4534. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4535. continue;
  4536. }
  4537. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4538. continue;
  4539. }
  4540. var sourceValue = source[prop];
  4541. var typeOfSourceValue = typeof sourceValue;
  4542. if (typeOfSourceValue === "function") {
  4543. continue;
  4544. }
  4545. if (typeOfSourceValue === "object") {
  4546. if (sourceValue instanceof Array) {
  4547. destination[prop] = [];
  4548. if (sourceValue.length > 0) {
  4549. if (typeof sourceValue[0] == "object") {
  4550. for (var index = 0; index < sourceValue.length; index++) {
  4551. var clonedValue = cloneValue(sourceValue[index], destination);
  4552. if (destination[prop].indexOf(clonedValue) === -1) {
  4553. destination[prop].push(clonedValue);
  4554. }
  4555. }
  4556. }
  4557. else {
  4558. destination[prop] = sourceValue.slice(0);
  4559. }
  4560. }
  4561. }
  4562. else {
  4563. destination[prop] = cloneValue(sourceValue, destination);
  4564. }
  4565. }
  4566. else {
  4567. destination[prop] = sourceValue;
  4568. }
  4569. }
  4570. };
  4571. Tools.IsEmpty = function (obj) {
  4572. for (var i in obj) {
  4573. return false;
  4574. }
  4575. return true;
  4576. };
  4577. Tools.RegisterTopRootEvents = function (events) {
  4578. for (var index = 0; index < events.length; index++) {
  4579. var event = events[index];
  4580. window.addEventListener(event.name, event.handler, false);
  4581. try {
  4582. if (window.parent) {
  4583. window.parent.addEventListener(event.name, event.handler, false);
  4584. }
  4585. }
  4586. catch (e) {
  4587. }
  4588. }
  4589. };
  4590. Tools.UnregisterTopRootEvents = function (events) {
  4591. for (var index = 0; index < events.length; index++) {
  4592. var event = events[index];
  4593. window.removeEventListener(event.name, event.handler);
  4594. try {
  4595. if (window.parent) {
  4596. window.parent.removeEventListener(event.name, event.handler);
  4597. }
  4598. }
  4599. catch (e) {
  4600. }
  4601. }
  4602. };
  4603. Tools.DumpFramebuffer = function (width, height, engine) {
  4604. // Read the contents of the framebuffer
  4605. var numberOfChannelsByLine = width * 4;
  4606. var halfHeight = height / 2;
  4607. //Reading datas from WebGL
  4608. var data = engine.readPixels(0, 0, width, height);
  4609. //To flip image on Y axis.
  4610. for (var i = 0; i < halfHeight; i++) {
  4611. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4612. var currentCell = j + i * numberOfChannelsByLine;
  4613. var targetLine = height - i - 1;
  4614. var targetCell = j + targetLine * numberOfChannelsByLine;
  4615. var temp = data[currentCell];
  4616. data[currentCell] = data[targetCell];
  4617. data[targetCell] = temp;
  4618. }
  4619. }
  4620. // Create a 2D canvas to store the result
  4621. if (!screenshotCanvas) {
  4622. screenshotCanvas = document.createElement('canvas');
  4623. }
  4624. screenshotCanvas.width = width;
  4625. screenshotCanvas.height = height;
  4626. var context = screenshotCanvas.getContext('2d');
  4627. // Copy the pixels to a 2D canvas
  4628. var imageData = context.createImageData(width, height);
  4629. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4630. var castData = imageData.data;
  4631. castData.set(data);
  4632. context.putImageData(imageData, 0, 0);
  4633. var base64Image = screenshotCanvas.toDataURL();
  4634. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4635. if (("download" in document.createElement("a"))) {
  4636. var a = window.document.createElement("a");
  4637. a.href = base64Image;
  4638. var date = new Date();
  4639. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4640. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4641. window.document.body.appendChild(a);
  4642. a.addEventListener("click", function () {
  4643. a.parentElement.removeChild(a);
  4644. });
  4645. a.click();
  4646. }
  4647. else {
  4648. var newWindow = window.open("");
  4649. var img = newWindow.document.createElement("img");
  4650. img.src = base64Image;
  4651. newWindow.document.body.appendChild(img);
  4652. }
  4653. };
  4654. Tools.CreateScreenshot = function (engine, camera, size) {
  4655. var width;
  4656. var height;
  4657. var scene = camera.getScene();
  4658. var previousCamera = null;
  4659. if (scene.activeCamera !== camera) {
  4660. previousCamera = scene.activeCamera;
  4661. scene.activeCamera = camera;
  4662. }
  4663. //If a precision value is specified
  4664. if (size.precision) {
  4665. width = Math.round(engine.getRenderWidth() * size.precision);
  4666. height = Math.round(width / engine.getAspectRatio(camera));
  4667. size = { width: width, height: height };
  4668. }
  4669. else if (size.width && size.height) {
  4670. width = size.width;
  4671. height = size.height;
  4672. }
  4673. else if (size.width && !size.height) {
  4674. width = size.width;
  4675. height = Math.round(width / engine.getAspectRatio(camera));
  4676. size = { width: width, height: height };
  4677. }
  4678. else if (size.height && !size.width) {
  4679. height = size.height;
  4680. width = Math.round(height * engine.getAspectRatio(camera));
  4681. size = { width: width, height: height };
  4682. }
  4683. else if (!isNaN(size)) {
  4684. height = size;
  4685. width = size;
  4686. }
  4687. else {
  4688. Tools.Error("Invalid 'size' parameter !");
  4689. return;
  4690. }
  4691. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4692. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4693. texture.renderList = scene.meshes;
  4694. texture.onAfterRender = function () {
  4695. Tools.DumpFramebuffer(width, height, engine);
  4696. };
  4697. scene.incrementRenderId();
  4698. texture.render(true);
  4699. texture.dispose();
  4700. if (previousCamera) {
  4701. scene.activeCamera = previousCamera;
  4702. }
  4703. };
  4704. // XHR response validator for local file scenario
  4705. Tools.ValidateXHRData = function (xhr, dataType) {
  4706. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4707. if (dataType === void 0) { dataType = 7; }
  4708. try {
  4709. if (dataType & 1) {
  4710. if (xhr.responseText && xhr.responseText.length > 0) {
  4711. return true;
  4712. }
  4713. else if (dataType === 1) {
  4714. return false;
  4715. }
  4716. }
  4717. if (dataType & 2) {
  4718. // Check header width and height since there is no "TGA" magic number
  4719. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4720. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4721. return true;
  4722. }
  4723. else if (dataType === 2) {
  4724. return false;
  4725. }
  4726. }
  4727. if (dataType & 4) {
  4728. // Check for the "DDS" magic number
  4729. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4730. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4731. return true;
  4732. }
  4733. else {
  4734. return false;
  4735. }
  4736. }
  4737. }
  4738. catch (e) {
  4739. }
  4740. return false;
  4741. };
  4742. Object.defineProperty(Tools, "NoneLogLevel", {
  4743. get: function () {
  4744. return Tools._NoneLogLevel;
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Object.defineProperty(Tools, "MessageLogLevel", {
  4750. get: function () {
  4751. return Tools._MessageLogLevel;
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "WarningLogLevel", {
  4757. get: function () {
  4758. return Tools._WarningLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "ErrorLogLevel", {
  4764. get: function () {
  4765. return Tools._ErrorLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "AllLogLevel", {
  4771. get: function () {
  4772. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Tools._AddLogEntry = function (entry) {
  4778. Tools._LogCache = entry + Tools._LogCache;
  4779. if (Tools.OnNewCacheEntry) {
  4780. Tools.OnNewCacheEntry(entry);
  4781. }
  4782. };
  4783. Tools._FormatMessage = function (message) {
  4784. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4785. var date = new Date();
  4786. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4787. };
  4788. Tools._LogDisabled = function (message) {
  4789. // nothing to do
  4790. };
  4791. Tools._LogEnabled = function (message) {
  4792. var formattedMessage = Tools._FormatMessage(message);
  4793. console.log("BJS - " + formattedMessage);
  4794. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4795. Tools._AddLogEntry(entry);
  4796. };
  4797. Tools._WarnDisabled = function (message) {
  4798. // nothing to do
  4799. };
  4800. Tools._WarnEnabled = function (message) {
  4801. var formattedMessage = Tools._FormatMessage(message);
  4802. console.warn("BJS - " + formattedMessage);
  4803. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4804. Tools._AddLogEntry(entry);
  4805. };
  4806. Tools._ErrorDisabled = function (message) {
  4807. // nothing to do
  4808. };
  4809. Tools._ErrorEnabled = function (message) {
  4810. Tools.errorsCount++;
  4811. var formattedMessage = Tools._FormatMessage(message);
  4812. console.error("BJS - " + formattedMessage);
  4813. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4814. Tools._AddLogEntry(entry);
  4815. };
  4816. Object.defineProperty(Tools, "LogCache", {
  4817. get: function () {
  4818. return Tools._LogCache;
  4819. },
  4820. enumerable: true,
  4821. configurable: true
  4822. });
  4823. Tools.ClearLogCache = function () {
  4824. Tools._LogCache = "";
  4825. Tools.errorsCount = 0;
  4826. };
  4827. Object.defineProperty(Tools, "LogLevels", {
  4828. set: function (level) {
  4829. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4830. Tools.Log = Tools._LogEnabled;
  4831. }
  4832. else {
  4833. Tools.Log = Tools._LogDisabled;
  4834. }
  4835. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4836. Tools.Warn = Tools._WarnEnabled;
  4837. }
  4838. else {
  4839. Tools.Warn = Tools._WarnDisabled;
  4840. }
  4841. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4842. Tools.Error = Tools._ErrorEnabled;
  4843. }
  4844. else {
  4845. Tools.Error = Tools._ErrorDisabled;
  4846. }
  4847. },
  4848. enumerable: true,
  4849. configurable: true
  4850. });
  4851. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4852. get: function () {
  4853. return Tools._PerformanceNoneLogLevel;
  4854. },
  4855. enumerable: true,
  4856. configurable: true
  4857. });
  4858. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4859. get: function () {
  4860. return Tools._PerformanceUserMarkLogLevel;
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4866. get: function () {
  4867. return Tools._PerformanceConsoleLogLevel;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4873. set: function (level) {
  4874. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4875. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4876. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4877. return;
  4878. }
  4879. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4880. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4881. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4882. return;
  4883. }
  4884. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4885. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4886. },
  4887. enumerable: true,
  4888. configurable: true
  4889. });
  4890. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4891. };
  4892. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4893. };
  4894. Tools._StartUserMark = function (counterName, condition) {
  4895. if (condition === void 0) { condition = true; }
  4896. if (!condition || !Tools._performance.mark) {
  4897. return;
  4898. }
  4899. Tools._performance.mark(counterName + "-Begin");
  4900. };
  4901. Tools._EndUserMark = function (counterName, condition) {
  4902. if (condition === void 0) { condition = true; }
  4903. if (!condition || !Tools._performance.mark) {
  4904. return;
  4905. }
  4906. Tools._performance.mark(counterName + "-End");
  4907. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4908. };
  4909. Tools._StartPerformanceConsole = function (counterName, condition) {
  4910. if (condition === void 0) { condition = true; }
  4911. if (!condition) {
  4912. return;
  4913. }
  4914. Tools._StartUserMark(counterName, condition);
  4915. if (console.time) {
  4916. console.time(counterName);
  4917. }
  4918. };
  4919. Tools._EndPerformanceConsole = function (counterName, condition) {
  4920. if (condition === void 0) { condition = true; }
  4921. if (!condition) {
  4922. return;
  4923. }
  4924. Tools._EndUserMark(counterName, condition);
  4925. if (console.time) {
  4926. console.timeEnd(counterName);
  4927. }
  4928. };
  4929. Object.defineProperty(Tools, "Now", {
  4930. get: function () {
  4931. if (window.performance && window.performance.now) {
  4932. return window.performance.now();
  4933. }
  4934. return new Date().getTime();
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. // Deprecated
  4940. Tools.GetFps = function () {
  4941. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4942. return 0;
  4943. };
  4944. Tools.BaseUrl = "";
  4945. // Logs
  4946. Tools._NoneLogLevel = 0;
  4947. Tools._MessageLogLevel = 1;
  4948. Tools._WarningLogLevel = 2;
  4949. Tools._ErrorLogLevel = 4;
  4950. Tools._LogCache = "";
  4951. Tools.errorsCount = 0;
  4952. Tools.Log = Tools._LogEnabled;
  4953. Tools.Warn = Tools._WarnEnabled;
  4954. Tools.Error = Tools._ErrorEnabled;
  4955. // Performances
  4956. Tools._PerformanceNoneLogLevel = 0;
  4957. Tools._PerformanceUserMarkLogLevel = 1;
  4958. Tools._PerformanceConsoleLogLevel = 2;
  4959. Tools._performance = window.performance;
  4960. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4961. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4962. return Tools;
  4963. })();
  4964. BABYLON.Tools = Tools;
  4965. /**
  4966. * An implementation of a loop for asynchronous functions.
  4967. */
  4968. var AsyncLoop = (function () {
  4969. /**
  4970. * Constroctor.
  4971. * @param iterations the number of iterations.
  4972. * @param _fn the function to run each iteration
  4973. * @param _successCallback the callback that will be called upon succesful execution
  4974. * @param offset starting offset.
  4975. */
  4976. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4977. if (offset === void 0) { offset = 0; }
  4978. this.iterations = iterations;
  4979. this._fn = _fn;
  4980. this._successCallback = _successCallback;
  4981. this.index = offset - 1;
  4982. this._done = false;
  4983. }
  4984. /**
  4985. * Execute the next iteration. Must be called after the last iteration was finished.
  4986. */
  4987. AsyncLoop.prototype.executeNext = function () {
  4988. if (!this._done) {
  4989. if (this.index + 1 < this.iterations) {
  4990. ++this.index;
  4991. this._fn(this);
  4992. }
  4993. else {
  4994. this.breakLoop();
  4995. }
  4996. }
  4997. };
  4998. /**
  4999. * Break the loop and run the success callback.
  5000. */
  5001. AsyncLoop.prototype.breakLoop = function () {
  5002. this._done = true;
  5003. this._successCallback();
  5004. };
  5005. /**
  5006. * Helper function
  5007. */
  5008. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5009. if (offset === void 0) { offset = 0; }
  5010. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5011. loop.executeNext();
  5012. return loop;
  5013. };
  5014. /**
  5015. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5016. * @param iterations total number of iterations
  5017. * @param syncedIterations number of synchronous iterations in each async iteration.
  5018. * @param fn the function to call each iteration.
  5019. * @param callback a success call back that will be called when iterating stops.
  5020. * @param breakFunction a break condition (optional)
  5021. * @param timeout timeout settings for the setTimeout function. default - 0.
  5022. * @constructor
  5023. */
  5024. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5025. if (timeout === void 0) { timeout = 0; }
  5026. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5027. if (breakFunction && breakFunction())
  5028. loop.breakLoop();
  5029. else {
  5030. setTimeout(function () {
  5031. for (var i = 0; i < syncedIterations; ++i) {
  5032. var iteration = (loop.index * syncedIterations) + i;
  5033. if (iteration >= iterations)
  5034. break;
  5035. fn(iteration);
  5036. if (breakFunction && breakFunction()) {
  5037. loop.breakLoop();
  5038. break;
  5039. }
  5040. }
  5041. loop.executeNext();
  5042. }, timeout);
  5043. }
  5044. }, callback);
  5045. };
  5046. return AsyncLoop;
  5047. })();
  5048. BABYLON.AsyncLoop = AsyncLoop;
  5049. })(BABYLON || (BABYLON = {}));
  5050. var BABYLON;
  5051. (function (BABYLON) {
  5052. var _DepthCullingState = (function () {
  5053. function _DepthCullingState() {
  5054. this._isDepthTestDirty = false;
  5055. this._isDepthMaskDirty = false;
  5056. this._isDepthFuncDirty = false;
  5057. this._isCullFaceDirty = false;
  5058. this._isCullDirty = false;
  5059. this._isZOffsetDirty = false;
  5060. }
  5061. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5062. get: function () {
  5063. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5064. },
  5065. enumerable: true,
  5066. configurable: true
  5067. });
  5068. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5069. get: function () {
  5070. return this._zOffset;
  5071. },
  5072. set: function (value) {
  5073. if (this._zOffset === value) {
  5074. return;
  5075. }
  5076. this._zOffset = value;
  5077. this._isZOffsetDirty = true;
  5078. },
  5079. enumerable: true,
  5080. configurable: true
  5081. });
  5082. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5083. get: function () {
  5084. return this._cullFace;
  5085. },
  5086. set: function (value) {
  5087. if (this._cullFace === value) {
  5088. return;
  5089. }
  5090. this._cullFace = value;
  5091. this._isCullFaceDirty = true;
  5092. },
  5093. enumerable: true,
  5094. configurable: true
  5095. });
  5096. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5097. get: function () {
  5098. return this._cull;
  5099. },
  5100. set: function (value) {
  5101. if (this._cull === value) {
  5102. return;
  5103. }
  5104. this._cull = value;
  5105. this._isCullDirty = true;
  5106. },
  5107. enumerable: true,
  5108. configurable: true
  5109. });
  5110. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5111. get: function () {
  5112. return this._depthFunc;
  5113. },
  5114. set: function (value) {
  5115. if (this._depthFunc === value) {
  5116. return;
  5117. }
  5118. this._depthFunc = value;
  5119. this._isDepthFuncDirty = true;
  5120. },
  5121. enumerable: true,
  5122. configurable: true
  5123. });
  5124. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5125. get: function () {
  5126. return this._depthMask;
  5127. },
  5128. set: function (value) {
  5129. if (this._depthMask === value) {
  5130. return;
  5131. }
  5132. this._depthMask = value;
  5133. this._isDepthMaskDirty = true;
  5134. },
  5135. enumerable: true,
  5136. configurable: true
  5137. });
  5138. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5139. get: function () {
  5140. return this._depthTest;
  5141. },
  5142. set: function (value) {
  5143. if (this._depthTest === value) {
  5144. return;
  5145. }
  5146. this._depthTest = value;
  5147. this._isDepthTestDirty = true;
  5148. },
  5149. enumerable: true,
  5150. configurable: true
  5151. });
  5152. _DepthCullingState.prototype.reset = function () {
  5153. this._depthMask = true;
  5154. this._depthTest = true;
  5155. this._depthFunc = null;
  5156. this._cull = null;
  5157. this._cullFace = null;
  5158. this._zOffset = 0;
  5159. this._isDepthTestDirty = true;
  5160. this._isDepthMaskDirty = true;
  5161. this._isDepthFuncDirty = false;
  5162. this._isCullFaceDirty = false;
  5163. this._isCullDirty = false;
  5164. this._isZOffsetDirty = false;
  5165. };
  5166. _DepthCullingState.prototype.apply = function (gl) {
  5167. if (!this.isDirty) {
  5168. return;
  5169. }
  5170. // Cull
  5171. if (this._isCullDirty) {
  5172. if (this.cull) {
  5173. gl.enable(gl.CULL_FACE);
  5174. }
  5175. else {
  5176. gl.disable(gl.CULL_FACE);
  5177. }
  5178. this._isCullDirty = false;
  5179. }
  5180. // Cull face
  5181. if (this._isCullFaceDirty) {
  5182. gl.cullFace(this.cullFace);
  5183. this._isCullFaceDirty = false;
  5184. }
  5185. // Depth mask
  5186. if (this._isDepthMaskDirty) {
  5187. gl.depthMask(this.depthMask);
  5188. this._isDepthMaskDirty = false;
  5189. }
  5190. // Depth test
  5191. if (this._isDepthTestDirty) {
  5192. if (this.depthTest) {
  5193. gl.enable(gl.DEPTH_TEST);
  5194. }
  5195. else {
  5196. gl.disable(gl.DEPTH_TEST);
  5197. }
  5198. this._isDepthTestDirty = false;
  5199. }
  5200. // Depth func
  5201. if (this._isDepthFuncDirty) {
  5202. gl.depthFunc(this.depthFunc);
  5203. this._isDepthFuncDirty = false;
  5204. }
  5205. // zOffset
  5206. if (this._isZOffsetDirty) {
  5207. if (this.zOffset) {
  5208. gl.enable(gl.POLYGON_OFFSET_FILL);
  5209. gl.polygonOffset(this.zOffset, 0);
  5210. }
  5211. else {
  5212. gl.disable(gl.POLYGON_OFFSET_FILL);
  5213. }
  5214. this._isZOffsetDirty = false;
  5215. }
  5216. };
  5217. return _DepthCullingState;
  5218. })();
  5219. BABYLON._DepthCullingState = _DepthCullingState;
  5220. var _AlphaState = (function () {
  5221. function _AlphaState() {
  5222. this._isAlphaBlendDirty = false;
  5223. this._isBlendFunctionParametersDirty = false;
  5224. this._alphaBlend = false;
  5225. this._blendFunctionParameters = new Array(4);
  5226. }
  5227. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5228. get: function () {
  5229. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5230. },
  5231. enumerable: true,
  5232. configurable: true
  5233. });
  5234. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5235. get: function () {
  5236. return this._alphaBlend;
  5237. },
  5238. set: function (value) {
  5239. if (this._alphaBlend === value) {
  5240. return;
  5241. }
  5242. this._alphaBlend = value;
  5243. this._isAlphaBlendDirty = true;
  5244. },
  5245. enumerable: true,
  5246. configurable: true
  5247. });
  5248. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5249. if (this._blendFunctionParameters[0] === value0 &&
  5250. this._blendFunctionParameters[1] === value1 &&
  5251. this._blendFunctionParameters[2] === value2 &&
  5252. this._blendFunctionParameters[3] === value3) {
  5253. return;
  5254. }
  5255. this._blendFunctionParameters[0] = value0;
  5256. this._blendFunctionParameters[1] = value1;
  5257. this._blendFunctionParameters[2] = value2;
  5258. this._blendFunctionParameters[3] = value3;
  5259. this._isBlendFunctionParametersDirty = true;
  5260. };
  5261. _AlphaState.prototype.reset = function () {
  5262. this._alphaBlend = false;
  5263. this._blendFunctionParameters[0] = null;
  5264. this._blendFunctionParameters[1] = null;
  5265. this._blendFunctionParameters[2] = null;
  5266. this._blendFunctionParameters[3] = null;
  5267. this._isAlphaBlendDirty = true;
  5268. this._isBlendFunctionParametersDirty = false;
  5269. };
  5270. _AlphaState.prototype.apply = function (gl) {
  5271. if (!this.isDirty) {
  5272. return;
  5273. }
  5274. // Alpha blend
  5275. if (this._isAlphaBlendDirty) {
  5276. if (this._alphaBlend) {
  5277. gl.enable(gl.BLEND);
  5278. }
  5279. else {
  5280. gl.disable(gl.BLEND);
  5281. }
  5282. this._isAlphaBlendDirty = false;
  5283. }
  5284. // Alpha function
  5285. if (this._isBlendFunctionParametersDirty) {
  5286. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5287. this._isBlendFunctionParametersDirty = false;
  5288. }
  5289. };
  5290. return _AlphaState;
  5291. })();
  5292. BABYLON._AlphaState = _AlphaState;
  5293. var compileShader = function (gl, source, type, defines) {
  5294. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5295. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5296. gl.compileShader(shader);
  5297. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5298. throw new Error(gl.getShaderInfoLog(shader));
  5299. }
  5300. return shader;
  5301. };
  5302. var getWebGLTextureType = function (gl, type) {
  5303. var textureType = gl.UNSIGNED_BYTE;
  5304. if (type === Engine.TEXTURETYPE_FLOAT)
  5305. textureType = gl.FLOAT;
  5306. return textureType;
  5307. };
  5308. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5309. var magFilter = gl.NEAREST;
  5310. var minFilter = gl.NEAREST;
  5311. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5312. magFilter = gl.LINEAR;
  5313. if (generateMipMaps) {
  5314. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5315. }
  5316. else {
  5317. minFilter = gl.LINEAR;
  5318. }
  5319. }
  5320. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5321. magFilter = gl.LINEAR;
  5322. if (generateMipMaps) {
  5323. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5324. }
  5325. else {
  5326. minFilter = gl.LINEAR;
  5327. }
  5328. }
  5329. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5330. magFilter = gl.NEAREST;
  5331. if (generateMipMaps) {
  5332. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5333. }
  5334. else {
  5335. minFilter = gl.NEAREST;
  5336. }
  5337. }
  5338. return {
  5339. min: minFilter,
  5340. mag: magFilter
  5341. };
  5342. };
  5343. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5345. var engine = scene.getEngine();
  5346. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5347. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5348. gl.bindTexture(gl.TEXTURE_2D, texture);
  5349. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5350. texture._baseWidth = width;
  5351. texture._baseHeight = height;
  5352. texture._width = potWidth;
  5353. texture._height = potHeight;
  5354. texture.isReady = true;
  5355. processFunction(potWidth, potHeight);
  5356. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5357. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5358. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5359. if (!noMipmap && !isCompressed) {
  5360. gl.generateMipmap(gl.TEXTURE_2D);
  5361. }
  5362. gl.bindTexture(gl.TEXTURE_2D, null);
  5363. engine._activeTexturesCache = [];
  5364. scene._removePendingData(texture);
  5365. };
  5366. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5367. var onload = function () {
  5368. loadedImages[index] = img;
  5369. loadedImages._internalCount++;
  5370. scene._removePendingData(img);
  5371. if (loadedImages._internalCount === 6) {
  5372. onfinish(loadedImages);
  5373. }
  5374. };
  5375. var onerror = function () {
  5376. scene._removePendingData(img);
  5377. };
  5378. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5379. scene._addPendingData(img);
  5380. };
  5381. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5382. var loadedImages = [];
  5383. loadedImages._internalCount = 0;
  5384. for (var index = 0; index < 6; index++) {
  5385. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5386. }
  5387. };
  5388. var EngineCapabilities = (function () {
  5389. function EngineCapabilities() {
  5390. }
  5391. return EngineCapabilities;
  5392. })();
  5393. BABYLON.EngineCapabilities = EngineCapabilities;
  5394. /**
  5395. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5396. */
  5397. var Engine = (function () {
  5398. /**
  5399. * @constructor
  5400. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5401. * @param {boolean} [antialias] - enable antialias
  5402. * @param options - further options to be sent to the getContext function
  5403. */
  5404. function Engine(canvas, antialias, options) {
  5405. var _this = this;
  5406. // Public members
  5407. this.isFullscreen = false;
  5408. this.isPointerLock = false;
  5409. this.cullBackFaces = true;
  5410. this.renderEvenInBackground = true;
  5411. // To enable/disable IDB support and avoid XHR on .manifest
  5412. this.enableOfflineSupport = true;
  5413. this.scenes = new Array();
  5414. this._windowIsBackground = false;
  5415. this._loadingDivBackgroundColor = "black";
  5416. this._drawCalls = 0;
  5417. this._renderingQueueLaunched = false;
  5418. this._activeRenderLoops = [];
  5419. // FPS
  5420. this.fpsRange = 60;
  5421. this.previousFramesDuration = [];
  5422. this.fps = 60;
  5423. this.deltaTime = 0;
  5424. // States
  5425. this._depthCullingState = new _DepthCullingState();
  5426. this._alphaState = new _AlphaState();
  5427. this._alphaMode = Engine.ALPHA_DISABLE;
  5428. // Cache
  5429. this._loadedTexturesCache = new Array();
  5430. this._activeTexturesCache = new Array();
  5431. this._compiledEffects = {};
  5432. this._uintIndicesCurrentlySet = false;
  5433. this._renderingCanvas = canvas;
  5434. options = options || {};
  5435. options.antialias = antialias;
  5436. if (options.preserveDrawingBuffer === undefined) {
  5437. options.preserveDrawingBuffer = false;
  5438. }
  5439. // GL
  5440. try {
  5441. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5442. }
  5443. catch (e) {
  5444. throw new Error("WebGL not supported");
  5445. }
  5446. if (!this._gl) {
  5447. throw new Error("WebGL not supported");
  5448. }
  5449. this._onBlur = function () {
  5450. _this._windowIsBackground = true;
  5451. };
  5452. this._onFocus = function () {
  5453. _this._windowIsBackground = false;
  5454. };
  5455. window.addEventListener("blur", this._onBlur);
  5456. window.addEventListener("focus", this._onFocus);
  5457. // Viewport
  5458. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5459. this.resize();
  5460. // Caps
  5461. this._caps = new EngineCapabilities();
  5462. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5463. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5464. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5465. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5466. // Infos
  5467. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5468. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5469. if (rendererInfo != null) {
  5470. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5471. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5472. }
  5473. if (!this._glVendor) {
  5474. this._glVendor = "Unknown vendor";
  5475. }
  5476. if (!this._glRenderer) {
  5477. this._glRenderer = "Unknown renderer";
  5478. }
  5479. // Extensions
  5480. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5481. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5482. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5483. 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');
  5484. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5485. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5486. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5487. this._caps.highPrecisionShaderSupported = true;
  5488. if (this._gl.getShaderPrecisionFormat) {
  5489. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5490. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5491. }
  5492. // Depth buffer
  5493. this.setDepthBuffer(true);
  5494. this.setDepthFunctionToLessOrEqual();
  5495. this.setDepthWrite(true);
  5496. // Fullscreen
  5497. this._onFullscreenChange = function () {
  5498. if (document.fullscreen !== undefined) {
  5499. _this.isFullscreen = document.fullscreen;
  5500. }
  5501. else if (document.mozFullScreen !== undefined) {
  5502. _this.isFullscreen = document.mozFullScreen;
  5503. }
  5504. else if (document.webkitIsFullScreen !== undefined) {
  5505. _this.isFullscreen = document.webkitIsFullScreen;
  5506. }
  5507. else if (document.msIsFullScreen !== undefined) {
  5508. _this.isFullscreen = document.msIsFullScreen;
  5509. }
  5510. // Pointer lock
  5511. if (_this.isFullscreen && _this._pointerLockRequested) {
  5512. canvas.requestPointerLock = canvas.requestPointerLock ||
  5513. canvas.msRequestPointerLock ||
  5514. canvas.mozRequestPointerLock ||
  5515. canvas.webkitRequestPointerLock;
  5516. if (canvas.requestPointerLock) {
  5517. canvas.requestPointerLock();
  5518. }
  5519. }
  5520. };
  5521. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5522. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5523. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5524. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5525. // Pointer lock
  5526. this._onPointerLockChange = function () {
  5527. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5528. document.webkitPointerLockElement === canvas ||
  5529. document.msPointerLockElement === canvas ||
  5530. document.pointerLockElement === canvas);
  5531. };
  5532. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5533. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5534. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5535. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5536. if (!Engine.audioEngine) {
  5537. Engine.audioEngine = new BABYLON.AudioEngine();
  5538. }
  5539. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5540. }
  5541. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5542. get: function () {
  5543. return Engine._ALPHA_DISABLE;
  5544. },
  5545. enumerable: true,
  5546. configurable: true
  5547. });
  5548. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5549. get: function () {
  5550. return Engine._ALPHA_ONEONE;
  5551. },
  5552. enumerable: true,
  5553. configurable: true
  5554. });
  5555. Object.defineProperty(Engine, "ALPHA_ADD", {
  5556. get: function () {
  5557. return Engine._ALPHA_ADD;
  5558. },
  5559. enumerable: true,
  5560. configurable: true
  5561. });
  5562. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5563. get: function () {
  5564. return Engine._ALPHA_COMBINE;
  5565. },
  5566. enumerable: true,
  5567. configurable: true
  5568. });
  5569. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5570. get: function () {
  5571. return Engine._ALPHA_SUBTRACT;
  5572. },
  5573. enumerable: true,
  5574. configurable: true
  5575. });
  5576. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5577. get: function () {
  5578. return Engine._ALPHA_MULTIPLY;
  5579. },
  5580. enumerable: true,
  5581. configurable: true
  5582. });
  5583. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5584. get: function () {
  5585. return Engine._ALPHA_MAXIMIZED;
  5586. },
  5587. enumerable: true,
  5588. configurable: true
  5589. });
  5590. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5591. get: function () {
  5592. return Engine._DELAYLOADSTATE_NONE;
  5593. },
  5594. enumerable: true,
  5595. configurable: true
  5596. });
  5597. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5598. get: function () {
  5599. return Engine._DELAYLOADSTATE_LOADED;
  5600. },
  5601. enumerable: true,
  5602. configurable: true
  5603. });
  5604. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5605. get: function () {
  5606. return Engine._DELAYLOADSTATE_LOADING;
  5607. },
  5608. enumerable: true,
  5609. configurable: true
  5610. });
  5611. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5612. get: function () {
  5613. return Engine._DELAYLOADSTATE_NOTLOADED;
  5614. },
  5615. enumerable: true,
  5616. configurable: true
  5617. });
  5618. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5619. get: function () {
  5620. return Engine._TEXTUREFORMAT_ALPHA;
  5621. },
  5622. enumerable: true,
  5623. configurable: true
  5624. });
  5625. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5626. get: function () {
  5627. return Engine._TEXTUREFORMAT_LUMINANCE;
  5628. },
  5629. enumerable: true,
  5630. configurable: true
  5631. });
  5632. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5633. get: function () {
  5634. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5635. },
  5636. enumerable: true,
  5637. configurable: true
  5638. });
  5639. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5640. get: function () {
  5641. return Engine._TEXTUREFORMAT_RGB;
  5642. },
  5643. enumerable: true,
  5644. configurable: true
  5645. });
  5646. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5647. get: function () {
  5648. return Engine._TEXTUREFORMAT_RGBA;
  5649. },
  5650. enumerable: true,
  5651. configurable: true
  5652. });
  5653. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5654. get: function () {
  5655. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5656. },
  5657. enumerable: true,
  5658. configurable: true
  5659. });
  5660. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5661. get: function () {
  5662. return Engine._TEXTURETYPE_FLOAT;
  5663. },
  5664. enumerable: true,
  5665. configurable: true
  5666. });
  5667. Object.defineProperty(Engine, "Version", {
  5668. get: function () {
  5669. return "2.2.0-alpha";
  5670. },
  5671. enumerable: true,
  5672. configurable: true
  5673. });
  5674. Engine.prototype._prepareWorkingCanvas = function () {
  5675. if (this._workingCanvas) {
  5676. return;
  5677. }
  5678. this._workingCanvas = document.createElement("canvas");
  5679. this._workingContext = this._workingCanvas.getContext("2d");
  5680. };
  5681. Engine.prototype.getGlInfo = function () {
  5682. return {
  5683. vendor: this._glVendor,
  5684. renderer: this._glRenderer,
  5685. version: this._glVersion
  5686. };
  5687. };
  5688. Engine.prototype.getAspectRatio = function (camera) {
  5689. var viewport = camera.viewport;
  5690. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5691. };
  5692. Engine.prototype.getRenderWidth = function () {
  5693. if (this._currentRenderTarget) {
  5694. return this._currentRenderTarget._width;
  5695. }
  5696. return this._renderingCanvas.width;
  5697. };
  5698. Engine.prototype.getRenderHeight = function () {
  5699. if (this._currentRenderTarget) {
  5700. return this._currentRenderTarget._height;
  5701. }
  5702. return this._renderingCanvas.height;
  5703. };
  5704. Engine.prototype.getRenderingCanvas = function () {
  5705. return this._renderingCanvas;
  5706. };
  5707. Engine.prototype.getRenderingCanvasClientRect = function () {
  5708. return this._renderingCanvas.getBoundingClientRect();
  5709. };
  5710. Engine.prototype.setHardwareScalingLevel = function (level) {
  5711. this._hardwareScalingLevel = level;
  5712. this.resize();
  5713. };
  5714. Engine.prototype.getHardwareScalingLevel = function () {
  5715. return this._hardwareScalingLevel;
  5716. };
  5717. Engine.prototype.getLoadedTexturesCache = function () {
  5718. return this._loadedTexturesCache;
  5719. };
  5720. Engine.prototype.getCaps = function () {
  5721. return this._caps;
  5722. };
  5723. Object.defineProperty(Engine.prototype, "drawCalls", {
  5724. get: function () {
  5725. return this._drawCalls;
  5726. },
  5727. enumerable: true,
  5728. configurable: true
  5729. });
  5730. // Methods
  5731. Engine.prototype.resetDrawCalls = function () {
  5732. this._drawCalls = 0;
  5733. };
  5734. Engine.prototype.setDepthFunctionToGreater = function () {
  5735. this._depthCullingState.depthFunc = this._gl.GREATER;
  5736. };
  5737. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5738. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5739. };
  5740. Engine.prototype.setDepthFunctionToLess = function () {
  5741. this._depthCullingState.depthFunc = this._gl.LESS;
  5742. };
  5743. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5744. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5745. };
  5746. /**
  5747. * stop executing a render loop function and remove it from the execution array
  5748. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5749. */
  5750. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5751. if (!renderFunction) {
  5752. this._activeRenderLoops = [];
  5753. return;
  5754. }
  5755. var index = this._activeRenderLoops.indexOf(renderFunction);
  5756. if (index >= 0) {
  5757. this._activeRenderLoops.splice(index, 1);
  5758. }
  5759. };
  5760. Engine.prototype._renderLoop = function () {
  5761. var _this = this;
  5762. var shouldRender = true;
  5763. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5764. shouldRender = false;
  5765. }
  5766. if (shouldRender) {
  5767. // Start new frame
  5768. this.beginFrame();
  5769. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5770. var renderFunction = this._activeRenderLoops[index];
  5771. renderFunction();
  5772. }
  5773. // Present
  5774. this.endFrame();
  5775. }
  5776. if (this._activeRenderLoops.length > 0) {
  5777. // Register new frame
  5778. BABYLON.Tools.QueueNewFrame(function () {
  5779. _this._renderLoop();
  5780. });
  5781. }
  5782. else {
  5783. this._renderingQueueLaunched = false;
  5784. }
  5785. };
  5786. /**
  5787. * Register and execute a render loop. The engine can have more than one render function.
  5788. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5789. * @example
  5790. * engine.runRenderLoop(function () {
  5791. * scene.render()
  5792. * })
  5793. */
  5794. Engine.prototype.runRenderLoop = function (renderFunction) {
  5795. var _this = this;
  5796. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5797. return;
  5798. }
  5799. this._activeRenderLoops.push(renderFunction);
  5800. if (!this._renderingQueueLaunched) {
  5801. this._renderingQueueLaunched = true;
  5802. BABYLON.Tools.QueueNewFrame(function () {
  5803. _this._renderLoop();
  5804. });
  5805. }
  5806. };
  5807. /**
  5808. * Toggle full screen mode.
  5809. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5810. */
  5811. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5812. if (this.isFullscreen) {
  5813. BABYLON.Tools.ExitFullscreen();
  5814. }
  5815. else {
  5816. this._pointerLockRequested = requestPointerLock;
  5817. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5818. }
  5819. };
  5820. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5821. this.applyStates();
  5822. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5823. if (this._depthCullingState.depthMask) {
  5824. this._gl.clearDepth(1.0);
  5825. }
  5826. var mode = 0;
  5827. if (backBuffer)
  5828. mode |= this._gl.COLOR_BUFFER_BIT;
  5829. if (depthStencil && this._depthCullingState.depthMask)
  5830. mode |= this._gl.DEPTH_BUFFER_BIT;
  5831. this._gl.clear(mode);
  5832. };
  5833. /**
  5834. * Set the WebGL's viewport
  5835. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5836. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5837. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5838. */
  5839. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5840. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5841. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5842. var x = viewport.x || 0;
  5843. var y = viewport.y || 0;
  5844. this._cachedViewport = viewport;
  5845. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5846. };
  5847. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5848. this._cachedViewport = null;
  5849. this._gl.viewport(x, y, width, height);
  5850. };
  5851. Engine.prototype.beginFrame = function () {
  5852. this._measureFps();
  5853. };
  5854. Engine.prototype.endFrame = function () {
  5855. //this.flushFramebuffer();
  5856. };
  5857. /**
  5858. * resize the view according to the canvas' size.
  5859. * @example
  5860. * window.addEventListener("resize", function () {
  5861. * engine.resize();
  5862. * });
  5863. */
  5864. Engine.prototype.resize = function () {
  5865. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5866. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5867. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5868. };
  5869. /**
  5870. * force a specific size of the canvas
  5871. * @param {number} width - the new canvas' width
  5872. * @param {number} height - the new canvas' height
  5873. */
  5874. Engine.prototype.setSize = function (width, height) {
  5875. this._renderingCanvas.width = width;
  5876. this._renderingCanvas.height = height;
  5877. for (var index = 0; index < this.scenes.length; index++) {
  5878. var scene = this.scenes[index];
  5879. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5880. var cam = scene.cameras[camIndex];
  5881. cam._currentRenderId = 0;
  5882. }
  5883. }
  5884. };
  5885. Engine.prototype.bindFramebuffer = function (texture) {
  5886. this._currentRenderTarget = texture;
  5887. var gl = this._gl;
  5888. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5889. this._gl.viewport(0, 0, texture._width, texture._height);
  5890. this.wipeCaches();
  5891. };
  5892. Engine.prototype.unBindFramebuffer = function (texture) {
  5893. this._currentRenderTarget = null;
  5894. if (texture.generateMipMaps) {
  5895. var gl = this._gl;
  5896. gl.bindTexture(gl.TEXTURE_2D, texture);
  5897. gl.generateMipmap(gl.TEXTURE_2D);
  5898. gl.bindTexture(gl.TEXTURE_2D, null);
  5899. }
  5900. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5901. };
  5902. Engine.prototype.flushFramebuffer = function () {
  5903. this._gl.flush();
  5904. };
  5905. Engine.prototype.restoreDefaultFramebuffer = function () {
  5906. this._currentRenderTarget = null;
  5907. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5908. this.setViewport(this._cachedViewport);
  5909. this.wipeCaches();
  5910. };
  5911. // VBOs
  5912. Engine.prototype._resetVertexBufferBinding = function () {
  5913. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5914. this._cachedVertexBuffers = null;
  5915. };
  5916. Engine.prototype.createVertexBuffer = function (vertices) {
  5917. var vbo = this._gl.createBuffer();
  5918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5919. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5920. this._resetVertexBufferBinding();
  5921. vbo.references = 1;
  5922. return vbo;
  5923. };
  5924. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5925. var vbo = this._gl.createBuffer();
  5926. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5927. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5928. this._resetVertexBufferBinding();
  5929. vbo.references = 1;
  5930. return vbo;
  5931. };
  5932. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5933. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5934. if (offset === undefined) {
  5935. offset = 0;
  5936. }
  5937. if (vertices instanceof Float32Array) {
  5938. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5939. }
  5940. else {
  5941. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5942. }
  5943. this._resetVertexBufferBinding();
  5944. };
  5945. Engine.prototype._resetIndexBufferBinding = function () {
  5946. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5947. this._cachedIndexBuffer = null;
  5948. };
  5949. Engine.prototype.createIndexBuffer = function (indices) {
  5950. var vbo = this._gl.createBuffer();
  5951. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5952. // Check for 32 bits indices
  5953. var arrayBuffer;
  5954. var need32Bits = false;
  5955. if (this._caps.uintIndices) {
  5956. for (var index = 0; index < indices.length; index++) {
  5957. if (indices[index] > 65535) {
  5958. need32Bits = true;
  5959. break;
  5960. }
  5961. }
  5962. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5963. }
  5964. else {
  5965. arrayBuffer = new Uint16Array(indices);
  5966. }
  5967. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5968. this._resetIndexBufferBinding();
  5969. vbo.references = 1;
  5970. vbo.is32Bits = need32Bits;
  5971. return vbo;
  5972. };
  5973. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5974. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5975. this._cachedVertexBuffers = vertexBuffer;
  5976. this._cachedEffectForVertexBuffers = effect;
  5977. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5978. var offset = 0;
  5979. for (var index = 0; index < vertexDeclaration.length; index++) {
  5980. var order = effect.getAttributeLocation(index);
  5981. if (order >= 0) {
  5982. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5983. }
  5984. offset += vertexDeclaration[index] * 4;
  5985. }
  5986. }
  5987. if (this._cachedIndexBuffer !== indexBuffer) {
  5988. this._cachedIndexBuffer = indexBuffer;
  5989. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5990. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5991. }
  5992. };
  5993. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5994. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5995. this._cachedVertexBuffers = vertexBuffers;
  5996. this._cachedEffectForVertexBuffers = effect;
  5997. var attributes = effect.getAttributesNames();
  5998. for (var index = 0; index < attributes.length; index++) {
  5999. var order = effect.getAttributeLocation(index);
  6000. if (order >= 0) {
  6001. var vertexBuffer = vertexBuffers[attributes[index]];
  6002. if (!vertexBuffer) {
  6003. continue;
  6004. }
  6005. var stride = vertexBuffer.getStrideSize();
  6006. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6007. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6008. }
  6009. }
  6010. }
  6011. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6012. this._cachedIndexBuffer = indexBuffer;
  6013. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6014. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6015. }
  6016. };
  6017. Engine.prototype._releaseBuffer = function (buffer) {
  6018. buffer.references--;
  6019. if (buffer.references === 0) {
  6020. this._gl.deleteBuffer(buffer);
  6021. return true;
  6022. }
  6023. return false;
  6024. };
  6025. Engine.prototype.createInstancesBuffer = function (capacity) {
  6026. var buffer = this._gl.createBuffer();
  6027. buffer.capacity = capacity;
  6028. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6029. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6030. return buffer;
  6031. };
  6032. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6033. this._gl.deleteBuffer(buffer);
  6034. };
  6035. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6036. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6037. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6038. for (var index = 0; index < 4; index++) {
  6039. var offsetLocation = offsetLocations[index];
  6040. this._gl.enableVertexAttribArray(offsetLocation);
  6041. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6042. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6043. }
  6044. };
  6045. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6046. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6047. for (var index = 0; index < 4; index++) {
  6048. var offsetLocation = offsetLocations[index];
  6049. this._gl.disableVertexAttribArray(offsetLocation);
  6050. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6051. }
  6052. };
  6053. Engine.prototype.applyStates = function () {
  6054. this._depthCullingState.apply(this._gl);
  6055. this._alphaState.apply(this._gl);
  6056. };
  6057. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6058. // Apply states
  6059. this.applyStates();
  6060. this._drawCalls++;
  6061. // Render
  6062. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6063. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6064. if (instancesCount) {
  6065. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6066. return;
  6067. }
  6068. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6069. };
  6070. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6071. // Apply states
  6072. this.applyStates();
  6073. this._drawCalls++;
  6074. if (instancesCount) {
  6075. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6076. return;
  6077. }
  6078. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6079. };
  6080. // Shaders
  6081. Engine.prototype._releaseEffect = function (effect) {
  6082. if (this._compiledEffects[effect._key]) {
  6083. delete this._compiledEffects[effect._key];
  6084. if (effect.getProgram()) {
  6085. this._gl.deleteProgram(effect.getProgram());
  6086. }
  6087. }
  6088. };
  6089. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6090. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6091. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6092. var name = vertex + "+" + fragment + "@" + defines;
  6093. if (this._compiledEffects[name]) {
  6094. return this._compiledEffects[name];
  6095. }
  6096. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6097. effect._key = name;
  6098. this._compiledEffects[name] = effect;
  6099. return effect;
  6100. };
  6101. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6102. if (uniformsNames === void 0) { uniformsNames = []; }
  6103. if (samplers === void 0) { samplers = []; }
  6104. if (defines === void 0) { defines = ""; }
  6105. return this.createEffect({
  6106. vertex: "particles",
  6107. fragmentElement: fragmentName
  6108. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6109. };
  6110. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6111. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6112. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6113. var shaderProgram = this._gl.createProgram();
  6114. this._gl.attachShader(shaderProgram, vertexShader);
  6115. this._gl.attachShader(shaderProgram, fragmentShader);
  6116. this._gl.linkProgram(shaderProgram);
  6117. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6118. if (!linked) {
  6119. var error = this._gl.getProgramInfoLog(shaderProgram);
  6120. if (error) {
  6121. throw new Error(error);
  6122. }
  6123. }
  6124. this._gl.deleteShader(vertexShader);
  6125. this._gl.deleteShader(fragmentShader);
  6126. return shaderProgram;
  6127. };
  6128. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6129. var results = [];
  6130. for (var index = 0; index < uniformsNames.length; index++) {
  6131. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6132. }
  6133. return results;
  6134. };
  6135. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6136. var results = [];
  6137. for (var index = 0; index < attributesNames.length; index++) {
  6138. try {
  6139. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6140. }
  6141. catch (e) {
  6142. results.push(-1);
  6143. }
  6144. }
  6145. return results;
  6146. };
  6147. Engine.prototype.enableEffect = function (effect) {
  6148. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6149. if (effect && effect.onBind) {
  6150. effect.onBind(effect);
  6151. }
  6152. return;
  6153. }
  6154. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6155. // Use program
  6156. this._gl.useProgram(effect.getProgram());
  6157. for (var i in this._vertexAttribArrays) {
  6158. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6159. continue;
  6160. }
  6161. this._vertexAttribArrays[i] = false;
  6162. this._gl.disableVertexAttribArray(i);
  6163. }
  6164. var attributesCount = effect.getAttributesCount();
  6165. for (var index = 0; index < attributesCount; index++) {
  6166. // Attributes
  6167. var order = effect.getAttributeLocation(index);
  6168. if (order >= 0) {
  6169. this._vertexAttribArrays[order] = true;
  6170. this._gl.enableVertexAttribArray(order);
  6171. }
  6172. }
  6173. this._currentEffect = effect;
  6174. if (effect.onBind) {
  6175. effect.onBind(effect);
  6176. }
  6177. };
  6178. Engine.prototype.setArray = function (uniform, array) {
  6179. if (!uniform)
  6180. return;
  6181. this._gl.uniform1fv(uniform, array);
  6182. };
  6183. Engine.prototype.setArray2 = function (uniform, array) {
  6184. if (!uniform || array.length % 2 !== 0)
  6185. return;
  6186. this._gl.uniform2fv(uniform, array);
  6187. };
  6188. Engine.prototype.setArray3 = function (uniform, array) {
  6189. if (!uniform || array.length % 3 !== 0)
  6190. return;
  6191. this._gl.uniform3fv(uniform, array);
  6192. };
  6193. Engine.prototype.setArray4 = function (uniform, array) {
  6194. if (!uniform || array.length % 4 !== 0)
  6195. return;
  6196. this._gl.uniform4fv(uniform, array);
  6197. };
  6198. Engine.prototype.setMatrices = function (uniform, matrices) {
  6199. if (!uniform)
  6200. return;
  6201. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6202. };
  6203. Engine.prototype.setMatrix = function (uniform, matrix) {
  6204. if (!uniform)
  6205. return;
  6206. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6207. };
  6208. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6209. if (!uniform)
  6210. return;
  6211. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6212. };
  6213. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6214. if (!uniform)
  6215. return;
  6216. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6217. };
  6218. Engine.prototype.setFloat = function (uniform, value) {
  6219. if (!uniform)
  6220. return;
  6221. this._gl.uniform1f(uniform, value);
  6222. };
  6223. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6224. if (!uniform)
  6225. return;
  6226. this._gl.uniform2f(uniform, x, y);
  6227. };
  6228. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6229. if (!uniform)
  6230. return;
  6231. this._gl.uniform3f(uniform, x, y, z);
  6232. };
  6233. Engine.prototype.setBool = function (uniform, bool) {
  6234. if (!uniform)
  6235. return;
  6236. this._gl.uniform1i(uniform, bool);
  6237. };
  6238. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6239. if (!uniform)
  6240. return;
  6241. this._gl.uniform4f(uniform, x, y, z, w);
  6242. };
  6243. Engine.prototype.setColor3 = function (uniform, color3) {
  6244. if (!uniform)
  6245. return;
  6246. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6247. };
  6248. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6249. if (!uniform)
  6250. return;
  6251. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6252. };
  6253. // States
  6254. Engine.prototype.setState = function (culling, zOffset, force) {
  6255. if (zOffset === void 0) { zOffset = 0; }
  6256. // Culling
  6257. if (this._depthCullingState.cull !== culling || force) {
  6258. if (culling) {
  6259. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6260. this._depthCullingState.cull = true;
  6261. }
  6262. else {
  6263. this._depthCullingState.cull = false;
  6264. }
  6265. }
  6266. // Z offset
  6267. this._depthCullingState.zOffset = zOffset;
  6268. };
  6269. Engine.prototype.setDepthBuffer = function (enable) {
  6270. this._depthCullingState.depthTest = enable;
  6271. };
  6272. Engine.prototype.getDepthWrite = function () {
  6273. return this._depthCullingState.depthMask;
  6274. };
  6275. Engine.prototype.setDepthWrite = function (enable) {
  6276. this._depthCullingState.depthMask = enable;
  6277. };
  6278. Engine.prototype.setColorWrite = function (enable) {
  6279. this._gl.colorMask(enable, enable, enable, enable);
  6280. };
  6281. Engine.prototype.setAlphaMode = function (mode) {
  6282. if (this._alphaMode == mode) {
  6283. return;
  6284. }
  6285. switch (mode) {
  6286. case Engine.ALPHA_DISABLE:
  6287. this.setDepthWrite(true);
  6288. this._alphaState.alphaBlend = false;
  6289. break;
  6290. case Engine.ALPHA_COMBINE:
  6291. this.setDepthWrite(false);
  6292. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6293. this._alphaState.alphaBlend = true;
  6294. break;
  6295. case Engine.ALPHA_ONEONE:
  6296. this.setDepthWrite(false);
  6297. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6298. this._alphaState.alphaBlend = true;
  6299. break;
  6300. case Engine.ALPHA_ADD:
  6301. this.setDepthWrite(false);
  6302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6303. this._alphaState.alphaBlend = true;
  6304. break;
  6305. case Engine.ALPHA_SUBTRACT:
  6306. this.setDepthWrite(false);
  6307. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6308. this._alphaState.alphaBlend = true;
  6309. break;
  6310. case Engine.ALPHA_MULTIPLY:
  6311. this.setDepthWrite(false);
  6312. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6313. this._alphaState.alphaBlend = true;
  6314. break;
  6315. case Engine.ALPHA_MAXIMIZED:
  6316. this.setDepthWrite(false);
  6317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6318. this._alphaState.alphaBlend = true;
  6319. break;
  6320. }
  6321. this._alphaMode = mode;
  6322. };
  6323. Engine.prototype.getAlphaMode = function () {
  6324. return this._alphaMode;
  6325. };
  6326. Engine.prototype.setAlphaTesting = function (enable) {
  6327. this._alphaTest = enable;
  6328. };
  6329. Engine.prototype.getAlphaTesting = function () {
  6330. return this._alphaTest;
  6331. };
  6332. // Textures
  6333. Engine.prototype.wipeCaches = function () {
  6334. this._activeTexturesCache = [];
  6335. this._currentEffect = null;
  6336. this._depthCullingState.reset();
  6337. this._alphaState.reset();
  6338. this._cachedVertexBuffers = null;
  6339. this._cachedIndexBuffer = null;
  6340. this._cachedEffectForVertexBuffers = null;
  6341. };
  6342. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6343. var gl = this._gl;
  6344. gl.bindTexture(gl.TEXTURE_2D, texture);
  6345. var magFilter = gl.NEAREST;
  6346. var minFilter = gl.NEAREST;
  6347. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6348. magFilter = gl.LINEAR;
  6349. minFilter = gl.LINEAR;
  6350. }
  6351. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6352. magFilter = gl.LINEAR;
  6353. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6354. }
  6355. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6356. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6357. gl.bindTexture(gl.TEXTURE_2D, null);
  6358. texture.samplingMode = samplingMode;
  6359. };
  6360. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6361. var _this = this;
  6362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6363. if (onLoad === void 0) { onLoad = null; }
  6364. if (onError === void 0) { onError = null; }
  6365. if (buffer === void 0) { buffer = null; }
  6366. var texture = this._gl.createTexture();
  6367. var extension;
  6368. var fromData = false;
  6369. if (url.substr(0, 5) === "data:") {
  6370. fromData = true;
  6371. }
  6372. if (!fromData)
  6373. extension = url.substr(url.length - 4, 4).toLowerCase();
  6374. else {
  6375. var oldUrl = url;
  6376. fromData = oldUrl.split(':');
  6377. url = oldUrl;
  6378. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6379. }
  6380. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6381. var isTGA = (extension === ".tga");
  6382. scene._addPendingData(texture);
  6383. texture.url = url;
  6384. texture.noMipmap = noMipmap;
  6385. texture.references = 1;
  6386. texture.samplingMode = samplingMode;
  6387. this._loadedTexturesCache.push(texture);
  6388. var onerror = function () {
  6389. scene._removePendingData(texture);
  6390. if (onError) {
  6391. onError();
  6392. }
  6393. };
  6394. if (isTGA) {
  6395. var callback = function (arrayBuffer) {
  6396. var data = new Uint8Array(arrayBuffer);
  6397. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6398. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6399. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6400. if (onLoad) {
  6401. onLoad();
  6402. }
  6403. }, samplingMode);
  6404. };
  6405. if (!(fromData instanceof Array))
  6406. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6407. callback(arrayBuffer);
  6408. }, onerror, scene.database, true);
  6409. else
  6410. callback(buffer);
  6411. }
  6412. else if (isDDS) {
  6413. callback = function (data) {
  6414. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6415. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6416. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6417. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6418. if (onLoad) {
  6419. onLoad();
  6420. }
  6421. }, samplingMode);
  6422. };
  6423. if (!(fromData instanceof Array))
  6424. BABYLON.Tools.LoadFile(url, function (data) {
  6425. callback(data);
  6426. }, onerror, scene.database, true);
  6427. else
  6428. callback(buffer);
  6429. }
  6430. else {
  6431. var onload = function (img) {
  6432. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6433. var isPot = (img.width === potWidth && img.height === potHeight);
  6434. if (!isPot) {
  6435. _this._prepareWorkingCanvas();
  6436. _this._workingCanvas.width = potWidth;
  6437. _this._workingCanvas.height = potHeight;
  6438. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6439. _this._workingContext.imageSmoothingEnabled = false;
  6440. _this._workingContext.mozImageSmoothingEnabled = false;
  6441. _this._workingContext.oImageSmoothingEnabled = false;
  6442. _this._workingContext.webkitImageSmoothingEnabled = false;
  6443. _this._workingContext.msImageSmoothingEnabled = false;
  6444. }
  6445. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6446. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6447. _this._workingContext.imageSmoothingEnabled = true;
  6448. _this._workingContext.mozImageSmoothingEnabled = true;
  6449. _this._workingContext.oImageSmoothingEnabled = true;
  6450. _this._workingContext.webkitImageSmoothingEnabled = true;
  6451. _this._workingContext.msImageSmoothingEnabled = true;
  6452. }
  6453. }
  6454. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6455. if (onLoad) {
  6456. onLoad();
  6457. }
  6458. }, samplingMode);
  6459. };
  6460. if (!(fromData instanceof Array))
  6461. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6462. else
  6463. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6464. }
  6465. return texture;
  6466. };
  6467. Engine.prototype.updateRawTexture = function (texture, data, format, invertY) {
  6468. var internalFormat = this._gl.RGBA;
  6469. switch (format) {
  6470. case Engine.TEXTUREFORMAT_ALPHA:
  6471. internalFormat = this._gl.ALPHA;
  6472. break;
  6473. case Engine.TEXTUREFORMAT_LUMINANCE:
  6474. internalFormat = this._gl.LUMINANCE;
  6475. break;
  6476. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6477. internalFormat = this._gl.LUMINANCE_ALPHA;
  6478. break;
  6479. case Engine.TEXTUREFORMAT_RGB:
  6480. internalFormat = this._gl.RGB;
  6481. break;
  6482. case Engine.TEXTUREFORMAT_RGBA:
  6483. internalFormat = this._gl.RGBA;
  6484. break;
  6485. }
  6486. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6487. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6488. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6489. if (texture.generateMipMaps) {
  6490. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6491. }
  6492. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6493. this._activeTexturesCache = [];
  6494. texture.isReady = true;
  6495. };
  6496. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6497. var texture = this._gl.createTexture();
  6498. texture._baseWidth = width;
  6499. texture._baseHeight = height;
  6500. texture._width = width;
  6501. texture._height = height;
  6502. texture.references = 1;
  6503. this.updateRawTexture(texture, data, format, invertY);
  6504. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6505. // Filters
  6506. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6507. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6509. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6510. texture.samplingMode = samplingMode;
  6511. this._loadedTexturesCache.push(texture);
  6512. return texture;
  6513. };
  6514. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6515. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6516. var texture = this._gl.createTexture();
  6517. texture._baseWidth = width;
  6518. texture._baseHeight = height;
  6519. if (forceExponantOfTwo) {
  6520. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6521. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6522. }
  6523. this._activeTexturesCache = [];
  6524. texture._width = width;
  6525. texture._height = height;
  6526. texture.isReady = false;
  6527. texture.generateMipMaps = generateMipMaps;
  6528. texture.references = 1;
  6529. texture.samplingMode = samplingMode;
  6530. this.updateTextureSamplingMode(samplingMode, texture);
  6531. this._loadedTexturesCache.push(texture);
  6532. return texture;
  6533. };
  6534. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6535. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6536. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6537. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6538. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6539. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6540. };
  6541. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6542. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6543. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6544. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6545. if (texture.generateMipMaps) {
  6546. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6547. }
  6548. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6549. this._activeTexturesCache = [];
  6550. texture.isReady = true;
  6551. };
  6552. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6553. if (texture._isDisabled) {
  6554. return;
  6555. }
  6556. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6557. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6558. try {
  6559. // Testing video texture support
  6560. if (this._videoTextureSupported === undefined) {
  6561. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6562. if (this._gl.getError() !== 0) {
  6563. this._videoTextureSupported = false;
  6564. }
  6565. else {
  6566. this._videoTextureSupported = true;
  6567. }
  6568. }
  6569. // Copy video through the current working canvas if video texture is not supported
  6570. if (!this._videoTextureSupported) {
  6571. if (!texture._workingCanvas) {
  6572. texture._workingCanvas = document.createElement("canvas");
  6573. texture._workingContext = texture._workingCanvas.getContext("2d");
  6574. texture._workingCanvas.width = texture._width;
  6575. texture._workingCanvas.height = texture._height;
  6576. }
  6577. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6578. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6579. }
  6580. else {
  6581. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6582. }
  6583. if (texture.generateMipMaps) {
  6584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6585. }
  6586. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6587. this._activeTexturesCache = [];
  6588. texture.isReady = true;
  6589. }
  6590. catch (ex) {
  6591. // Something unexpected
  6592. // Let's disable the texture
  6593. texture._isDisabled = true;
  6594. }
  6595. };
  6596. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6597. // old version had a "generateMipMaps" arg instead of options.
  6598. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6599. // in the same way, generateDepthBuffer is defaulted to true
  6600. var generateMipMaps = false;
  6601. var generateDepthBuffer = true;
  6602. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6603. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6604. if (options !== undefined) {
  6605. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6606. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6607. type = options.type === undefined ? type : options.type;
  6608. if (options.samplingMode !== undefined) {
  6609. samplingMode = options.samplingMode;
  6610. }
  6611. if (type === Engine.TEXTURETYPE_FLOAT) {
  6612. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6613. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6614. }
  6615. }
  6616. var gl = this._gl;
  6617. var texture = gl.createTexture();
  6618. gl.bindTexture(gl.TEXTURE_2D, texture);
  6619. var width = size.width || size;
  6620. var height = size.height || size;
  6621. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6622. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6623. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6624. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6625. }
  6626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6630. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6631. var depthBuffer;
  6632. // Create the depth buffer
  6633. if (generateDepthBuffer) {
  6634. depthBuffer = gl.createRenderbuffer();
  6635. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6636. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6637. }
  6638. // Create the framebuffer
  6639. var framebuffer = gl.createFramebuffer();
  6640. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6641. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6642. if (generateDepthBuffer) {
  6643. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6644. }
  6645. if (generateMipMaps) {
  6646. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6647. }
  6648. // Unbind
  6649. gl.bindTexture(gl.TEXTURE_2D, null);
  6650. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6651. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6652. texture._framebuffer = framebuffer;
  6653. if (generateDepthBuffer) {
  6654. texture._depthBuffer = depthBuffer;
  6655. }
  6656. texture._width = width;
  6657. texture._height = height;
  6658. texture.isReady = true;
  6659. texture.generateMipMaps = generateMipMaps;
  6660. texture.references = 1;
  6661. texture.samplingMode = samplingMode;
  6662. this._activeTexturesCache = [];
  6663. this._loadedTexturesCache.push(texture);
  6664. return texture;
  6665. };
  6666. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6667. var _this = this;
  6668. var gl = this._gl;
  6669. var texture = gl.createTexture();
  6670. texture.isCube = true;
  6671. texture.url = rootUrl;
  6672. texture.references = 1;
  6673. this._loadedTexturesCache.push(texture);
  6674. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6675. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6676. if (isDDS) {
  6677. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6678. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6679. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6680. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6681. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6682. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6683. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6684. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6685. }
  6686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6690. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6691. _this._activeTexturesCache = [];
  6692. texture._width = info.width;
  6693. texture._height = info.height;
  6694. texture.isReady = true;
  6695. }, null, null, true);
  6696. }
  6697. else {
  6698. cascadeLoad(rootUrl, scene, function (imgs) {
  6699. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6700. var height = width;
  6701. _this._prepareWorkingCanvas();
  6702. _this._workingCanvas.width = width;
  6703. _this._workingCanvas.height = height;
  6704. var faces = [
  6705. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6706. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6707. ];
  6708. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6709. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6710. for (var index = 0; index < faces.length; index++) {
  6711. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6712. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6713. }
  6714. if (!noMipmap) {
  6715. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6716. }
  6717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6721. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6722. _this._activeTexturesCache = [];
  6723. texture._width = width;
  6724. texture._height = height;
  6725. texture.isReady = true;
  6726. }, extensions);
  6727. }
  6728. return texture;
  6729. };
  6730. Engine.prototype._releaseTexture = function (texture) {
  6731. var gl = this._gl;
  6732. if (texture._framebuffer) {
  6733. gl.deleteFramebuffer(texture._framebuffer);
  6734. }
  6735. if (texture._depthBuffer) {
  6736. gl.deleteRenderbuffer(texture._depthBuffer);
  6737. }
  6738. gl.deleteTexture(texture);
  6739. // Unbind channels
  6740. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6741. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6742. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6743. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6744. this._activeTexturesCache[channel] = null;
  6745. }
  6746. var index = this._loadedTexturesCache.indexOf(texture);
  6747. if (index !== -1) {
  6748. this._loadedTexturesCache.splice(index, 1);
  6749. }
  6750. };
  6751. Engine.prototype.bindSamplers = function (effect) {
  6752. this._gl.useProgram(effect.getProgram());
  6753. var samplers = effect.getSamplers();
  6754. for (var index = 0; index < samplers.length; index++) {
  6755. var uniform = effect.getUniform(samplers[index]);
  6756. this._gl.uniform1i(uniform, index);
  6757. }
  6758. this._currentEffect = null;
  6759. };
  6760. Engine.prototype._bindTexture = function (channel, texture) {
  6761. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6762. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6763. this._activeTexturesCache[channel] = null;
  6764. };
  6765. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6766. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6767. };
  6768. Engine.prototype.setTexture = function (channel, texture) {
  6769. if (channel < 0) {
  6770. return;
  6771. }
  6772. // Not ready?
  6773. if (!texture || !texture.isReady()) {
  6774. if (this._activeTexturesCache[channel] != null) {
  6775. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6776. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6777. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6778. this._activeTexturesCache[channel] = null;
  6779. }
  6780. return;
  6781. }
  6782. // Video
  6783. if (texture instanceof BABYLON.VideoTexture) {
  6784. if (texture.update()) {
  6785. this._activeTexturesCache[channel] = null;
  6786. }
  6787. }
  6788. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6789. texture.delayLoad();
  6790. return;
  6791. }
  6792. if (this._activeTexturesCache[channel] === texture) {
  6793. return;
  6794. }
  6795. this._activeTexturesCache[channel] = texture;
  6796. var internalTexture = texture.getInternalTexture();
  6797. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6798. if (internalTexture.isCube) {
  6799. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6800. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6801. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6802. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6803. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6804. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6805. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6806. }
  6807. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6808. }
  6809. else {
  6810. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6811. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6812. internalTexture._cachedWrapU = texture.wrapU;
  6813. switch (texture.wrapU) {
  6814. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6815. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6816. break;
  6817. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6818. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6819. break;
  6820. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6821. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6822. break;
  6823. }
  6824. }
  6825. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6826. internalTexture._cachedWrapV = texture.wrapV;
  6827. switch (texture.wrapV) {
  6828. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6829. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6830. break;
  6831. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6832. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6833. break;
  6834. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6835. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6836. break;
  6837. }
  6838. }
  6839. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6840. }
  6841. };
  6842. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6843. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6844. var value = texture.anisotropicFilteringLevel;
  6845. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6846. value = 1;
  6847. }
  6848. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6849. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6850. texture._cachedAnisotropicFilteringLevel = value;
  6851. }
  6852. };
  6853. Engine.prototype.readPixels = function (x, y, width, height) {
  6854. var data = new Uint8Array(height * width * 4);
  6855. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6856. return data;
  6857. };
  6858. // Dispose
  6859. Engine.prototype.dispose = function () {
  6860. this.hideLoadingUI();
  6861. this.stopRenderLoop();
  6862. // Release scenes
  6863. while (this.scenes.length) {
  6864. this.scenes[0].dispose();
  6865. }
  6866. // Release audio engine
  6867. Engine.audioEngine.dispose();
  6868. // Release effects
  6869. for (var name in this._compiledEffects) {
  6870. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6871. }
  6872. // Unbind
  6873. for (var i in this._vertexAttribArrays) {
  6874. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6875. continue;
  6876. }
  6877. this._gl.disableVertexAttribArray(i);
  6878. }
  6879. this._gl = null;
  6880. // Events
  6881. window.removeEventListener("blur", this._onBlur);
  6882. window.removeEventListener("focus", this._onFocus);
  6883. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6884. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6885. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6886. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6887. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6888. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6889. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6890. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6891. };
  6892. // Loading screen
  6893. Engine.prototype.displayLoadingUI = function () {
  6894. var _this = this;
  6895. this._loadingDiv = document.createElement("div");
  6896. this._loadingDiv.style.opacity = "0";
  6897. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6898. // Loading text
  6899. this._loadingTextDiv = document.createElement("div");
  6900. this._loadingTextDiv.style.position = "absolute";
  6901. this._loadingTextDiv.style.left = "0";
  6902. this._loadingTextDiv.style.top = "50%";
  6903. this._loadingTextDiv.style.marginTop = "80px";
  6904. this._loadingTextDiv.style.width = "100%";
  6905. this._loadingTextDiv.style.height = "20px";
  6906. this._loadingTextDiv.style.fontFamily = "Arial";
  6907. this._loadingTextDiv.style.fontSize = "14px";
  6908. this._loadingTextDiv.style.color = "white";
  6909. this._loadingTextDiv.style.textAlign = "center";
  6910. this._loadingTextDiv.innerHTML = "Loading";
  6911. this._loadingDiv.appendChild(this._loadingTextDiv);
  6912. // Loading img
  6913. var imgBack = new Image();
  6914. 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==";
  6915. imgBack.style.position = "absolute";
  6916. imgBack.style.left = "50%";
  6917. imgBack.style.top = "50%";
  6918. imgBack.style.marginLeft = "-50px";
  6919. imgBack.style.marginTop = "-50px";
  6920. imgBack.style.transition = "transform 1.0s ease";
  6921. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6922. var deg = 360;
  6923. var onTransitionEnd = function () {
  6924. deg += 360;
  6925. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6926. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6927. };
  6928. imgBack.addEventListener("transitionend", onTransitionEnd);
  6929. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6930. this._loadingDiv.appendChild(imgBack);
  6931. // front image
  6932. var imgFront = new Image();
  6933. 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=";
  6934. imgFront.style.position = "absolute";
  6935. imgFront.style.left = "50%";
  6936. imgFront.style.top = "50%";
  6937. imgFront.style.marginLeft = "-50px";
  6938. imgFront.style.marginTop = "-50px";
  6939. this._loadingDiv.appendChild(imgFront);
  6940. // Resize
  6941. this._resizeLoadingUI = function () {
  6942. var canvasRect = _this.getRenderingCanvasClientRect();
  6943. _this._loadingDiv.style.position = "absolute";
  6944. _this._loadingDiv.style.left = canvasRect.left + "px";
  6945. _this._loadingDiv.style.top = canvasRect.top + "px";
  6946. _this._loadingDiv.style.width = canvasRect.width + "px";
  6947. _this._loadingDiv.style.height = canvasRect.height + "px";
  6948. };
  6949. this._resizeLoadingUI();
  6950. window.addEventListener("resize", this._resizeLoadingUI);
  6951. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6952. document.body.appendChild(this._loadingDiv);
  6953. setTimeout(function () {
  6954. _this._loadingDiv.style.opacity = "1";
  6955. imgBack.style.transform = "rotateZ(360deg)";
  6956. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6957. }, 0);
  6958. };
  6959. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6960. set: function (text) {
  6961. if (!this._loadingDiv) {
  6962. return;
  6963. }
  6964. this._loadingTextDiv.innerHTML = text;
  6965. },
  6966. enumerable: true,
  6967. configurable: true
  6968. });
  6969. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6970. get: function () {
  6971. return this._loadingDivBackgroundColor;
  6972. },
  6973. set: function (color) {
  6974. this._loadingDivBackgroundColor = color;
  6975. if (!this._loadingDiv) {
  6976. return;
  6977. }
  6978. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6979. },
  6980. enumerable: true,
  6981. configurable: true
  6982. });
  6983. Engine.prototype.hideLoadingUI = function () {
  6984. var _this = this;
  6985. if (!this._loadingDiv) {
  6986. return;
  6987. }
  6988. var onTransitionEnd = function () {
  6989. if (!_this._loadingDiv) {
  6990. return;
  6991. }
  6992. document.body.removeChild(_this._loadingDiv);
  6993. window.removeEventListener("resize", _this._resizeLoadingUI);
  6994. _this._loadingDiv = null;
  6995. };
  6996. this._loadingDiv.style.opacity = "0";
  6997. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6998. };
  6999. // FPS
  7000. Engine.prototype.getFps = function () {
  7001. return this.fps;
  7002. };
  7003. Engine.prototype.getDeltaTime = function () {
  7004. return this.deltaTime;
  7005. };
  7006. Engine.prototype._measureFps = function () {
  7007. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7008. var length = this.previousFramesDuration.length;
  7009. if (length >= 2) {
  7010. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7011. }
  7012. if (length >= this.fpsRange) {
  7013. if (length > this.fpsRange) {
  7014. this.previousFramesDuration.splice(0, 1);
  7015. length = this.previousFramesDuration.length;
  7016. }
  7017. var sum = 0;
  7018. for (var id = 0; id < length - 1; id++) {
  7019. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7020. }
  7021. this.fps = 1000.0 / (sum / (length - 1));
  7022. }
  7023. };
  7024. // Statics
  7025. Engine.isSupported = function () {
  7026. try {
  7027. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7028. if (navigator.isCocoonJS) {
  7029. return true;
  7030. }
  7031. var tempcanvas = document.createElement("canvas");
  7032. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7033. return gl != null && !!window.WebGLRenderingContext;
  7034. }
  7035. catch (e) {
  7036. return false;
  7037. }
  7038. };
  7039. // Const statics
  7040. Engine._ALPHA_DISABLE = 0;
  7041. Engine._ALPHA_ADD = 1;
  7042. Engine._ALPHA_COMBINE = 2;
  7043. Engine._ALPHA_SUBTRACT = 3;
  7044. Engine._ALPHA_MULTIPLY = 4;
  7045. Engine._ALPHA_MAXIMIZED = 5;
  7046. Engine._ALPHA_ONEONE = 6;
  7047. Engine._DELAYLOADSTATE_NONE = 0;
  7048. Engine._DELAYLOADSTATE_LOADED = 1;
  7049. Engine._DELAYLOADSTATE_LOADING = 2;
  7050. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7051. Engine._TEXTUREFORMAT_ALPHA = 0;
  7052. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7053. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7054. Engine._TEXTUREFORMAT_RGB = 4;
  7055. Engine._TEXTUREFORMAT_RGBA = 4;
  7056. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7057. Engine._TEXTURETYPE_FLOAT = 1;
  7058. // Updatable statics so stick with vars here
  7059. Engine.Epsilon = 0.001;
  7060. Engine.CollisionsEpsilon = 0.001;
  7061. Engine.CodeRepository = "src/";
  7062. Engine.ShadersRepository = "src/Shaders/";
  7063. return Engine;
  7064. })();
  7065. BABYLON.Engine = Engine;
  7066. })(BABYLON || (BABYLON = {}));
  7067. var BABYLON;
  7068. (function (BABYLON) {
  7069. /**
  7070. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7071. */
  7072. var Node = (function () {
  7073. /**
  7074. * @constructor
  7075. * @param {string} name - the name and id to be given to this node
  7076. * @param {BABYLON.Scene} the scene this node will be added to
  7077. */
  7078. function Node(name, scene) {
  7079. this.state = "";
  7080. this.animations = new Array();
  7081. this._childrenFlag = -1;
  7082. this._isEnabled = true;
  7083. this._isReady = true;
  7084. this._currentRenderId = -1;
  7085. this._parentRenderId = -1;
  7086. this.name = name;
  7087. this.id = name;
  7088. this._scene = scene;
  7089. this._initCache();
  7090. }
  7091. Node.prototype.getScene = function () {
  7092. return this._scene;
  7093. };
  7094. Node.prototype.getEngine = function () {
  7095. return this._scene.getEngine();
  7096. };
  7097. // override it in derived class
  7098. Node.prototype.getWorldMatrix = function () {
  7099. return BABYLON.Matrix.Identity();
  7100. };
  7101. // override it in derived class if you add new variables to the cache
  7102. // and call the parent class method
  7103. Node.prototype._initCache = function () {
  7104. this._cache = {};
  7105. this._cache.parent = undefined;
  7106. };
  7107. Node.prototype.updateCache = function (force) {
  7108. if (!force && this.isSynchronized())
  7109. return;
  7110. this._cache.parent = this.parent;
  7111. this._updateCache();
  7112. };
  7113. // override it in derived class if you add new variables to the cache
  7114. // and call the parent class method if !ignoreParentClass
  7115. Node.prototype._updateCache = function (ignoreParentClass) {
  7116. };
  7117. // override it in derived class if you add new variables to the cache
  7118. Node.prototype._isSynchronized = function () {
  7119. return true;
  7120. };
  7121. Node.prototype._markSyncedWithParent = function () {
  7122. this._parentRenderId = this.parent._currentRenderId;
  7123. };
  7124. Node.prototype.isSynchronizedWithParent = function () {
  7125. if (!this.parent) {
  7126. return true;
  7127. }
  7128. if (this._parentRenderId !== this.parent._currentRenderId) {
  7129. return false;
  7130. }
  7131. return this.parent.isSynchronized();
  7132. };
  7133. Node.prototype.isSynchronized = function (updateCache) {
  7134. var check = this.hasNewParent();
  7135. check = check || !this.isSynchronizedWithParent();
  7136. check = check || !this._isSynchronized();
  7137. if (updateCache)
  7138. this.updateCache(true);
  7139. return !check;
  7140. };
  7141. Node.prototype.hasNewParent = function (update) {
  7142. if (this._cache.parent === this.parent)
  7143. return false;
  7144. if (update)
  7145. this._cache.parent = this.parent;
  7146. return true;
  7147. };
  7148. /**
  7149. * Is this node ready to be used/rendered
  7150. * @return {boolean} is it ready
  7151. */
  7152. Node.prototype.isReady = function () {
  7153. return this._isReady;
  7154. };
  7155. /**
  7156. * Is this node enabled.
  7157. * If the node has a parent and is enabled, the parent will be inspected as well.
  7158. * @return {boolean} whether this node (and its parent) is enabled.
  7159. * @see setEnabled
  7160. */
  7161. Node.prototype.isEnabled = function () {
  7162. if (!this._isEnabled) {
  7163. return false;
  7164. }
  7165. if (this.parent) {
  7166. return this.parent.isEnabled();
  7167. }
  7168. return true;
  7169. };
  7170. /**
  7171. * Set the enabled state of this node.
  7172. * @param {boolean} value - the new enabled state
  7173. * @see isEnabled
  7174. */
  7175. Node.prototype.setEnabled = function (value) {
  7176. this._isEnabled = value;
  7177. };
  7178. /**
  7179. * Is this node a descendant of the given node.
  7180. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7181. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7182. * @see parent
  7183. */
  7184. Node.prototype.isDescendantOf = function (ancestor) {
  7185. if (this.parent) {
  7186. if (this.parent === ancestor) {
  7187. return true;
  7188. }
  7189. return this.parent.isDescendantOf(ancestor);
  7190. }
  7191. return false;
  7192. };
  7193. Node.prototype._getDescendants = function (list, results) {
  7194. for (var index = 0; index < list.length; index++) {
  7195. var item = list[index];
  7196. if (item.isDescendantOf(this)) {
  7197. results.push(item);
  7198. }
  7199. }
  7200. };
  7201. /**
  7202. * Will return all nodes that have this node as parent.
  7203. * @return {BABYLON.Node[]} all children nodes of all types.
  7204. */
  7205. Node.prototype.getDescendants = function () {
  7206. var results = [];
  7207. this._getDescendants(this._scene.meshes, results);
  7208. this._getDescendants(this._scene.lights, results);
  7209. this._getDescendants(this._scene.cameras, results);
  7210. return results;
  7211. };
  7212. Node.prototype._setReady = function (state) {
  7213. if (state == this._isReady) {
  7214. return;
  7215. }
  7216. if (!state) {
  7217. this._isReady = false;
  7218. return;
  7219. }
  7220. this._isReady = true;
  7221. if (this.onReady) {
  7222. this.onReady(this);
  7223. }
  7224. };
  7225. return Node;
  7226. })();
  7227. BABYLON.Node = Node;
  7228. })(BABYLON || (BABYLON = {}));
  7229. var BABYLON;
  7230. (function (BABYLON) {
  7231. var FilesInput = (function () {
  7232. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7233. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7234. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7235. this._engine = p_engine;
  7236. this._canvas = p_canvas;
  7237. this._currentScene = p_scene;
  7238. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7239. this._progressCallback = p_progressCallback;
  7240. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7241. this._textureLoadingCallback = p_textureLoadingCallback;
  7242. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7243. }
  7244. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7245. var _this = this;
  7246. if (p_elementToMonitor) {
  7247. this._elementToMonitor = p_elementToMonitor;
  7248. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7249. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7250. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7251. }
  7252. };
  7253. FilesInput.prototype.renderFunction = function () {
  7254. if (this._additionnalRenderLoopLogicCallback) {
  7255. this._additionnalRenderLoopLogicCallback();
  7256. }
  7257. if (this._currentScene) {
  7258. if (this._textureLoadingCallback) {
  7259. var remaining = this._currentScene.getWaitingItemsCount();
  7260. if (remaining > 0) {
  7261. this._textureLoadingCallback(remaining);
  7262. }
  7263. }
  7264. this._currentScene.render();
  7265. }
  7266. };
  7267. FilesInput.prototype.drag = function (e) {
  7268. e.stopPropagation();
  7269. e.preventDefault();
  7270. };
  7271. FilesInput.prototype.drop = function (eventDrop) {
  7272. eventDrop.stopPropagation();
  7273. eventDrop.preventDefault();
  7274. this.loadFiles(eventDrop);
  7275. };
  7276. FilesInput.prototype.loadFiles = function (event) {
  7277. if (this._startingProcessingFilesCallback)
  7278. this._startingProcessingFilesCallback();
  7279. // Handling data transfer via drag'n'drop
  7280. if (event && event.dataTransfer && event.dataTransfer.files) {
  7281. this._filesToLoad = event.dataTransfer.files;
  7282. }
  7283. // Handling files from input files
  7284. if (event && event.target && event.target.files) {
  7285. this._filesToLoad = event.target.files;
  7286. }
  7287. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7288. for (var i = 0; i < this._filesToLoad.length; i++) {
  7289. switch (this._filesToLoad[i].type) {
  7290. case "image/jpeg":
  7291. case "image/png":
  7292. case "image/bmp":
  7293. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7294. break;
  7295. case "image/targa":
  7296. case "image/vnd.ms-dds":
  7297. case "audio/wav":
  7298. case "audio/x-wav":
  7299. case "audio/mp3":
  7300. case "audio/mpeg":
  7301. case "audio/mpeg3":
  7302. case "audio/x-mpeg-3":
  7303. case "audio/ogg":
  7304. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7305. break;
  7306. default:
  7307. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7308. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7309. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7310. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7311. this._sceneFileToLoad = this._filesToLoad[i];
  7312. }
  7313. break;
  7314. }
  7315. }
  7316. this.reload();
  7317. }
  7318. };
  7319. FilesInput.prototype.reload = function () {
  7320. var _this = this;
  7321. var that = this;
  7322. // If a ".babylon" file has been provided
  7323. if (this._sceneFileToLoad) {
  7324. if (this._currentScene) {
  7325. if (BABYLON.Tools.errorsCount > 0) {
  7326. BABYLON.Tools.ClearLogCache();
  7327. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7328. }
  7329. this._engine.stopRenderLoop();
  7330. this._currentScene.dispose();
  7331. }
  7332. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7333. that._currentScene = newScene;
  7334. // Wait for textures and shaders to be ready
  7335. that._currentScene.executeWhenReady(function () {
  7336. // Attach camera to canvas inputs
  7337. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7338. that._currentScene.createDefaultCameraOrLight();
  7339. }
  7340. that._currentScene.activeCamera.attachControl(that._canvas);
  7341. if (that._sceneLoadedCallback) {
  7342. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7343. }
  7344. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7345. });
  7346. }, function (progress) {
  7347. if (_this._progressCallback) {
  7348. _this._progressCallback(progress);
  7349. }
  7350. });
  7351. }
  7352. else {
  7353. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7354. }
  7355. };
  7356. FilesInput.FilesTextures = new Array();
  7357. FilesInput.FilesToLoad = new Array();
  7358. return FilesInput;
  7359. })();
  7360. BABYLON.FilesInput = FilesInput;
  7361. })(BABYLON || (BABYLON = {}));
  7362. var BABYLON;
  7363. (function (BABYLON) {
  7364. var IntersectionInfo = (function () {
  7365. function IntersectionInfo(bu, bv, distance) {
  7366. this.bu = bu;
  7367. this.bv = bv;
  7368. this.distance = distance;
  7369. this.faceId = 0;
  7370. this.subMeshId = 0;
  7371. }
  7372. return IntersectionInfo;
  7373. })();
  7374. BABYLON.IntersectionInfo = IntersectionInfo;
  7375. var PickingInfo = (function () {
  7376. function PickingInfo() {
  7377. this.hit = false;
  7378. this.distance = 0;
  7379. this.pickedPoint = null;
  7380. this.pickedMesh = null;
  7381. this.bu = 0;
  7382. this.bv = 0;
  7383. this.faceId = -1;
  7384. this.subMeshId = 0;
  7385. }
  7386. // Methods
  7387. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7388. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7389. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7390. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7391. return null;
  7392. }
  7393. var indices = this.pickedMesh.getIndices();
  7394. var result;
  7395. if (useVerticesNormals) {
  7396. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7397. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7398. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7399. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7400. normal0 = normal0.scale(this.bu);
  7401. normal1 = normal1.scale(this.bv);
  7402. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7403. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7404. }
  7405. else {
  7406. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7407. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7408. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7409. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7410. var p1p2 = vertex1.subtract(vertex2);
  7411. var p3p2 = vertex3.subtract(vertex2);
  7412. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7413. }
  7414. if (useWorldCoordinates) {
  7415. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7416. }
  7417. return BABYLON.Vector3.Normalize(result);
  7418. };
  7419. PickingInfo.prototype.getTextureCoordinates = function () {
  7420. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7421. return null;
  7422. }
  7423. var indices = this.pickedMesh.getIndices();
  7424. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7425. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7426. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7427. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7428. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7429. uv1 = uv1.scale(this.bu);
  7430. uv2 = uv2.scale(this.bv);
  7431. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7432. };
  7433. return PickingInfo;
  7434. })();
  7435. BABYLON.PickingInfo = PickingInfo;
  7436. })(BABYLON || (BABYLON = {}));
  7437. var BABYLON;
  7438. (function (BABYLON) {
  7439. var BoundingSphere = (function () {
  7440. function BoundingSphere(minimum, maximum) {
  7441. this.minimum = minimum;
  7442. this.maximum = maximum;
  7443. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7444. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7445. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7446. this.radius = distance * 0.5;
  7447. this.centerWorld = BABYLON.Vector3.Zero();
  7448. this._update(BABYLON.Matrix.Identity());
  7449. }
  7450. // Methods
  7451. BoundingSphere.prototype._update = function (world) {
  7452. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7453. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7454. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7455. };
  7456. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7457. for (var i = 0; i < 6; i++) {
  7458. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7459. return false;
  7460. }
  7461. return true;
  7462. };
  7463. BoundingSphere.prototype.intersectsPoint = function (point) {
  7464. var x = this.centerWorld.x - point.x;
  7465. var y = this.centerWorld.y - point.y;
  7466. var z = this.centerWorld.z - point.z;
  7467. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7468. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7469. return false;
  7470. return true;
  7471. };
  7472. // Statics
  7473. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7474. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7475. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7476. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7477. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7478. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7479. return false;
  7480. return true;
  7481. };
  7482. return BoundingSphere;
  7483. })();
  7484. BABYLON.BoundingSphere = BoundingSphere;
  7485. })(BABYLON || (BABYLON = {}));
  7486. var BABYLON;
  7487. (function (BABYLON) {
  7488. var BoundingBox = (function () {
  7489. function BoundingBox(minimum, maximum) {
  7490. this.minimum = minimum;
  7491. this.maximum = maximum;
  7492. this.vectors = new Array();
  7493. this.vectorsWorld = new Array();
  7494. // Bounding vectors
  7495. this.vectors.push(this.minimum.clone());
  7496. this.vectors.push(this.maximum.clone());
  7497. this.vectors.push(this.minimum.clone());
  7498. this.vectors[2].x = this.maximum.x;
  7499. this.vectors.push(this.minimum.clone());
  7500. this.vectors[3].y = this.maximum.y;
  7501. this.vectors.push(this.minimum.clone());
  7502. this.vectors[4].z = this.maximum.z;
  7503. this.vectors.push(this.maximum.clone());
  7504. this.vectors[5].z = this.minimum.z;
  7505. this.vectors.push(this.maximum.clone());
  7506. this.vectors[6].x = this.minimum.x;
  7507. this.vectors.push(this.maximum.clone());
  7508. this.vectors[7].y = this.minimum.y;
  7509. // OBB
  7510. this.center = this.maximum.add(this.minimum).scale(0.5);
  7511. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7512. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7513. // World
  7514. for (var index = 0; index < this.vectors.length; index++) {
  7515. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7516. }
  7517. this.minimumWorld = BABYLON.Vector3.Zero();
  7518. this.maximumWorld = BABYLON.Vector3.Zero();
  7519. this._update(BABYLON.Matrix.Identity());
  7520. }
  7521. // Methods
  7522. BoundingBox.prototype.getWorldMatrix = function () {
  7523. return this._worldMatrix;
  7524. };
  7525. BoundingBox.prototype._update = function (world) {
  7526. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7527. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7528. for (var index = 0; index < this.vectors.length; index++) {
  7529. var v = this.vectorsWorld[index];
  7530. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7531. if (v.x < this.minimumWorld.x)
  7532. this.minimumWorld.x = v.x;
  7533. if (v.y < this.minimumWorld.y)
  7534. this.minimumWorld.y = v.y;
  7535. if (v.z < this.minimumWorld.z)
  7536. this.minimumWorld.z = v.z;
  7537. if (v.x > this.maximumWorld.x)
  7538. this.maximumWorld.x = v.x;
  7539. if (v.y > this.maximumWorld.y)
  7540. this.maximumWorld.y = v.y;
  7541. if (v.z > this.maximumWorld.z)
  7542. this.maximumWorld.z = v.z;
  7543. }
  7544. // OBB
  7545. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7546. this.center.scaleInPlace(0.5);
  7547. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7548. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7549. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7550. this._worldMatrix = world;
  7551. };
  7552. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7553. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7554. };
  7555. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7556. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7557. };
  7558. BoundingBox.prototype.intersectsPoint = function (point) {
  7559. var delta = -BABYLON.Engine.Epsilon;
  7560. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7561. return false;
  7562. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7563. return false;
  7564. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7565. return false;
  7566. return true;
  7567. };
  7568. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7569. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7570. };
  7571. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7572. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7573. return false;
  7574. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7575. return false;
  7576. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7577. return false;
  7578. return true;
  7579. };
  7580. // Statics
  7581. BoundingBox.Intersects = function (box0, box1) {
  7582. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7583. return false;
  7584. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7585. return false;
  7586. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7587. return false;
  7588. return true;
  7589. };
  7590. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7591. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7592. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7593. return (num <= (sphereRadius * sphereRadius));
  7594. };
  7595. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7596. for (var p = 0; p < 6; p++) {
  7597. for (var i = 0; i < 8; i++) {
  7598. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7599. return false;
  7600. }
  7601. }
  7602. }
  7603. return true;
  7604. };
  7605. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7606. for (var p = 0; p < 6; p++) {
  7607. var inCount = 8;
  7608. for (var i = 0; i < 8; i++) {
  7609. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7610. --inCount;
  7611. }
  7612. else {
  7613. break;
  7614. }
  7615. }
  7616. if (inCount === 0)
  7617. return false;
  7618. }
  7619. return true;
  7620. };
  7621. return BoundingBox;
  7622. })();
  7623. BABYLON.BoundingBox = BoundingBox;
  7624. })(BABYLON || (BABYLON = {}));
  7625. var BABYLON;
  7626. (function (BABYLON) {
  7627. var computeBoxExtents = function (axis, box) {
  7628. var p = BABYLON.Vector3.Dot(box.center, axis);
  7629. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7630. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7631. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7632. var r = r0 + r1 + r2;
  7633. return {
  7634. min: p - r,
  7635. max: p + r
  7636. };
  7637. };
  7638. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7639. var axisOverlap = function (axis, box0, box1) {
  7640. var result0 = computeBoxExtents(axis, box0);
  7641. var result1 = computeBoxExtents(axis, box1);
  7642. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7643. };
  7644. var BoundingInfo = (function () {
  7645. function BoundingInfo(minimum, maximum) {
  7646. this.minimum = minimum;
  7647. this.maximum = maximum;
  7648. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7649. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7650. }
  7651. // Methods
  7652. BoundingInfo.prototype._update = function (world) {
  7653. this.boundingBox._update(world);
  7654. this.boundingSphere._update(world);
  7655. };
  7656. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7657. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7658. return false;
  7659. return this.boundingBox.isInFrustum(frustumPlanes);
  7660. };
  7661. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7662. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7663. };
  7664. BoundingInfo.prototype._checkCollision = function (collider) {
  7665. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7666. };
  7667. BoundingInfo.prototype.intersectsPoint = function (point) {
  7668. if (!this.boundingSphere.centerWorld) {
  7669. return false;
  7670. }
  7671. if (!this.boundingSphere.intersectsPoint(point)) {
  7672. return false;
  7673. }
  7674. if (!this.boundingBox.intersectsPoint(point)) {
  7675. return false;
  7676. }
  7677. return true;
  7678. };
  7679. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7680. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7681. return false;
  7682. }
  7683. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7684. return false;
  7685. }
  7686. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7687. return false;
  7688. }
  7689. if (!precise) {
  7690. return true;
  7691. }
  7692. var box0 = this.boundingBox;
  7693. var box1 = boundingInfo.boundingBox;
  7694. if (!axisOverlap(box0.directions[0], box0, box1))
  7695. return false;
  7696. if (!axisOverlap(box0.directions[1], box0, box1))
  7697. return false;
  7698. if (!axisOverlap(box0.directions[2], box0, box1))
  7699. return false;
  7700. if (!axisOverlap(box1.directions[0], box0, box1))
  7701. return false;
  7702. if (!axisOverlap(box1.directions[1], box0, box1))
  7703. return false;
  7704. if (!axisOverlap(box1.directions[2], box0, box1))
  7705. return false;
  7706. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7707. return false;
  7708. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7709. return false;
  7710. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7711. return false;
  7712. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7713. return false;
  7714. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7715. return false;
  7716. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7717. return false;
  7718. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7719. return false;
  7720. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7721. return false;
  7722. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7723. return false;
  7724. return true;
  7725. };
  7726. return BoundingInfo;
  7727. })();
  7728. BABYLON.BoundingInfo = BoundingInfo;
  7729. })(BABYLON || (BABYLON = {}));
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. var AbstractMesh = (function (_super) {
  7733. __extends(AbstractMesh, _super);
  7734. function AbstractMesh(name, scene) {
  7735. var _this = this;
  7736. _super.call(this, name, scene);
  7737. // Properties
  7738. this.definedFacingForward = true; // orientation for POV movement & rotation
  7739. this.position = new BABYLON.Vector3(0, 0, 0);
  7740. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7741. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7742. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7743. this.visibility = 1.0;
  7744. this.alphaIndex = Number.MAX_VALUE;
  7745. this.infiniteDistance = false;
  7746. this.isVisible = true;
  7747. this.isPickable = true;
  7748. this.showBoundingBox = false;
  7749. this.showSubMeshesBoundingBox = false;
  7750. this.onDispose = null;
  7751. this.isBlocker = false;
  7752. this.renderingGroupId = 0;
  7753. this.receiveShadows = false;
  7754. this.renderOutline = false;
  7755. this.outlineColor = BABYLON.Color3.Red();
  7756. this.outlineWidth = 0.02;
  7757. this.renderOverlay = false;
  7758. this.overlayColor = BABYLON.Color3.Red();
  7759. this.overlayAlpha = 0.5;
  7760. this.hasVertexAlpha = false;
  7761. this.useVertexColors = true;
  7762. this.applyFog = true;
  7763. this.computeBonesUsingShaders = true;
  7764. this.useOctreeForRenderingSelection = true;
  7765. this.useOctreeForPicking = true;
  7766. this.useOctreeForCollisions = true;
  7767. this.layerMask = 0x0FFFFFFF;
  7768. this.alwaysSelectAsActiveMesh = false;
  7769. // Physics
  7770. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7771. // Collisions
  7772. this._checkCollisions = false;
  7773. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7774. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7775. this._collider = new BABYLON.Collider();
  7776. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7777. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7778. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7779. // Cache
  7780. this._localScaling = BABYLON.Matrix.Zero();
  7781. this._localRotation = BABYLON.Matrix.Zero();
  7782. this._localTranslation = BABYLON.Matrix.Zero();
  7783. this._localBillboard = BABYLON.Matrix.Zero();
  7784. this._localPivotScaling = BABYLON.Matrix.Zero();
  7785. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7786. this._localWorld = BABYLON.Matrix.Zero();
  7787. this._worldMatrix = BABYLON.Matrix.Zero();
  7788. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7789. this._absolutePosition = BABYLON.Vector3.Zero();
  7790. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7791. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7792. this._isDirty = false;
  7793. this._pivotMatrix = BABYLON.Matrix.Identity();
  7794. this._isDisposed = false;
  7795. this._renderId = 0;
  7796. this._intersectionsInProgress = new Array();
  7797. this._onAfterWorldMatrixUpdate = new Array();
  7798. this._isWorldMatrixFrozen = false;
  7799. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7800. if (collidedMesh === void 0) { collidedMesh = null; }
  7801. //TODO move this to the collision coordinator!
  7802. if (_this.getScene().workerCollisions)
  7803. newPosition.multiplyInPlace(_this._collider.radius);
  7804. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7805. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7806. _this.position.addInPlace(_this._diffPositionForCollisions);
  7807. }
  7808. if (_this.onCollide && collidedMesh) {
  7809. _this.onCollide(collidedMesh);
  7810. }
  7811. };
  7812. scene.addMesh(this);
  7813. }
  7814. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7815. get: function () {
  7816. return AbstractMesh._BILLBOARDMODE_NONE;
  7817. },
  7818. enumerable: true,
  7819. configurable: true
  7820. });
  7821. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7822. get: function () {
  7823. return AbstractMesh._BILLBOARDMODE_X;
  7824. },
  7825. enumerable: true,
  7826. configurable: true
  7827. });
  7828. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7829. get: function () {
  7830. return AbstractMesh._BILLBOARDMODE_Y;
  7831. },
  7832. enumerable: true,
  7833. configurable: true
  7834. });
  7835. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7836. get: function () {
  7837. return AbstractMesh._BILLBOARDMODE_Z;
  7838. },
  7839. enumerable: true,
  7840. configurable: true
  7841. });
  7842. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7843. get: function () {
  7844. return AbstractMesh._BILLBOARDMODE_ALL;
  7845. },
  7846. enumerable: true,
  7847. configurable: true
  7848. });
  7849. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7850. // Methods
  7851. get: function () {
  7852. return false;
  7853. },
  7854. enumerable: true,
  7855. configurable: true
  7856. });
  7857. AbstractMesh.prototype.getLOD = function (camera) {
  7858. return this;
  7859. };
  7860. AbstractMesh.prototype.getTotalVertices = function () {
  7861. return 0;
  7862. };
  7863. AbstractMesh.prototype.getIndices = function () {
  7864. return null;
  7865. };
  7866. AbstractMesh.prototype.getVerticesData = function (kind) {
  7867. return null;
  7868. };
  7869. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7870. return false;
  7871. };
  7872. AbstractMesh.prototype.getBoundingInfo = function () {
  7873. if (this._masterMesh) {
  7874. return this._masterMesh.getBoundingInfo();
  7875. }
  7876. if (!this._boundingInfo) {
  7877. this._updateBoundingInfo();
  7878. }
  7879. return this._boundingInfo;
  7880. };
  7881. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7882. get: function () {
  7883. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. AbstractMesh.prototype._preActivate = function () {
  7889. };
  7890. AbstractMesh.prototype._activate = function (renderId) {
  7891. this._renderId = renderId;
  7892. };
  7893. AbstractMesh.prototype.getWorldMatrix = function () {
  7894. if (this._masterMesh) {
  7895. return this._masterMesh.getWorldMatrix();
  7896. }
  7897. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7898. this.computeWorldMatrix();
  7899. }
  7900. return this._worldMatrix;
  7901. };
  7902. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7903. get: function () {
  7904. return this._worldMatrix;
  7905. },
  7906. enumerable: true,
  7907. configurable: true
  7908. });
  7909. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7910. get: function () {
  7911. return this._absolutePosition;
  7912. },
  7913. enumerable: true,
  7914. configurable: true
  7915. });
  7916. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7917. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7918. this.computeWorldMatrix(true);
  7919. this._isWorldMatrixFrozen = true;
  7920. };
  7921. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7922. this._isWorldMatrixFrozen = false;
  7923. this.computeWorldMatrix(true);
  7924. };
  7925. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7926. get: function () {
  7927. return this._isWorldMatrixFrozen;
  7928. },
  7929. enumerable: true,
  7930. configurable: true
  7931. });
  7932. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7933. axis.normalize();
  7934. if (!this.rotationQuaternion) {
  7935. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7936. this.rotation = BABYLON.Vector3.Zero();
  7937. }
  7938. if (!space || space === BABYLON.Space.LOCAL) {
  7939. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7940. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7941. }
  7942. else {
  7943. if (this.parent) {
  7944. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7945. invertParentWorldMatrix.invert();
  7946. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7947. }
  7948. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7949. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7950. }
  7951. };
  7952. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7953. var displacementVector = axis.scale(distance);
  7954. if (!space || space === BABYLON.Space.LOCAL) {
  7955. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7956. this.setPositionWithLocalVector(tempV3);
  7957. }
  7958. else {
  7959. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7960. }
  7961. };
  7962. AbstractMesh.prototype.getAbsolutePosition = function () {
  7963. this.computeWorldMatrix();
  7964. return this._absolutePosition;
  7965. };
  7966. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7967. if (!absolutePosition) {
  7968. return;
  7969. }
  7970. var absolutePositionX;
  7971. var absolutePositionY;
  7972. var absolutePositionZ;
  7973. if (absolutePosition.x === undefined) {
  7974. if (arguments.length < 3) {
  7975. return;
  7976. }
  7977. absolutePositionX = arguments[0];
  7978. absolutePositionY = arguments[1];
  7979. absolutePositionZ = arguments[2];
  7980. }
  7981. else {
  7982. absolutePositionX = absolutePosition.x;
  7983. absolutePositionY = absolutePosition.y;
  7984. absolutePositionZ = absolutePosition.z;
  7985. }
  7986. if (this.parent) {
  7987. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7988. invertParentWorldMatrix.invert();
  7989. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7990. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7991. }
  7992. else {
  7993. this.position.x = absolutePositionX;
  7994. this.position.y = absolutePositionY;
  7995. this.position.z = absolutePositionZ;
  7996. }
  7997. };
  7998. // ================================== Point of View Movement =================================
  7999. /**
  8000. * Perform relative position change from the point of view of behind the front of the mesh.
  8001. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8002. * Supports definition of mesh facing forward or backward.
  8003. * @param {number} amountRight
  8004. * @param {number} amountUp
  8005. * @param {number} amountForward
  8006. */
  8007. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8008. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8009. };
  8010. /**
  8011. * Calculate relative position change from the point of view of behind the front of the mesh.
  8012. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8013. * Supports definition of mesh facing forward or backward.
  8014. * @param {number} amountRight
  8015. * @param {number} amountUp
  8016. * @param {number} amountForward
  8017. */
  8018. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8019. var rotMatrix = new BABYLON.Matrix();
  8020. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8021. rotQuaternion.toRotationMatrix(rotMatrix);
  8022. var translationDelta = BABYLON.Vector3.Zero();
  8023. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8025. return translationDelta;
  8026. };
  8027. // ================================== Point of View Rotation =================================
  8028. /**
  8029. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8030. * Supports definition of mesh facing forward or backward.
  8031. * @param {number} flipBack
  8032. * @param {number} twirlClockwise
  8033. * @param {number} tiltRight
  8034. */
  8035. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8036. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8037. };
  8038. /**
  8039. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8040. * Supports definition of mesh facing forward or backward.
  8041. * @param {number} flipBack
  8042. * @param {number} twirlClockwise
  8043. * @param {number} tiltRight
  8044. */
  8045. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8046. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8047. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8048. };
  8049. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8050. this._pivotMatrix = matrix;
  8051. this._cache.pivotMatrixUpdated = true;
  8052. };
  8053. AbstractMesh.prototype.getPivotMatrix = function () {
  8054. return this._pivotMatrix;
  8055. };
  8056. AbstractMesh.prototype._isSynchronized = function () {
  8057. if (this._isDirty) {
  8058. return false;
  8059. }
  8060. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8061. return false;
  8062. if (this._cache.pivotMatrixUpdated) {
  8063. return false;
  8064. }
  8065. if (this.infiniteDistance) {
  8066. return false;
  8067. }
  8068. if (!this._cache.position.equals(this.position))
  8069. return false;
  8070. if (this.rotationQuaternion) {
  8071. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8072. return false;
  8073. }
  8074. else {
  8075. if (!this._cache.rotation.equals(this.rotation))
  8076. return false;
  8077. }
  8078. if (!this._cache.scaling.equals(this.scaling))
  8079. return false;
  8080. return true;
  8081. };
  8082. AbstractMesh.prototype._initCache = function () {
  8083. _super.prototype._initCache.call(this);
  8084. this._cache.localMatrixUpdated = false;
  8085. this._cache.position = BABYLON.Vector3.Zero();
  8086. this._cache.scaling = BABYLON.Vector3.Zero();
  8087. this._cache.rotation = BABYLON.Vector3.Zero();
  8088. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8089. };
  8090. AbstractMesh.prototype.markAsDirty = function (property) {
  8091. if (property === "rotation") {
  8092. this.rotationQuaternion = null;
  8093. }
  8094. this._currentRenderId = Number.MAX_VALUE;
  8095. this._isDirty = true;
  8096. };
  8097. AbstractMesh.prototype._updateBoundingInfo = function () {
  8098. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8099. this._boundingInfo._update(this.worldMatrixFromCache);
  8100. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8101. };
  8102. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8103. if (!this.subMeshes) {
  8104. return;
  8105. }
  8106. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8107. var subMesh = this.subMeshes[subIndex];
  8108. subMesh.updateBoundingInfo(matrix);
  8109. }
  8110. };
  8111. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8112. if (this._isWorldMatrixFrozen) {
  8113. return this._worldMatrix;
  8114. }
  8115. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8116. return this._worldMatrix;
  8117. }
  8118. this._cache.position.copyFrom(this.position);
  8119. this._cache.scaling.copyFrom(this.scaling);
  8120. this._cache.pivotMatrixUpdated = false;
  8121. this._currentRenderId = this.getScene().getRenderId();
  8122. this._isDirty = false;
  8123. // Scaling
  8124. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8125. // Rotation
  8126. if (this.rotationQuaternion) {
  8127. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8128. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8129. }
  8130. else {
  8131. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8132. this._cache.rotation.copyFrom(this.rotation);
  8133. }
  8134. // Translation
  8135. if (this.infiniteDistance && !this.parent) {
  8136. var camera = this.getScene().activeCamera;
  8137. if (camera) {
  8138. var cameraWorldMatrix = camera.getWorldMatrix();
  8139. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8140. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8141. }
  8142. }
  8143. else {
  8144. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8145. }
  8146. // Composing transformations
  8147. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8148. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8149. // Billboarding
  8150. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8151. var localPosition = this.position.clone();
  8152. var zero = this.getScene().activeCamera.globalPosition.clone();
  8153. if (this.parent && this.parent.position) {
  8154. localPosition.addInPlace(this.parent.position);
  8155. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8156. }
  8157. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  8158. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8159. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8160. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8161. zero.y = localPosition.y + 0.001;
  8162. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8163. zero.z = localPosition.z + 0.001;
  8164. }
  8165. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8166. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8167. this._localBillboard.invert();
  8168. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8169. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8170. }
  8171. // Local world
  8172. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8173. // Parent
  8174. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8175. this._markSyncedWithParent();
  8176. if (this._meshToBoneReferal) {
  8177. if (!this._localMeshReferalTransform) {
  8178. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8179. }
  8180. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8181. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8182. }
  8183. else {
  8184. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8185. }
  8186. }
  8187. else {
  8188. this._worldMatrix.copyFrom(this._localWorld);
  8189. }
  8190. // Bounding info
  8191. this._updateBoundingInfo();
  8192. // Absolute position
  8193. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8194. // Callbacks
  8195. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8196. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8197. }
  8198. return this._worldMatrix;
  8199. };
  8200. /**
  8201. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8202. * @param func: callback function to add
  8203. */
  8204. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8205. this._onAfterWorldMatrixUpdate.push(func);
  8206. };
  8207. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8208. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8209. if (index > -1) {
  8210. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8211. }
  8212. };
  8213. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8214. this.computeWorldMatrix();
  8215. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8216. };
  8217. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8218. this.computeWorldMatrix();
  8219. var invLocalWorldMatrix = this._localWorld.clone();
  8220. invLocalWorldMatrix.invert();
  8221. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8222. };
  8223. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8224. this.computeWorldMatrix(true);
  8225. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8226. };
  8227. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8228. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8229. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8230. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8231. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8232. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8233. /// <returns>Mesh oriented towards targetMesh</returns>
  8234. yawCor = yawCor || 0; // default to zero if undefined
  8235. pitchCor = pitchCor || 0;
  8236. rollCor = rollCor || 0;
  8237. var dv = targetPoint.subtract(this.position);
  8238. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8239. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8240. var pitch = Math.atan2(dv.y, len);
  8241. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8242. };
  8243. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8244. this._meshToBoneReferal = affectedMesh;
  8245. this.parent = bone;
  8246. };
  8247. AbstractMesh.prototype.detachFromBone = function () {
  8248. this._meshToBoneReferal = null;
  8249. this.parent = null;
  8250. };
  8251. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8252. return this._boundingInfo.isInFrustum(frustumPlanes);
  8253. };
  8254. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8255. if (!camera) {
  8256. camera = this.getScene().activeCamera;
  8257. }
  8258. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8259. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8260. return false;
  8261. }
  8262. return true;
  8263. };
  8264. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8265. if (!this._boundingInfo || !mesh._boundingInfo) {
  8266. return false;
  8267. }
  8268. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8269. };
  8270. AbstractMesh.prototype.intersectsPoint = function (point) {
  8271. if (!this._boundingInfo) {
  8272. return false;
  8273. }
  8274. return this._boundingInfo.intersectsPoint(point);
  8275. };
  8276. // Physics
  8277. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8278. var physicsEngine = this.getScene().getPhysicsEngine();
  8279. if (!physicsEngine) {
  8280. return;
  8281. }
  8282. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8283. if (impostor.impostor) {
  8284. // Old API
  8285. options = impostor;
  8286. impostor = impostor.impostor;
  8287. }
  8288. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8289. physicsEngine._unregisterMesh(this);
  8290. return;
  8291. }
  8292. if (!options) {
  8293. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8294. }
  8295. else {
  8296. if (!options.mass && options.mass !== 0)
  8297. options.mass = 0;
  8298. if (!options.friction && options.friction !== 0)
  8299. options.friction = 0.2;
  8300. if (!options.restitution && options.restitution !== 0)
  8301. options.restitution = 0.2;
  8302. }
  8303. this._physicImpostor = impostor;
  8304. this._physicsMass = options.mass;
  8305. this._physicsFriction = options.friction;
  8306. this._physicRestitution = options.restitution;
  8307. return physicsEngine._registerMesh(this, impostor, options);
  8308. };
  8309. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8310. if (!this._physicImpostor) {
  8311. return BABYLON.PhysicsEngine.NoImpostor;
  8312. }
  8313. return this._physicImpostor;
  8314. };
  8315. AbstractMesh.prototype.getPhysicsMass = function () {
  8316. if (!this._physicsMass) {
  8317. return 0;
  8318. }
  8319. return this._physicsMass;
  8320. };
  8321. AbstractMesh.prototype.getPhysicsFriction = function () {
  8322. if (!this._physicsFriction) {
  8323. return 0;
  8324. }
  8325. return this._physicsFriction;
  8326. };
  8327. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8328. if (!this._physicRestitution) {
  8329. return 0;
  8330. }
  8331. return this._physicRestitution;
  8332. };
  8333. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8334. if (!camera) {
  8335. camera = this.getScene().activeCamera;
  8336. }
  8337. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8338. };
  8339. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8340. if (!camera) {
  8341. camera = this.getScene().activeCamera;
  8342. }
  8343. return this.absolutePosition.subtract(camera.position).length();
  8344. };
  8345. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8346. if (!this._physicImpostor) {
  8347. return;
  8348. }
  8349. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8350. };
  8351. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8352. if (!this._physicImpostor) {
  8353. return;
  8354. }
  8355. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8356. };
  8357. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8358. if (!this._physicImpostor) {
  8359. return;
  8360. }
  8361. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8362. };
  8363. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8364. // Collisions
  8365. get: function () {
  8366. return this._checkCollisions;
  8367. },
  8368. set: function (collisionEnabled) {
  8369. this._checkCollisions = collisionEnabled;
  8370. if (this.getScene().workerCollisions) {
  8371. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8372. }
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8378. var globalPosition = this.getAbsolutePosition();
  8379. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8380. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8381. this._collider.radius = this.ellipsoid;
  8382. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8383. };
  8384. // Submeshes octree
  8385. /**
  8386. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8387. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8388. */
  8389. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8390. if (maxCapacity === void 0) { maxCapacity = 64; }
  8391. if (maxDepth === void 0) { maxDepth = 2; }
  8392. if (!this._submeshesOctree) {
  8393. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8394. }
  8395. this.computeWorldMatrix(true);
  8396. // Update octree
  8397. var bbox = this.getBoundingInfo().boundingBox;
  8398. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8399. return this._submeshesOctree;
  8400. };
  8401. // Collisions
  8402. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8403. this._generatePointsArray();
  8404. // Transformation
  8405. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8406. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8407. subMesh._lastColliderWorldVertices = [];
  8408. subMesh._trianglePlanes = [];
  8409. var start = subMesh.verticesStart;
  8410. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8411. for (var i = start; i < end; i++) {
  8412. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8413. }
  8414. }
  8415. // Collide
  8416. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8417. if (collider.collisionFound) {
  8418. collider.collidedMesh = this;
  8419. }
  8420. };
  8421. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8422. var subMeshes;
  8423. var len;
  8424. // Octrees
  8425. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8426. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8427. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8428. len = intersections.length;
  8429. subMeshes = intersections.data;
  8430. }
  8431. else {
  8432. subMeshes = this.subMeshes;
  8433. len = subMeshes.length;
  8434. }
  8435. for (var index = 0; index < len; index++) {
  8436. var subMesh = subMeshes[index];
  8437. // Bounding test
  8438. if (len > 1 && !subMesh._checkCollision(collider))
  8439. continue;
  8440. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8441. }
  8442. };
  8443. AbstractMesh.prototype._checkCollision = function (collider) {
  8444. // Bounding box test
  8445. if (!this._boundingInfo._checkCollision(collider))
  8446. return;
  8447. // Transformation matrix
  8448. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8449. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8450. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8451. };
  8452. // Picking
  8453. AbstractMesh.prototype._generatePointsArray = function () {
  8454. return false;
  8455. };
  8456. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8457. var pickingInfo = new BABYLON.PickingInfo();
  8458. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8459. return pickingInfo;
  8460. }
  8461. if (!this._generatePointsArray()) {
  8462. return pickingInfo;
  8463. }
  8464. var intersectInfo = null;
  8465. // Octrees
  8466. var subMeshes;
  8467. var len;
  8468. if (this._submeshesOctree && this.useOctreeForPicking) {
  8469. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8470. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8471. len = intersections.length;
  8472. subMeshes = intersections.data;
  8473. }
  8474. else {
  8475. subMeshes = this.subMeshes;
  8476. len = subMeshes.length;
  8477. }
  8478. for (var index = 0; index < len; index++) {
  8479. var subMesh = subMeshes[index];
  8480. // Bounding test
  8481. if (len > 1 && !subMesh.canIntersects(ray))
  8482. continue;
  8483. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8484. if (currentIntersectInfo) {
  8485. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8486. intersectInfo = currentIntersectInfo;
  8487. intersectInfo.subMeshId = index;
  8488. if (fastCheck) {
  8489. break;
  8490. }
  8491. }
  8492. }
  8493. }
  8494. if (intersectInfo) {
  8495. // Get picked point
  8496. var world = this.getWorldMatrix();
  8497. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8498. var direction = ray.direction.clone();
  8499. direction = direction.scale(intersectInfo.distance);
  8500. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8501. var pickedPoint = worldOrigin.add(worldDirection);
  8502. // Return result
  8503. pickingInfo.hit = true;
  8504. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8505. pickingInfo.pickedPoint = pickedPoint;
  8506. pickingInfo.pickedMesh = this;
  8507. pickingInfo.bu = intersectInfo.bu;
  8508. pickingInfo.bv = intersectInfo.bv;
  8509. pickingInfo.faceId = intersectInfo.faceId;
  8510. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8511. return pickingInfo;
  8512. }
  8513. return pickingInfo;
  8514. };
  8515. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8516. return null;
  8517. };
  8518. AbstractMesh.prototype.releaseSubMeshes = function () {
  8519. if (this.subMeshes) {
  8520. while (this.subMeshes.length) {
  8521. this.subMeshes[0].dispose();
  8522. }
  8523. }
  8524. else {
  8525. this.subMeshes = new Array();
  8526. }
  8527. };
  8528. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8529. var index;
  8530. // Physics
  8531. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8532. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8533. }
  8534. // Intersections in progress
  8535. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8536. var other = this._intersectionsInProgress[index];
  8537. var pos = other._intersectionsInProgress.indexOf(this);
  8538. other._intersectionsInProgress.splice(pos, 1);
  8539. }
  8540. this._intersectionsInProgress = [];
  8541. // SubMeshes
  8542. this.releaseSubMeshes();
  8543. // Remove from scene
  8544. this.getScene().removeMesh(this);
  8545. if (!doNotRecurse) {
  8546. // Particles
  8547. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8548. if (this.getScene().particleSystems[index].emitter === this) {
  8549. this.getScene().particleSystems[index].dispose();
  8550. index--;
  8551. }
  8552. }
  8553. // Children
  8554. var objects = this.getScene().meshes.slice(0);
  8555. for (index = 0; index < objects.length; index++) {
  8556. if (objects[index].parent === this) {
  8557. objects[index].dispose();
  8558. }
  8559. }
  8560. }
  8561. else {
  8562. for (index = 0; index < this.getScene().meshes.length; index++) {
  8563. var obj = this.getScene().meshes[index];
  8564. if (obj.parent === this) {
  8565. obj.parent = null;
  8566. obj.computeWorldMatrix(true);
  8567. }
  8568. }
  8569. }
  8570. this._onAfterWorldMatrixUpdate = [];
  8571. this._isDisposed = true;
  8572. // Callback
  8573. if (this.onDispose) {
  8574. this.onDispose();
  8575. }
  8576. };
  8577. // Statics
  8578. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8579. AbstractMesh._BILLBOARDMODE_X = 1;
  8580. AbstractMesh._BILLBOARDMODE_Y = 2;
  8581. AbstractMesh._BILLBOARDMODE_Z = 4;
  8582. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8583. return AbstractMesh;
  8584. })(BABYLON.Node);
  8585. BABYLON.AbstractMesh = AbstractMesh;
  8586. })(BABYLON || (BABYLON = {}));
  8587. var BABYLON;
  8588. (function (BABYLON) {
  8589. var Light = (function (_super) {
  8590. __extends(Light, _super);
  8591. function Light(name, scene) {
  8592. _super.call(this, name, scene);
  8593. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8594. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8595. this.intensity = 1.0;
  8596. this.range = Number.MAX_VALUE;
  8597. this.includeOnlyWithLayerMask = 0;
  8598. this.includedOnlyMeshes = new Array();
  8599. this.excludedMeshes = new Array();
  8600. this.excludeWithLayerMask = 0;
  8601. this._excludedMeshesIds = new Array();
  8602. this._includedOnlyMeshesIds = new Array();
  8603. scene.addLight(this);
  8604. }
  8605. Light.prototype.getShadowGenerator = function () {
  8606. return this._shadowGenerator;
  8607. };
  8608. Light.prototype.getAbsolutePosition = function () {
  8609. return BABYLON.Vector3.Zero();
  8610. };
  8611. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8612. };
  8613. Light.prototype._getWorldMatrix = function () {
  8614. return BABYLON.Matrix.Identity();
  8615. };
  8616. Light.prototype.canAffectMesh = function (mesh) {
  8617. if (!mesh) {
  8618. return true;
  8619. }
  8620. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8621. return false;
  8622. }
  8623. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8624. return false;
  8625. }
  8626. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8627. return false;
  8628. }
  8629. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8630. return false;
  8631. }
  8632. return true;
  8633. };
  8634. Light.prototype.getWorldMatrix = function () {
  8635. this._currentRenderId = this.getScene().getRenderId();
  8636. var worldMatrix = this._getWorldMatrix();
  8637. if (this.parent && this.parent.getWorldMatrix) {
  8638. if (!this._parentedWorldMatrix) {
  8639. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8640. }
  8641. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8642. this._markSyncedWithParent();
  8643. return this._parentedWorldMatrix;
  8644. }
  8645. return worldMatrix;
  8646. };
  8647. Light.prototype.dispose = function () {
  8648. if (this._shadowGenerator) {
  8649. this._shadowGenerator.dispose();
  8650. this._shadowGenerator = null;
  8651. }
  8652. // Remove from scene
  8653. this.getScene().removeLight(this);
  8654. };
  8655. return Light;
  8656. })(BABYLON.Node);
  8657. BABYLON.Light = Light;
  8658. })(BABYLON || (BABYLON = {}));
  8659. var BABYLON;
  8660. (function (BABYLON) {
  8661. var PointLight = (function (_super) {
  8662. __extends(PointLight, _super);
  8663. function PointLight(name, position, scene) {
  8664. _super.call(this, name, scene);
  8665. this.position = position;
  8666. }
  8667. PointLight.prototype.getAbsolutePosition = function () {
  8668. return this._transformedPosition ? this._transformedPosition : this.position;
  8669. };
  8670. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8671. if (this.parent && this.parent.getWorldMatrix) {
  8672. if (!this._transformedPosition) {
  8673. this._transformedPosition = BABYLON.Vector3.Zero();
  8674. }
  8675. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8676. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8677. return;
  8678. }
  8679. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8680. };
  8681. PointLight.prototype.getShadowGenerator = function () {
  8682. return null;
  8683. };
  8684. PointLight.prototype._getWorldMatrix = function () {
  8685. if (!this._worldMatrix) {
  8686. this._worldMatrix = BABYLON.Matrix.Identity();
  8687. }
  8688. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8689. return this._worldMatrix;
  8690. };
  8691. return PointLight;
  8692. })(BABYLON.Light);
  8693. BABYLON.PointLight = PointLight;
  8694. })(BABYLON || (BABYLON = {}));
  8695. var BABYLON;
  8696. (function (BABYLON) {
  8697. var SpotLight = (function (_super) {
  8698. __extends(SpotLight, _super);
  8699. function SpotLight(name, position, direction, angle, exponent, scene) {
  8700. _super.call(this, name, scene);
  8701. this.position = position;
  8702. this.direction = direction;
  8703. this.angle = angle;
  8704. this.exponent = exponent;
  8705. }
  8706. SpotLight.prototype.getAbsolutePosition = function () {
  8707. return this.transformedPosition ? this.transformedPosition : this.position;
  8708. };
  8709. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8710. var activeCamera = this.getScene().activeCamera;
  8711. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8712. };
  8713. SpotLight.prototype.supportsVSM = function () {
  8714. return true;
  8715. };
  8716. SpotLight.prototype.needRefreshPerFrame = function () {
  8717. return false;
  8718. };
  8719. SpotLight.prototype.setDirectionToTarget = function (target) {
  8720. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8721. return this.direction;
  8722. };
  8723. SpotLight.prototype.computeTransformedPosition = function () {
  8724. if (this.parent && this.parent.getWorldMatrix) {
  8725. if (!this.transformedPosition) {
  8726. this.transformedPosition = BABYLON.Vector3.Zero();
  8727. }
  8728. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8729. return true;
  8730. }
  8731. return false;
  8732. };
  8733. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8734. var normalizeDirection;
  8735. if (this.parent && this.parent.getWorldMatrix) {
  8736. if (!this._transformedDirection) {
  8737. this._transformedDirection = BABYLON.Vector3.Zero();
  8738. }
  8739. this.computeTransformedPosition();
  8740. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8741. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8742. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8743. }
  8744. else {
  8745. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8746. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8747. }
  8748. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8749. };
  8750. SpotLight.prototype._getWorldMatrix = function () {
  8751. if (!this._worldMatrix) {
  8752. this._worldMatrix = BABYLON.Matrix.Identity();
  8753. }
  8754. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8755. return this._worldMatrix;
  8756. };
  8757. return SpotLight;
  8758. })(BABYLON.Light);
  8759. BABYLON.SpotLight = SpotLight;
  8760. })(BABYLON || (BABYLON = {}));
  8761. var BABYLON;
  8762. (function (BABYLON) {
  8763. var HemisphericLight = (function (_super) {
  8764. __extends(HemisphericLight, _super);
  8765. function HemisphericLight(name, direction, scene) {
  8766. _super.call(this, name, scene);
  8767. this.direction = direction;
  8768. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8769. }
  8770. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8771. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8772. return this.direction;
  8773. };
  8774. HemisphericLight.prototype.getShadowGenerator = function () {
  8775. return null;
  8776. };
  8777. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8778. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8779. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8780. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8781. };
  8782. HemisphericLight.prototype._getWorldMatrix = function () {
  8783. if (!this._worldMatrix) {
  8784. this._worldMatrix = BABYLON.Matrix.Identity();
  8785. }
  8786. return this._worldMatrix;
  8787. };
  8788. return HemisphericLight;
  8789. })(BABYLON.Light);
  8790. BABYLON.HemisphericLight = HemisphericLight;
  8791. })(BABYLON || (BABYLON = {}));
  8792. var BABYLON;
  8793. (function (BABYLON) {
  8794. var DirectionalLight = (function (_super) {
  8795. __extends(DirectionalLight, _super);
  8796. function DirectionalLight(name, direction, scene) {
  8797. _super.call(this, name, scene);
  8798. this.direction = direction;
  8799. this.shadowOrthoScale = 0.5;
  8800. this.position = direction.scale(-1);
  8801. }
  8802. DirectionalLight.prototype.getAbsolutePosition = function () {
  8803. return this.transformedPosition ? this.transformedPosition : this.position;
  8804. };
  8805. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8806. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8807. return this.direction;
  8808. };
  8809. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8810. var orthoLeft = Number.MAX_VALUE;
  8811. var orthoRight = Number.MIN_VALUE;
  8812. var orthoTop = Number.MIN_VALUE;
  8813. var orthoBottom = Number.MAX_VALUE;
  8814. var tempVector3 = BABYLON.Vector3.Zero();
  8815. var activeCamera = this.getScene().activeCamera;
  8816. // Check extends
  8817. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8818. var mesh = renderList[meshIndex];
  8819. if (!mesh) {
  8820. continue;
  8821. }
  8822. var boundingInfo = mesh.getBoundingInfo();
  8823. if (!boundingInfo) {
  8824. continue;
  8825. }
  8826. var boundingBox = boundingInfo.boundingBox;
  8827. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8828. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8829. if (tempVector3.x < orthoLeft)
  8830. orthoLeft = tempVector3.x;
  8831. if (tempVector3.y < orthoBottom)
  8832. orthoBottom = tempVector3.y;
  8833. if (tempVector3.x > orthoRight)
  8834. orthoRight = tempVector3.x;
  8835. if (tempVector3.y > orthoTop)
  8836. orthoTop = tempVector3.y;
  8837. }
  8838. }
  8839. var xOffset = orthoRight - orthoLeft;
  8840. var yOffset = orthoTop - orthoBottom;
  8841. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8842. };
  8843. DirectionalLight.prototype.supportsVSM = function () {
  8844. return true;
  8845. };
  8846. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8847. return true;
  8848. };
  8849. DirectionalLight.prototype.computeTransformedPosition = function () {
  8850. if (this.parent && this.parent.getWorldMatrix) {
  8851. if (!this.transformedPosition) {
  8852. this.transformedPosition = BABYLON.Vector3.Zero();
  8853. }
  8854. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8855. return true;
  8856. }
  8857. return false;
  8858. };
  8859. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8860. if (this.parent && this.parent.getWorldMatrix) {
  8861. if (!this._transformedDirection) {
  8862. this._transformedDirection = BABYLON.Vector3.Zero();
  8863. }
  8864. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8865. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8866. return;
  8867. }
  8868. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8869. };
  8870. DirectionalLight.prototype._getWorldMatrix = function () {
  8871. if (!this._worldMatrix) {
  8872. this._worldMatrix = BABYLON.Matrix.Identity();
  8873. }
  8874. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8875. return this._worldMatrix;
  8876. };
  8877. return DirectionalLight;
  8878. })(BABYLON.Light);
  8879. BABYLON.DirectionalLight = DirectionalLight;
  8880. })(BABYLON || (BABYLON = {}));
  8881. var BABYLON;
  8882. (function (BABYLON) {
  8883. var ShadowGenerator = (function () {
  8884. function ShadowGenerator(mapSize, light) {
  8885. var _this = this;
  8886. // Members
  8887. this._filter = ShadowGenerator.FILTER_NONE;
  8888. this.blurScale = 2;
  8889. this._blurBoxOffset = 0;
  8890. this._bias = 0.00005;
  8891. this._lightDirection = BABYLON.Vector3.Zero();
  8892. this._darkness = 0;
  8893. this._transparencyShadow = false;
  8894. this._viewMatrix = BABYLON.Matrix.Zero();
  8895. this._projectionMatrix = BABYLON.Matrix.Zero();
  8896. this._transformMatrix = BABYLON.Matrix.Zero();
  8897. this._worldViewProjection = BABYLON.Matrix.Zero();
  8898. this._light = light;
  8899. this._scene = light.getScene();
  8900. this._mapSize = mapSize;
  8901. light._shadowGenerator = this;
  8902. // Render target
  8903. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8904. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8905. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8906. this._shadowMap.anisotropicFilteringLevel = 1;
  8907. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8908. this._shadowMap.renderParticles = false;
  8909. this._shadowMap.onAfterUnbind = function () {
  8910. if (!_this.useBlurVarianceShadowMap) {
  8911. return;
  8912. }
  8913. if (!_this._shadowMap2) {
  8914. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8915. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8916. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8917. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8918. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8919. _this._downSamplePostprocess.onApply = function (effect) {
  8920. effect.setTexture("textureSampler", _this._shadowMap);
  8921. };
  8922. _this.blurBoxOffset = 1;
  8923. }
  8924. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8925. };
  8926. // Custom render function
  8927. var renderSubMesh = function (subMesh) {
  8928. var mesh = subMesh.getRenderingMesh();
  8929. var scene = _this._scene;
  8930. var engine = scene.getEngine();
  8931. // Culling
  8932. engine.setState(subMesh.getMaterial().backFaceCulling);
  8933. // Managing instances
  8934. var batch = mesh._getInstancesRenderList(subMesh._id);
  8935. if (batch.mustReturn) {
  8936. return;
  8937. }
  8938. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8939. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8940. engine.enableEffect(_this._effect);
  8941. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8942. var material = subMesh.getMaterial();
  8943. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8944. // Alpha test
  8945. if (material && material.needAlphaTesting()) {
  8946. var alphaTexture = material.getAlphaTestTexture();
  8947. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8948. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8949. }
  8950. // Bones
  8951. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8952. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8953. }
  8954. // Draw
  8955. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8956. }
  8957. else {
  8958. // Need to reset refresh rate of the shadowMap
  8959. _this._shadowMap.resetRefreshCounter();
  8960. }
  8961. };
  8962. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8963. var index;
  8964. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8965. renderSubMesh(opaqueSubMeshes.data[index]);
  8966. }
  8967. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8968. renderSubMesh(alphaTestSubMeshes.data[index]);
  8969. }
  8970. if (_this._transparencyShadow) {
  8971. for (index = 0; index < transparentSubMeshes.length; index++) {
  8972. renderSubMesh(transparentSubMeshes.data[index]);
  8973. }
  8974. }
  8975. };
  8976. this._shadowMap.onClear = function (engine) {
  8977. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8978. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8979. }
  8980. else {
  8981. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8982. }
  8983. };
  8984. }
  8985. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8986. // Static
  8987. get: function () {
  8988. return ShadowGenerator._FILTER_NONE;
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8994. get: function () {
  8995. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8996. },
  8997. enumerable: true,
  8998. configurable: true
  8999. });
  9000. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9001. get: function () {
  9002. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9003. },
  9004. enumerable: true,
  9005. configurable: true
  9006. });
  9007. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9008. get: function () {
  9009. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9010. },
  9011. enumerable: true,
  9012. configurable: true
  9013. });
  9014. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9015. get: function () {
  9016. return this._bias;
  9017. },
  9018. set: function (bias) {
  9019. this._bias = bias;
  9020. },
  9021. enumerable: true,
  9022. configurable: true
  9023. });
  9024. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9025. get: function () {
  9026. return this._blurBoxOffset;
  9027. },
  9028. set: function (value) {
  9029. var _this = this;
  9030. if (this._blurBoxOffset === value) {
  9031. return;
  9032. }
  9033. this._blurBoxOffset = value;
  9034. if (this._boxBlurPostprocess) {
  9035. this._boxBlurPostprocess.dispose();
  9036. }
  9037. 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);
  9038. this._boxBlurPostprocess.onApply = function (effect) {
  9039. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9040. };
  9041. },
  9042. enumerable: true,
  9043. configurable: true
  9044. });
  9045. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9046. get: function () {
  9047. return this._filter;
  9048. },
  9049. set: function (value) {
  9050. if (this._filter === value) {
  9051. return;
  9052. }
  9053. this._filter = value;
  9054. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9055. this._shadowMap.anisotropicFilteringLevel = 16;
  9056. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9057. }
  9058. else {
  9059. this._shadowMap.anisotropicFilteringLevel = 1;
  9060. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9061. }
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9067. get: function () {
  9068. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9069. },
  9070. set: function (value) {
  9071. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9072. },
  9073. enumerable: true,
  9074. configurable: true
  9075. });
  9076. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9077. get: function () {
  9078. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9079. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9080. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9081. },
  9082. set: function (value) {
  9083. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9084. },
  9085. enumerable: true,
  9086. configurable: true
  9087. });
  9088. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9089. get: function () {
  9090. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9091. },
  9092. set: function (value) {
  9093. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9094. },
  9095. enumerable: true,
  9096. configurable: true
  9097. });
  9098. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9099. var defines = [];
  9100. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9101. defines.push("#define VSM");
  9102. }
  9103. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9104. var mesh = subMesh.getMesh();
  9105. var material = subMesh.getMaterial();
  9106. // Alpha test
  9107. if (material && material.needAlphaTesting()) {
  9108. defines.push("#define ALPHATEST");
  9109. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9110. attribs.push(BABYLON.VertexBuffer.UVKind);
  9111. defines.push("#define UV1");
  9112. }
  9113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9114. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9115. defines.push("#define UV2");
  9116. }
  9117. }
  9118. // Bones
  9119. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9120. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9121. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9122. defines.push("#define BONES");
  9123. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9124. }
  9125. // Instances
  9126. if (useInstances) {
  9127. defines.push("#define INSTANCES");
  9128. attribs.push("world0");
  9129. attribs.push("world1");
  9130. attribs.push("world2");
  9131. attribs.push("world3");
  9132. }
  9133. // Get correct effect
  9134. var join = defines.join("\n");
  9135. if (this._cachedDefines !== join) {
  9136. this._cachedDefines = join;
  9137. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9138. }
  9139. return this._effect.isReady();
  9140. };
  9141. ShadowGenerator.prototype.getShadowMap = function () {
  9142. return this._shadowMap;
  9143. };
  9144. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9145. if (this._shadowMap2) {
  9146. return this._shadowMap2;
  9147. }
  9148. return this._shadowMap;
  9149. };
  9150. ShadowGenerator.prototype.getLight = function () {
  9151. return this._light;
  9152. };
  9153. // Methods
  9154. ShadowGenerator.prototype.getTransformMatrix = function () {
  9155. var scene = this._scene;
  9156. if (this._currentRenderID === scene.getRenderId()) {
  9157. return this._transformMatrix;
  9158. }
  9159. this._currentRenderID = scene.getRenderId();
  9160. var lightPosition = this._light.position;
  9161. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9162. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9163. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9164. }
  9165. if (this._light.computeTransformedPosition()) {
  9166. lightPosition = this._light.transformedPosition;
  9167. }
  9168. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9169. this._cachedPosition = lightPosition.clone();
  9170. this._cachedDirection = this._lightDirection.clone();
  9171. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9172. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9173. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9174. }
  9175. return this._transformMatrix;
  9176. };
  9177. ShadowGenerator.prototype.getDarkness = function () {
  9178. return this._darkness;
  9179. };
  9180. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9181. if (darkness >= 1.0)
  9182. this._darkness = 1.0;
  9183. else if (darkness <= 0.0)
  9184. this._darkness = 0.0;
  9185. else
  9186. this._darkness = darkness;
  9187. };
  9188. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9189. this._transparencyShadow = hasShadow;
  9190. };
  9191. ShadowGenerator.prototype._packHalf = function (depth) {
  9192. var scale = depth * 255.0;
  9193. var fract = scale - Math.floor(scale);
  9194. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9195. };
  9196. ShadowGenerator.prototype.dispose = function () {
  9197. this._shadowMap.dispose();
  9198. if (this._shadowMap2) {
  9199. this._shadowMap2.dispose();
  9200. }
  9201. if (this._downSamplePostprocess) {
  9202. this._downSamplePostprocess.dispose();
  9203. }
  9204. if (this._boxBlurPostprocess) {
  9205. this._boxBlurPostprocess.dispose();
  9206. }
  9207. };
  9208. ShadowGenerator._FILTER_NONE = 0;
  9209. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9210. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9211. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9212. return ShadowGenerator;
  9213. })();
  9214. BABYLON.ShadowGenerator = ShadowGenerator;
  9215. })(BABYLON || (BABYLON = {}));
  9216. var BABYLON;
  9217. (function (BABYLON) {
  9218. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9219. if (boxMin.x > sphereCenter.x + sphereRadius)
  9220. return false;
  9221. if (sphereCenter.x - sphereRadius > boxMax.x)
  9222. return false;
  9223. if (boxMin.y > sphereCenter.y + sphereRadius)
  9224. return false;
  9225. if (sphereCenter.y - sphereRadius > boxMax.y)
  9226. return false;
  9227. if (boxMin.z > sphereCenter.z + sphereRadius)
  9228. return false;
  9229. if (sphereCenter.z - sphereRadius > boxMax.z)
  9230. return false;
  9231. return true;
  9232. };
  9233. var getLowestRoot = function (a, b, c, maxR) {
  9234. var determinant = b * b - 4.0 * a * c;
  9235. var result = { root: 0, found: false };
  9236. if (determinant < 0)
  9237. return result;
  9238. var sqrtD = Math.sqrt(determinant);
  9239. var r1 = (-b - sqrtD) / (2.0 * a);
  9240. var r2 = (-b + sqrtD) / (2.0 * a);
  9241. if (r1 > r2) {
  9242. var temp = r2;
  9243. r2 = r1;
  9244. r1 = temp;
  9245. }
  9246. if (r1 > 0 && r1 < maxR) {
  9247. result.root = r1;
  9248. result.found = true;
  9249. return result;
  9250. }
  9251. if (r2 > 0 && r2 < maxR) {
  9252. result.root = r2;
  9253. result.found = true;
  9254. return result;
  9255. }
  9256. return result;
  9257. };
  9258. var Collider = (function () {
  9259. function Collider() {
  9260. this.radius = new BABYLON.Vector3(1, 1, 1);
  9261. this.retry = 0;
  9262. this.basePointWorld = BABYLON.Vector3.Zero();
  9263. this.velocityWorld = BABYLON.Vector3.Zero();
  9264. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9265. this._collisionPoint = BABYLON.Vector3.Zero();
  9266. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9267. this._tempVector = BABYLON.Vector3.Zero();
  9268. this._tempVector2 = BABYLON.Vector3.Zero();
  9269. this._tempVector3 = BABYLON.Vector3.Zero();
  9270. this._tempVector4 = BABYLON.Vector3.Zero();
  9271. this._edge = BABYLON.Vector3.Zero();
  9272. this._baseToVertex = BABYLON.Vector3.Zero();
  9273. this._destinationPoint = BABYLON.Vector3.Zero();
  9274. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9275. this._displacementVector = BABYLON.Vector3.Zero();
  9276. }
  9277. // Methods
  9278. Collider.prototype._initialize = function (source, dir, e) {
  9279. this.velocity = dir;
  9280. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9281. this.basePoint = source;
  9282. source.multiplyToRef(this.radius, this.basePointWorld);
  9283. dir.multiplyToRef(this.radius, this.velocityWorld);
  9284. this.velocityWorldLength = this.velocityWorld.length();
  9285. this.epsilon = e;
  9286. this.collisionFound = false;
  9287. };
  9288. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9289. pa.subtractToRef(point, this._tempVector);
  9290. pb.subtractToRef(point, this._tempVector2);
  9291. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9292. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9293. if (d < 0)
  9294. return false;
  9295. pc.subtractToRef(point, this._tempVector3);
  9296. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9297. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9298. if (d < 0)
  9299. return false;
  9300. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9301. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9302. return d >= 0;
  9303. };
  9304. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9305. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9306. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9307. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9308. return false;
  9309. }
  9310. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9311. return false;
  9312. return true;
  9313. };
  9314. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9315. var t0;
  9316. var embeddedInPlane = false;
  9317. //defensive programming, actually not needed.
  9318. if (!trianglePlaneArray) {
  9319. trianglePlaneArray = [];
  9320. }
  9321. if (!trianglePlaneArray[faceIndex]) {
  9322. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9323. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9324. }
  9325. var trianglePlane = trianglePlaneArray[faceIndex];
  9326. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9327. return;
  9328. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9329. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9330. if (normalDotVelocity == 0) {
  9331. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9332. return;
  9333. embeddedInPlane = true;
  9334. t0 = 0;
  9335. }
  9336. else {
  9337. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9338. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9339. if (t0 > t1) {
  9340. var temp = t1;
  9341. t1 = t0;
  9342. t0 = temp;
  9343. }
  9344. if (t0 > 1.0 || t1 < 0.0)
  9345. return;
  9346. if (t0 < 0)
  9347. t0 = 0;
  9348. if (t0 > 1.0)
  9349. t0 = 1.0;
  9350. }
  9351. this._collisionPoint.copyFromFloats(0, 0, 0);
  9352. var found = false;
  9353. var t = 1.0;
  9354. if (!embeddedInPlane) {
  9355. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9356. this.velocity.scaleToRef(t0, this._tempVector);
  9357. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9358. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9359. found = true;
  9360. t = t0;
  9361. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9362. }
  9363. }
  9364. if (!found) {
  9365. var velocitySquaredLength = this.velocity.lengthSquared();
  9366. var a = velocitySquaredLength;
  9367. this.basePoint.subtractToRef(p1, this._tempVector);
  9368. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9369. var c = this._tempVector.lengthSquared() - 1.0;
  9370. var lowestRoot = getLowestRoot(a, b, c, t);
  9371. if (lowestRoot.found) {
  9372. t = lowestRoot.root;
  9373. found = true;
  9374. this._collisionPoint.copyFrom(p1);
  9375. }
  9376. this.basePoint.subtractToRef(p2, this._tempVector);
  9377. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9378. c = this._tempVector.lengthSquared() - 1.0;
  9379. lowestRoot = getLowestRoot(a, b, c, t);
  9380. if (lowestRoot.found) {
  9381. t = lowestRoot.root;
  9382. found = true;
  9383. this._collisionPoint.copyFrom(p2);
  9384. }
  9385. this.basePoint.subtractToRef(p3, this._tempVector);
  9386. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9387. c = this._tempVector.lengthSquared() - 1.0;
  9388. lowestRoot = getLowestRoot(a, b, c, t);
  9389. if (lowestRoot.found) {
  9390. t = lowestRoot.root;
  9391. found = true;
  9392. this._collisionPoint.copyFrom(p3);
  9393. }
  9394. p2.subtractToRef(p1, this._edge);
  9395. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9396. var edgeSquaredLength = this._edge.lengthSquared();
  9397. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9398. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9399. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9400. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9401. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9402. lowestRoot = getLowestRoot(a, b, c, t);
  9403. if (lowestRoot.found) {
  9404. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9405. if (f >= 0.0 && f <= 1.0) {
  9406. t = lowestRoot.root;
  9407. found = true;
  9408. this._edge.scaleInPlace(f);
  9409. p1.addToRef(this._edge, this._collisionPoint);
  9410. }
  9411. }
  9412. p3.subtractToRef(p2, this._edge);
  9413. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9414. edgeSquaredLength = this._edge.lengthSquared();
  9415. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9416. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9417. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9418. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9419. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9420. lowestRoot = getLowestRoot(a, b, c, t);
  9421. if (lowestRoot.found) {
  9422. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9423. if (f >= 0.0 && f <= 1.0) {
  9424. t = lowestRoot.root;
  9425. found = true;
  9426. this._edge.scaleInPlace(f);
  9427. p2.addToRef(this._edge, this._collisionPoint);
  9428. }
  9429. }
  9430. p1.subtractToRef(p3, this._edge);
  9431. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9432. edgeSquaredLength = this._edge.lengthSquared();
  9433. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9434. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9435. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9436. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9437. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9438. lowestRoot = getLowestRoot(a, b, c, t);
  9439. if (lowestRoot.found) {
  9440. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9441. if (f >= 0.0 && f <= 1.0) {
  9442. t = lowestRoot.root;
  9443. found = true;
  9444. this._edge.scaleInPlace(f);
  9445. p3.addToRef(this._edge, this._collisionPoint);
  9446. }
  9447. }
  9448. }
  9449. if (found) {
  9450. var distToCollision = t * this.velocity.length();
  9451. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9452. if (!this.intersectionPoint) {
  9453. this.intersectionPoint = this._collisionPoint.clone();
  9454. }
  9455. else {
  9456. this.intersectionPoint.copyFrom(this._collisionPoint);
  9457. }
  9458. this.nearestDistance = distToCollision;
  9459. this.collisionFound = true;
  9460. }
  9461. }
  9462. };
  9463. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9464. for (var i = indexStart; i < indexEnd; i += 3) {
  9465. var p1 = pts[indices[i] - decal];
  9466. var p2 = pts[indices[i + 1] - decal];
  9467. var p3 = pts[indices[i + 2] - decal];
  9468. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9469. }
  9470. };
  9471. Collider.prototype._getResponse = function (pos, vel) {
  9472. pos.addToRef(vel, this._destinationPoint);
  9473. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9474. this.basePoint.addToRef(vel, pos);
  9475. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9476. this._slidePlaneNormal.normalize();
  9477. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9478. pos.addInPlace(this._displacementVector);
  9479. this.intersectionPoint.addInPlace(this._displacementVector);
  9480. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9481. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9482. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9483. };
  9484. return Collider;
  9485. })();
  9486. BABYLON.Collider = Collider;
  9487. })(BABYLON || (BABYLON = {}));
  9488. var BABYLON;
  9489. (function (BABYLON) {
  9490. //WebWorker code will be inserted to this variable.
  9491. BABYLON.CollisionWorker = "";
  9492. (function (WorkerTaskType) {
  9493. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9494. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9495. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9496. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9497. var WorkerTaskType = BABYLON.WorkerTaskType;
  9498. (function (WorkerReplyType) {
  9499. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9500. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9501. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9502. var WorkerReplyType = BABYLON.WorkerReplyType;
  9503. var CollisionCoordinatorWorker = (function () {
  9504. function CollisionCoordinatorWorker() {
  9505. var _this = this;
  9506. this._scaledPosition = BABYLON.Vector3.Zero();
  9507. this._scaledVelocity = BABYLON.Vector3.Zero();
  9508. this.onMeshUpdated = function (mesh) {
  9509. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9510. };
  9511. this.onGeometryUpdated = function (geometry) {
  9512. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9513. };
  9514. this._afterRender = function () {
  9515. if (!_this._init)
  9516. return;
  9517. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9518. return;
  9519. }
  9520. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9521. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9522. if (_this._runningUpdated > 4) {
  9523. return;
  9524. }
  9525. ++_this._runningUpdated;
  9526. var payload = {
  9527. updatedMeshes: _this._addUpdateMeshesList,
  9528. updatedGeometries: _this._addUpdateGeometriesList,
  9529. removedGeometries: _this._toRemoveGeometryArray,
  9530. removedMeshes: _this._toRemoveMeshesArray
  9531. };
  9532. var message = {
  9533. payload: payload,
  9534. taskType: WorkerTaskType.UPDATE
  9535. };
  9536. var serializable = [];
  9537. for (var id in payload.updatedGeometries) {
  9538. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9539. //prepare transferables
  9540. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9541. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9542. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9543. }
  9544. }
  9545. _this._worker.postMessage(message, serializable);
  9546. _this._addUpdateMeshesList = {};
  9547. _this._addUpdateGeometriesList = {};
  9548. _this._toRemoveGeometryArray = [];
  9549. _this._toRemoveMeshesArray = [];
  9550. };
  9551. this._onMessageFromWorker = function (e) {
  9552. var returnData = e.data;
  9553. if (returnData.error != WorkerReplyType.SUCCESS) {
  9554. //TODO what errors can be returned from the worker?
  9555. BABYLON.Tools.Warn("error returned from worker!");
  9556. return;
  9557. }
  9558. switch (returnData.taskType) {
  9559. case WorkerTaskType.INIT:
  9560. _this._init = true;
  9561. //Update the worked with ALL of the scene's current state
  9562. _this._scene.meshes.forEach(function (mesh) {
  9563. _this.onMeshAdded(mesh);
  9564. });
  9565. _this._scene.getGeometries().forEach(function (geometry) {
  9566. _this.onGeometryAdded(geometry);
  9567. });
  9568. break;
  9569. case WorkerTaskType.UPDATE:
  9570. _this._runningUpdated--;
  9571. break;
  9572. case WorkerTaskType.COLLIDE:
  9573. _this._runningCollisionTask = false;
  9574. var returnPayload = returnData.payload;
  9575. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9576. return;
  9577. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9578. //cleanup
  9579. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9580. break;
  9581. }
  9582. };
  9583. this._collisionsCallbackArray = [];
  9584. this._init = false;
  9585. this._runningUpdated = 0;
  9586. this._runningCollisionTask = false;
  9587. this._addUpdateMeshesList = {};
  9588. this._addUpdateGeometriesList = {};
  9589. this._toRemoveGeometryArray = [];
  9590. this._toRemoveMeshesArray = [];
  9591. }
  9592. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9593. if (!this._init)
  9594. return;
  9595. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9596. return;
  9597. position.divideToRef(collider.radius, this._scaledPosition);
  9598. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9599. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9600. var payload = {
  9601. collider: {
  9602. position: this._scaledPosition.asArray(),
  9603. velocity: this._scaledVelocity.asArray(),
  9604. radius: collider.radius.asArray()
  9605. },
  9606. collisionId: collisionIndex,
  9607. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9608. maximumRetry: maximumRetry
  9609. };
  9610. var message = {
  9611. payload: payload,
  9612. taskType: WorkerTaskType.COLLIDE
  9613. };
  9614. this._worker.postMessage(message);
  9615. };
  9616. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9617. this._scene = scene;
  9618. this._scene.registerAfterRender(this._afterRender);
  9619. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9620. this._worker = new Worker(workerUrl);
  9621. this._worker.onmessage = this._onMessageFromWorker;
  9622. var message = {
  9623. payload: {},
  9624. taskType: WorkerTaskType.INIT
  9625. };
  9626. this._worker.postMessage(message);
  9627. };
  9628. CollisionCoordinatorWorker.prototype.destroy = function () {
  9629. this._scene.unregisterAfterRender(this._afterRender);
  9630. this._worker.terminate();
  9631. };
  9632. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9633. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9634. this.onMeshUpdated(mesh);
  9635. };
  9636. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9637. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9638. };
  9639. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9640. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9641. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9642. this.onGeometryUpdated(geometry);
  9643. };
  9644. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9645. this._toRemoveGeometryArray.push(geometry.id);
  9646. };
  9647. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9648. var submeshes = [];
  9649. if (mesh.subMeshes) {
  9650. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9651. return {
  9652. position: idx,
  9653. verticesStart: sm.verticesStart,
  9654. verticesCount: sm.verticesCount,
  9655. indexStart: sm.indexStart,
  9656. indexCount: sm.indexCount,
  9657. hasMaterial: !!sm.getMaterial(),
  9658. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9659. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9660. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9661. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9662. };
  9663. });
  9664. }
  9665. var geometryId = null;
  9666. if (mesh instanceof BABYLON.Mesh) {
  9667. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9668. }
  9669. else if (mesh instanceof BABYLON.InstancedMesh) {
  9670. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9671. }
  9672. return {
  9673. uniqueId: mesh.uniqueId,
  9674. id: mesh.id,
  9675. name: mesh.name,
  9676. geometryId: geometryId,
  9677. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9678. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9679. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9680. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9681. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9682. subMeshes: submeshes,
  9683. checkCollisions: mesh.checkCollisions
  9684. };
  9685. };
  9686. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9687. return {
  9688. id: geometry.id,
  9689. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9690. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9691. indices: new Int32Array(geometry.getIndices() || []),
  9692. };
  9693. };
  9694. return CollisionCoordinatorWorker;
  9695. })();
  9696. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9697. var CollisionCoordinatorLegacy = (function () {
  9698. function CollisionCoordinatorLegacy() {
  9699. this._scaledPosition = BABYLON.Vector3.Zero();
  9700. this._scaledVelocity = BABYLON.Vector3.Zero();
  9701. this._finalPosition = BABYLON.Vector3.Zero();
  9702. }
  9703. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9704. position.divideToRef(collider.radius, this._scaledPosition);
  9705. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9706. collider.collidedMesh = null;
  9707. collider.retry = 0;
  9708. collider.initialVelocity = this._scaledVelocity;
  9709. collider.initialPosition = this._scaledPosition;
  9710. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9711. this._finalPosition.multiplyInPlace(collider.radius);
  9712. //run the callback
  9713. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9714. };
  9715. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9716. this._scene = scene;
  9717. };
  9718. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9719. //Legacy need no destruction method.
  9720. };
  9721. //No update in legacy mode
  9722. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9723. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9724. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9725. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9726. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9727. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9728. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9729. if (excludedMesh === void 0) { excludedMesh = null; }
  9730. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9731. if (collider.retry >= maximumRetry) {
  9732. finalPosition.copyFrom(position);
  9733. return;
  9734. }
  9735. collider._initialize(position, velocity, closeDistance);
  9736. // Check all meshes
  9737. for (var index = 0; index < this._scene.meshes.length; index++) {
  9738. var mesh = this._scene.meshes[index];
  9739. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9740. mesh._checkCollision(collider);
  9741. }
  9742. }
  9743. if (!collider.collisionFound) {
  9744. position.addToRef(velocity, finalPosition);
  9745. return;
  9746. }
  9747. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9748. collider._getResponse(position, velocity);
  9749. }
  9750. if (velocity.length() <= closeDistance) {
  9751. finalPosition.copyFrom(position);
  9752. return;
  9753. }
  9754. collider.retry++;
  9755. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9756. };
  9757. return CollisionCoordinatorLegacy;
  9758. })();
  9759. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9760. })(BABYLON || (BABYLON = {}));
  9761. var BABYLON;
  9762. (function (BABYLON) {
  9763. var VRCameraMetrics = (function () {
  9764. function VRCameraMetrics() {
  9765. this.compensateDistorsion = true;
  9766. }
  9767. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9768. get: function () {
  9769. return this.hResolution / (2 * this.vResolution);
  9770. },
  9771. enumerable: true,
  9772. configurable: true
  9773. });
  9774. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9775. get: function () {
  9776. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9782. get: function () {
  9783. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9784. var h = (4 * meters) / this.hScreenSize;
  9785. return BABYLON.Matrix.Translation(h, 0, 0);
  9786. },
  9787. enumerable: true,
  9788. configurable: true
  9789. });
  9790. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9791. get: function () {
  9792. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9793. var h = (4 * meters) / this.hScreenSize;
  9794. return BABYLON.Matrix.Translation(-h, 0, 0);
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9800. get: function () {
  9801. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9807. get: function () {
  9808. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. VRCameraMetrics.GetDefault = function () {
  9814. var result = new VRCameraMetrics();
  9815. result.hResolution = 1280;
  9816. result.vResolution = 800;
  9817. result.hScreenSize = 0.149759993;
  9818. result.vScreenSize = 0.0935999975;
  9819. result.vScreenCenter = 0.0467999987,
  9820. result.eyeToScreenDistance = 0.0410000011;
  9821. result.lensSeparationDistance = 0.0635000020;
  9822. result.interpupillaryDistance = 0.0640000030;
  9823. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9824. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9825. result.postProcessScaleFactor = 1.714605507808412;
  9826. result.lensCenterOffset = 0.151976421;
  9827. return result;
  9828. };
  9829. return VRCameraMetrics;
  9830. })();
  9831. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9832. var Camera = (function (_super) {
  9833. __extends(Camera, _super);
  9834. function Camera(name, position, scene) {
  9835. _super.call(this, name, scene);
  9836. this.position = position;
  9837. // Members
  9838. this.upVector = BABYLON.Vector3.Up();
  9839. this.orthoLeft = null;
  9840. this.orthoRight = null;
  9841. this.orthoBottom = null;
  9842. this.orthoTop = null;
  9843. this.fov = 0.8;
  9844. this.minZ = 1.0;
  9845. this.maxZ = 10000.0;
  9846. this.inertia = 0.9;
  9847. this.mode = Camera.PERSPECTIVE_CAMERA;
  9848. this.isIntermediate = false;
  9849. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9850. this.layerMask = 0x0FFFFFFF;
  9851. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9852. // Camera rig members
  9853. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9854. this._rigCameras = new Array();
  9855. // Cache
  9856. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9857. this._projectionMatrix = new BABYLON.Matrix();
  9858. this._postProcesses = new Array();
  9859. this._postProcessesTakenIndices = [];
  9860. this._activeMeshes = new BABYLON.SmartArray(256);
  9861. this._globalPosition = BABYLON.Vector3.Zero();
  9862. scene.addCamera(this);
  9863. if (!scene.activeCamera) {
  9864. scene.activeCamera = this;
  9865. }
  9866. }
  9867. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9868. get: function () {
  9869. return Camera._PERSPECTIVE_CAMERA;
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9875. get: function () {
  9876. return Camera._ORTHOGRAPHIC_CAMERA;
  9877. },
  9878. enumerable: true,
  9879. configurable: true
  9880. });
  9881. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9882. get: function () {
  9883. return Camera._FOVMODE_VERTICAL_FIXED;
  9884. },
  9885. enumerable: true,
  9886. configurable: true
  9887. });
  9888. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9889. get: function () {
  9890. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9891. },
  9892. enumerable: true,
  9893. configurable: true
  9894. });
  9895. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9896. get: function () {
  9897. return Camera._RIG_MODE_NONE;
  9898. },
  9899. enumerable: true,
  9900. configurable: true
  9901. });
  9902. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9903. get: function () {
  9904. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9910. get: function () {
  9911. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9917. get: function () {
  9918. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9924. get: function () {
  9925. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9931. get: function () {
  9932. return Camera._RIG_MODE_VR;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Object.defineProperty(Camera.prototype, "globalPosition", {
  9938. get: function () {
  9939. return this._globalPosition;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Camera.prototype.getActiveMeshes = function () {
  9945. return this._activeMeshes;
  9946. };
  9947. Camera.prototype.isActiveMesh = function (mesh) {
  9948. return (this._activeMeshes.indexOf(mesh) !== -1);
  9949. };
  9950. //Cache
  9951. Camera.prototype._initCache = function () {
  9952. _super.prototype._initCache.call(this);
  9953. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9954. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9955. this._cache.mode = undefined;
  9956. this._cache.minZ = undefined;
  9957. this._cache.maxZ = undefined;
  9958. this._cache.fov = undefined;
  9959. this._cache.aspectRatio = undefined;
  9960. this._cache.orthoLeft = undefined;
  9961. this._cache.orthoRight = undefined;
  9962. this._cache.orthoBottom = undefined;
  9963. this._cache.orthoTop = undefined;
  9964. this._cache.renderWidth = undefined;
  9965. this._cache.renderHeight = undefined;
  9966. };
  9967. Camera.prototype._updateCache = function (ignoreParentClass) {
  9968. if (!ignoreParentClass) {
  9969. _super.prototype._updateCache.call(this);
  9970. }
  9971. var engine = this.getEngine();
  9972. this._cache.position.copyFrom(this.position);
  9973. this._cache.upVector.copyFrom(this.upVector);
  9974. this._cache.mode = this.mode;
  9975. this._cache.minZ = this.minZ;
  9976. this._cache.maxZ = this.maxZ;
  9977. this._cache.fov = this.fov;
  9978. this._cache.aspectRatio = engine.getAspectRatio(this);
  9979. this._cache.orthoLeft = this.orthoLeft;
  9980. this._cache.orthoRight = this.orthoRight;
  9981. this._cache.orthoBottom = this.orthoBottom;
  9982. this._cache.orthoTop = this.orthoTop;
  9983. this._cache.renderWidth = engine.getRenderWidth();
  9984. this._cache.renderHeight = engine.getRenderHeight();
  9985. };
  9986. Camera.prototype._updateFromScene = function () {
  9987. this.updateCache();
  9988. this._update();
  9989. };
  9990. // Synchronized
  9991. Camera.prototype._isSynchronized = function () {
  9992. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9993. };
  9994. Camera.prototype._isSynchronizedViewMatrix = function () {
  9995. if (!_super.prototype._isSynchronized.call(this))
  9996. return false;
  9997. return this._cache.position.equals(this.position)
  9998. && this._cache.upVector.equals(this.upVector)
  9999. && this.isSynchronizedWithParent();
  10000. };
  10001. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10002. var check = this._cache.mode === this.mode
  10003. && this._cache.minZ === this.minZ
  10004. && this._cache.maxZ === this.maxZ;
  10005. if (!check) {
  10006. return false;
  10007. }
  10008. var engine = this.getEngine();
  10009. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10010. check = this._cache.fov === this.fov
  10011. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10012. }
  10013. else {
  10014. check = this._cache.orthoLeft === this.orthoLeft
  10015. && this._cache.orthoRight === this.orthoRight
  10016. && this._cache.orthoBottom === this.orthoBottom
  10017. && this._cache.orthoTop === this.orthoTop
  10018. && this._cache.renderWidth === engine.getRenderWidth()
  10019. && this._cache.renderHeight === engine.getRenderHeight();
  10020. }
  10021. return check;
  10022. };
  10023. // Controls
  10024. Camera.prototype.attachControl = function (element) {
  10025. };
  10026. Camera.prototype.detachControl = function (element) {
  10027. };
  10028. Camera.prototype._update = function () {
  10029. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10030. this._updateRigCameras();
  10031. }
  10032. this._checkInputs();
  10033. };
  10034. Camera.prototype._checkInputs = function () {
  10035. };
  10036. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10037. if (insertAt === void 0) { insertAt = null; }
  10038. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10039. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10040. return 0;
  10041. }
  10042. if (insertAt == null || insertAt < 0) {
  10043. this._postProcesses.push(postProcess);
  10044. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10045. return this._postProcesses.length - 1;
  10046. }
  10047. var add = 0;
  10048. if (this._postProcesses[insertAt]) {
  10049. var start = this._postProcesses.length - 1;
  10050. for (var i = start; i >= insertAt + 1; --i) {
  10051. this._postProcesses[i + 1] = this._postProcesses[i];
  10052. }
  10053. add = 1;
  10054. }
  10055. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10056. if (this._postProcessesTakenIndices[i] < insertAt) {
  10057. continue;
  10058. }
  10059. start = this._postProcessesTakenIndices.length - 1;
  10060. for (var j = start; j >= i; --j) {
  10061. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10062. }
  10063. this._postProcessesTakenIndices[i] = insertAt;
  10064. break;
  10065. }
  10066. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10067. this._postProcessesTakenIndices.push(insertAt);
  10068. }
  10069. var result = insertAt + add;
  10070. this._postProcesses[result] = postProcess;
  10071. return result;
  10072. };
  10073. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10074. if (atIndices === void 0) { atIndices = null; }
  10075. var result = [];
  10076. if (!atIndices) {
  10077. var length = this._postProcesses.length;
  10078. for (var i = 0; i < length; i++) {
  10079. if (this._postProcesses[i] !== postProcess) {
  10080. continue;
  10081. }
  10082. delete this._postProcesses[i];
  10083. var index = this._postProcessesTakenIndices.indexOf(i);
  10084. this._postProcessesTakenIndices.splice(index, 1);
  10085. }
  10086. }
  10087. else {
  10088. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10089. for (i = 0; i < atIndices.length; i++) {
  10090. var foundPostProcess = this._postProcesses[atIndices[i]];
  10091. if (foundPostProcess !== postProcess) {
  10092. result.push(i);
  10093. continue;
  10094. }
  10095. delete this._postProcesses[atIndices[i]];
  10096. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10097. this._postProcessesTakenIndices.splice(index, 1);
  10098. }
  10099. }
  10100. return result;
  10101. };
  10102. Camera.prototype.getWorldMatrix = function () {
  10103. if (!this._worldMatrix) {
  10104. this._worldMatrix = BABYLON.Matrix.Identity();
  10105. }
  10106. var viewMatrix = this.getViewMatrix();
  10107. viewMatrix.invertToRef(this._worldMatrix);
  10108. return this._worldMatrix;
  10109. };
  10110. Camera.prototype._getViewMatrix = function () {
  10111. return BABYLON.Matrix.Identity();
  10112. };
  10113. Camera.prototype.getViewMatrix = function (force) {
  10114. this._computedViewMatrix = this._computeViewMatrix(force);
  10115. if (!force && this._isSynchronizedViewMatrix()) {
  10116. return this._computedViewMatrix;
  10117. }
  10118. if (!this.parent || !this.parent.getWorldMatrix) {
  10119. this._globalPosition.copyFrom(this.position);
  10120. }
  10121. else {
  10122. if (!this._worldMatrix) {
  10123. this._worldMatrix = BABYLON.Matrix.Identity();
  10124. }
  10125. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10126. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10127. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10128. this._computedViewMatrix.invert();
  10129. this._markSyncedWithParent();
  10130. }
  10131. this._currentRenderId = this.getScene().getRenderId();
  10132. return this._computedViewMatrix;
  10133. };
  10134. Camera.prototype._computeViewMatrix = function (force) {
  10135. if (!force && this._isSynchronizedViewMatrix()) {
  10136. return this._computedViewMatrix;
  10137. }
  10138. this._computedViewMatrix = this._getViewMatrix();
  10139. this._currentRenderId = this.getScene().getRenderId();
  10140. return this._computedViewMatrix;
  10141. };
  10142. Camera.prototype.getProjectionMatrix = function (force) {
  10143. if (!force && this._isSynchronizedProjectionMatrix()) {
  10144. return this._projectionMatrix;
  10145. }
  10146. var engine = this.getEngine();
  10147. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10148. if (this.minZ <= 0) {
  10149. this.minZ = 0.1;
  10150. }
  10151. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10152. return this._projectionMatrix;
  10153. }
  10154. var halfWidth = engine.getRenderWidth() / 2.0;
  10155. var halfHeight = engine.getRenderHeight() / 2.0;
  10156. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10157. return this._projectionMatrix;
  10158. };
  10159. Camera.prototype.dispose = function () {
  10160. // Remove from scene
  10161. this.getScene().removeCamera(this);
  10162. while (this._rigCameras.length > 0) {
  10163. this._rigCameras.pop().dispose();
  10164. }
  10165. // Postprocesses
  10166. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10167. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10168. }
  10169. };
  10170. // ---- Camera rigs section ----
  10171. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10172. while (this._rigCameras.length > 0) {
  10173. this._rigCameras.pop().dispose();
  10174. }
  10175. this.cameraRigMode = mode;
  10176. this._cameraRigParams = {};
  10177. switch (this.cameraRigMode) {
  10178. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10179. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10180. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10181. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10182. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10183. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10184. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10185. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10186. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10187. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10188. break;
  10189. }
  10190. var postProcesses = new Array();
  10191. switch (this.cameraRigMode) {
  10192. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10193. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10194. this._rigCameras[0].isIntermediate = true;
  10195. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10196. postProcesses[1].onApply = function (effect) {
  10197. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10198. };
  10199. break;
  10200. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10201. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10202. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10203. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10204. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10205. var secondCamIndex = 1 - firstCamIndex;
  10206. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10207. this._rigCameras[firstCamIndex].isIntermediate = true;
  10208. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10209. break;
  10210. case Camera.RIG_MODE_VR:
  10211. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10212. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10213. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10214. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10215. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10216. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10217. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10218. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10219. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10220. if (metrics.compensateDistorsion) {
  10221. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10222. }
  10223. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10224. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10225. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10226. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10227. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10228. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10229. if (metrics.compensateDistorsion) {
  10230. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10231. }
  10232. break;
  10233. }
  10234. this._update();
  10235. };
  10236. Camera.prototype._getVRProjectionMatrix = function () {
  10237. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10238. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10239. return this._projectionMatrix;
  10240. };
  10241. Camera.prototype.setCameraRigParameter = function (name, value) {
  10242. this._cameraRigParams[name] = value;
  10243. //provisionnally:
  10244. if (name === "interaxialDistance") {
  10245. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10246. }
  10247. };
  10248. /**
  10249. * May needs to be overridden by children so sub has required properties to be copied
  10250. */
  10251. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10252. return null;
  10253. };
  10254. /**
  10255. * May needs to be overridden by children
  10256. */
  10257. Camera.prototype._updateRigCameras = function () {
  10258. for (var i = 0; i < this._rigCameras.length; i++) {
  10259. this._rigCameras[i].minZ = this.minZ;
  10260. this._rigCameras[i].maxZ = this.maxZ;
  10261. this._rigCameras[i].fov = this.fov;
  10262. }
  10263. // only update viewport when ANAGLYPH
  10264. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10265. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10266. }
  10267. };
  10268. // Statics
  10269. Camera._PERSPECTIVE_CAMERA = 0;
  10270. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10271. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10272. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10273. Camera._RIG_MODE_NONE = 0;
  10274. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10275. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10276. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10277. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10278. Camera._RIG_MODE_VR = 20;
  10279. return Camera;
  10280. })(BABYLON.Node);
  10281. BABYLON.Camera = Camera;
  10282. })(BABYLON || (BABYLON = {}));
  10283. var BABYLON;
  10284. (function (BABYLON) {
  10285. var TargetCamera = (function (_super) {
  10286. __extends(TargetCamera, _super);
  10287. function TargetCamera(name, position, scene) {
  10288. _super.call(this, name, position, scene);
  10289. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10290. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10291. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10292. this.speed = 2.0;
  10293. this.noRotationConstraint = false;
  10294. this.lockedTarget = null;
  10295. this._currentTarget = BABYLON.Vector3.Zero();
  10296. this._viewMatrix = BABYLON.Matrix.Zero();
  10297. this._camMatrix = BABYLON.Matrix.Zero();
  10298. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10299. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10300. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10301. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10302. this._lookAtTemp = BABYLON.Matrix.Zero();
  10303. this._tempMatrix = BABYLON.Matrix.Zero();
  10304. }
  10305. TargetCamera.prototype._getLockedTargetPosition = function () {
  10306. if (!this.lockedTarget) {
  10307. return null;
  10308. }
  10309. return this.lockedTarget.position || this.lockedTarget;
  10310. };
  10311. // Cache
  10312. TargetCamera.prototype._initCache = function () {
  10313. _super.prototype._initCache.call(this);
  10314. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10315. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10316. };
  10317. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10318. if (!ignoreParentClass) {
  10319. _super.prototype._updateCache.call(this);
  10320. }
  10321. var lockedTargetPosition = this._getLockedTargetPosition();
  10322. if (!lockedTargetPosition) {
  10323. this._cache.lockedTarget = null;
  10324. }
  10325. else {
  10326. if (!this._cache.lockedTarget) {
  10327. this._cache.lockedTarget = lockedTargetPosition.clone();
  10328. }
  10329. else {
  10330. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10331. }
  10332. }
  10333. this._cache.rotation.copyFrom(this.rotation);
  10334. };
  10335. // Synchronized
  10336. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10337. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10338. return false;
  10339. }
  10340. var lockedTargetPosition = this._getLockedTargetPosition();
  10341. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10342. && this._cache.rotation.equals(this.rotation);
  10343. };
  10344. // Methods
  10345. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10346. var engine = this.getEngine();
  10347. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10348. };
  10349. // Target
  10350. TargetCamera.prototype.setTarget = function (target) {
  10351. this.upVector.normalize();
  10352. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10353. this._camMatrix.invert();
  10354. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10355. var vDir = target.subtract(this.position);
  10356. if (vDir.x >= 0.0) {
  10357. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10358. }
  10359. else {
  10360. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10361. }
  10362. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10363. if (isNaN(this.rotation.x)) {
  10364. this.rotation.x = 0;
  10365. }
  10366. if (isNaN(this.rotation.y)) {
  10367. this.rotation.y = 0;
  10368. }
  10369. if (isNaN(this.rotation.z)) {
  10370. this.rotation.z = 0;
  10371. }
  10372. };
  10373. TargetCamera.prototype.getTarget = function () {
  10374. return this._currentTarget;
  10375. };
  10376. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10377. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10378. };
  10379. TargetCamera.prototype._updatePosition = function () {
  10380. this.position.addInPlace(this.cameraDirection);
  10381. };
  10382. TargetCamera.prototype._checkInputs = function () {
  10383. var needToMove = this._decideIfNeedsToMove();
  10384. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10385. // Move
  10386. if (needToMove) {
  10387. this._updatePosition();
  10388. }
  10389. // Rotate
  10390. if (needToRotate) {
  10391. this.rotation.x += this.cameraRotation.x;
  10392. this.rotation.y += this.cameraRotation.y;
  10393. if (!this.noRotationConstraint) {
  10394. var limit = (Math.PI / 2) * 0.95;
  10395. if (this.rotation.x > limit)
  10396. this.rotation.x = limit;
  10397. if (this.rotation.x < -limit)
  10398. this.rotation.x = -limit;
  10399. }
  10400. }
  10401. // Inertia
  10402. if (needToMove) {
  10403. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10404. this.cameraDirection.x = 0;
  10405. }
  10406. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10407. this.cameraDirection.y = 0;
  10408. }
  10409. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10410. this.cameraDirection.z = 0;
  10411. }
  10412. this.cameraDirection.scaleInPlace(this.inertia);
  10413. }
  10414. if (needToRotate) {
  10415. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10416. this.cameraRotation.x = 0;
  10417. }
  10418. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10419. this.cameraRotation.y = 0;
  10420. }
  10421. this.cameraRotation.scaleInPlace(this.inertia);
  10422. }
  10423. _super.prototype._checkInputs.call(this);
  10424. };
  10425. TargetCamera.prototype._getViewMatrix = function () {
  10426. if (!this.lockedTarget) {
  10427. // Compute
  10428. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10429. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10430. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10431. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10432. this._lookAtTemp.invert();
  10433. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10434. }
  10435. else {
  10436. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10437. }
  10438. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10439. // Computing target and final matrix
  10440. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10441. }
  10442. else {
  10443. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10444. }
  10445. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10446. return this._viewMatrix;
  10447. };
  10448. TargetCamera.prototype._getVRViewMatrix = function () {
  10449. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10450. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10451. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10452. // Computing target and final matrix
  10453. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10454. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10455. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10456. return this._viewMatrix;
  10457. };
  10458. /**
  10459. * @override
  10460. * Override Camera.createRigCamera
  10461. */
  10462. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10463. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10464. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10465. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10466. rigCamera._cameraRigParams = {};
  10467. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10468. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10469. }
  10470. return rigCamera;
  10471. }
  10472. return null;
  10473. };
  10474. /**
  10475. * @override
  10476. * Override Camera._updateRigCameras
  10477. */
  10478. TargetCamera.prototype._updateRigCameras = function () {
  10479. switch (this.cameraRigMode) {
  10480. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10481. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10482. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10483. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10484. case BABYLON.Camera.RIG_MODE_VR:
  10485. var camLeft = this._rigCameras[0];
  10486. var camRight = this._rigCameras[1];
  10487. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10488. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10489. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10490. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10491. camLeft.position.copyFrom(this.position);
  10492. camRight.position.copyFrom(this.position);
  10493. }
  10494. else {
  10495. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10496. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10497. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10498. camLeft.setTarget(this.getTarget());
  10499. camRight.setTarget(this.getTarget());
  10500. }
  10501. break;
  10502. }
  10503. _super.prototype._updateRigCameras.call(this);
  10504. };
  10505. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10506. if (!this._rigCamTransformMatrix) {
  10507. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10508. }
  10509. var target = this.getTarget();
  10510. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10511. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10512. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10513. };
  10514. return TargetCamera;
  10515. })(BABYLON.Camera);
  10516. BABYLON.TargetCamera = TargetCamera;
  10517. })(BABYLON || (BABYLON = {}));
  10518. var BABYLON;
  10519. (function (BABYLON) {
  10520. var FreeCamera = (function (_super) {
  10521. __extends(FreeCamera, _super);
  10522. function FreeCamera(name, position, scene) {
  10523. var _this = this;
  10524. _super.call(this, name, position, scene);
  10525. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10526. this.keysUp = [38];
  10527. this.keysDown = [40];
  10528. this.keysLeft = [37];
  10529. this.keysRight = [39];
  10530. this.checkCollisions = false;
  10531. this.applyGravity = false;
  10532. this.angularSensibility = 2000.0;
  10533. this._keys = [];
  10534. this._collider = new BABYLON.Collider();
  10535. this._needMoveForGravity = false;
  10536. this._oldPosition = BABYLON.Vector3.Zero();
  10537. this._diffPosition = BABYLON.Vector3.Zero();
  10538. this._newPosition = BABYLON.Vector3.Zero();
  10539. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10540. if (collidedMesh === void 0) { collidedMesh = null; }
  10541. //TODO move this to the collision coordinator!
  10542. if (_this.getScene().workerCollisions)
  10543. newPosition.multiplyInPlace(_this._collider.radius);
  10544. var updatePosition = function (newPos) {
  10545. _this._newPosition.copyFrom(newPos);
  10546. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10547. var oldPosition = _this.position.clone();
  10548. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10549. _this.position.addInPlace(_this._diffPosition);
  10550. if (_this.onCollide && collidedMesh) {
  10551. _this.onCollide(collidedMesh);
  10552. }
  10553. }
  10554. };
  10555. updatePosition(newPosition);
  10556. };
  10557. }
  10558. // Controls
  10559. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10560. var _this = this;
  10561. var previousPosition;
  10562. var engine = this.getEngine();
  10563. if (this._attachedElement) {
  10564. return;
  10565. }
  10566. this._attachedElement = element;
  10567. if (this._onMouseDown === undefined) {
  10568. this._onMouseDown = function (evt) {
  10569. previousPosition = {
  10570. x: evt.clientX,
  10571. y: evt.clientY
  10572. };
  10573. if (!noPreventDefault) {
  10574. evt.preventDefault();
  10575. }
  10576. };
  10577. this._onMouseUp = function (evt) {
  10578. previousPosition = null;
  10579. if (!noPreventDefault) {
  10580. evt.preventDefault();
  10581. }
  10582. };
  10583. this._onMouseOut = function (evt) {
  10584. previousPosition = null;
  10585. _this._keys = [];
  10586. if (!noPreventDefault) {
  10587. evt.preventDefault();
  10588. }
  10589. };
  10590. this._onMouseMove = function (evt) {
  10591. if (!previousPosition && !engine.isPointerLock) {
  10592. return;
  10593. }
  10594. var offsetX;
  10595. var offsetY;
  10596. if (!engine.isPointerLock) {
  10597. offsetX = evt.clientX - previousPosition.x;
  10598. offsetY = evt.clientY - previousPosition.y;
  10599. }
  10600. else {
  10601. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10602. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10603. }
  10604. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10605. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10606. previousPosition = {
  10607. x: evt.clientX,
  10608. y: evt.clientY
  10609. };
  10610. if (!noPreventDefault) {
  10611. evt.preventDefault();
  10612. }
  10613. };
  10614. this._onKeyDown = function (evt) {
  10615. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10616. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10617. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10618. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10619. var index = _this._keys.indexOf(evt.keyCode);
  10620. if (index === -1) {
  10621. _this._keys.push(evt.keyCode);
  10622. }
  10623. if (!noPreventDefault) {
  10624. evt.preventDefault();
  10625. }
  10626. }
  10627. };
  10628. this._onKeyUp = function (evt) {
  10629. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10630. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10631. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10632. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10633. var index = _this._keys.indexOf(evt.keyCode);
  10634. if (index >= 0) {
  10635. _this._keys.splice(index, 1);
  10636. }
  10637. if (!noPreventDefault) {
  10638. evt.preventDefault();
  10639. }
  10640. }
  10641. };
  10642. this._onLostFocus = function () {
  10643. _this._keys = [];
  10644. };
  10645. this._reset = function () {
  10646. _this._keys = [];
  10647. previousPosition = null;
  10648. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10649. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10650. };
  10651. }
  10652. element.addEventListener("mousedown", this._onMouseDown, false);
  10653. element.addEventListener("mouseup", this._onMouseUp, false);
  10654. element.addEventListener("mouseout", this._onMouseOut, false);
  10655. element.addEventListener("mousemove", this._onMouseMove, false);
  10656. BABYLON.Tools.RegisterTopRootEvents([
  10657. { name: "keydown", handler: this._onKeyDown },
  10658. { name: "keyup", handler: this._onKeyUp },
  10659. { name: "blur", handler: this._onLostFocus }
  10660. ]);
  10661. };
  10662. FreeCamera.prototype.detachControl = function (element) {
  10663. if (this._attachedElement != element) {
  10664. return;
  10665. }
  10666. element.removeEventListener("mousedown", this._onMouseDown);
  10667. element.removeEventListener("mouseup", this._onMouseUp);
  10668. element.removeEventListener("mouseout", this._onMouseOut);
  10669. element.removeEventListener("mousemove", this._onMouseMove);
  10670. BABYLON.Tools.UnregisterTopRootEvents([
  10671. { name: "keydown", handler: this._onKeyDown },
  10672. { name: "keyup", handler: this._onKeyUp },
  10673. { name: "blur", handler: this._onLostFocus }
  10674. ]);
  10675. this._attachedElement = null;
  10676. if (this._reset) {
  10677. this._reset();
  10678. }
  10679. };
  10680. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10681. var globalPosition;
  10682. if (this.parent) {
  10683. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10684. }
  10685. else {
  10686. globalPosition = this.position;
  10687. }
  10688. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10689. this._collider.radius = this.ellipsoid;
  10690. //add gravity to the velocity to prevent the dual-collision checking
  10691. if (this.applyGravity) {
  10692. velocity.addInPlace(this.getScene().gravity);
  10693. }
  10694. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10695. };
  10696. FreeCamera.prototype._checkInputs = function () {
  10697. if (!this._localDirection) {
  10698. this._localDirection = BABYLON.Vector3.Zero();
  10699. this._transformedDirection = BABYLON.Vector3.Zero();
  10700. }
  10701. // Keyboard
  10702. for (var index = 0; index < this._keys.length; index++) {
  10703. var keyCode = this._keys[index];
  10704. var speed = this._computeLocalCameraSpeed();
  10705. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10706. this._localDirection.copyFromFloats(-speed, 0, 0);
  10707. }
  10708. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10709. this._localDirection.copyFromFloats(0, 0, speed);
  10710. }
  10711. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10712. this._localDirection.copyFromFloats(speed, 0, 0);
  10713. }
  10714. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10715. this._localDirection.copyFromFloats(0, 0, -speed);
  10716. }
  10717. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10718. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10719. this.cameraDirection.addInPlace(this._transformedDirection);
  10720. }
  10721. _super.prototype._checkInputs.call(this);
  10722. };
  10723. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10724. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10725. };
  10726. FreeCamera.prototype._updatePosition = function () {
  10727. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10728. this._collideWithWorld(this.cameraDirection);
  10729. }
  10730. else {
  10731. this.position.addInPlace(this.cameraDirection);
  10732. }
  10733. };
  10734. return FreeCamera;
  10735. })(BABYLON.TargetCamera);
  10736. BABYLON.FreeCamera = FreeCamera;
  10737. })(BABYLON || (BABYLON = {}));
  10738. var BABYLON;
  10739. (function (BABYLON) {
  10740. var FollowCamera = (function (_super) {
  10741. __extends(FollowCamera, _super);
  10742. function FollowCamera(name, position, scene) {
  10743. _super.call(this, name, position, scene);
  10744. this.radius = 12;
  10745. this.rotationOffset = 0;
  10746. this.heightOffset = 4;
  10747. this.cameraAcceleration = 0.05;
  10748. this.maxCameraSpeed = 20;
  10749. }
  10750. FollowCamera.prototype.getRadians = function (degrees) {
  10751. return degrees * Math.PI / 180;
  10752. };
  10753. FollowCamera.prototype.follow = function (cameraTarget) {
  10754. if (!cameraTarget)
  10755. return;
  10756. var yRotation;
  10757. if (cameraTarget.rotationQuaternion) {
  10758. var rotMatrix = new BABYLON.Matrix();
  10759. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10760. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10761. }
  10762. else {
  10763. yRotation = cameraTarget.rotation.y;
  10764. }
  10765. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10766. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10767. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10768. var dx = targetX - this.position.x;
  10769. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10770. var dz = (targetZ) - this.position.z;
  10771. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10772. var vy = dy * this.cameraAcceleration;
  10773. var vz = dz * this.cameraAcceleration * 2;
  10774. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10775. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10776. }
  10777. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10778. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10779. }
  10780. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10781. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10782. }
  10783. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10784. this.setTarget(cameraTarget.position);
  10785. };
  10786. FollowCamera.prototype._checkInputs = function () {
  10787. _super.prototype._checkInputs.call(this);
  10788. this.follow(this.target);
  10789. };
  10790. return FollowCamera;
  10791. })(BABYLON.TargetCamera);
  10792. BABYLON.FollowCamera = FollowCamera;
  10793. var ArcFollowCamera = (function (_super) {
  10794. __extends(ArcFollowCamera, _super);
  10795. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10796. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10797. this.alpha = alpha;
  10798. this.beta = beta;
  10799. this.radius = radius;
  10800. this.target = target;
  10801. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10802. this.follow();
  10803. }
  10804. ArcFollowCamera.prototype.follow = function () {
  10805. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10806. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10807. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10808. this.position = this.target.position.add(this._cartesianCoordinates);
  10809. this.setTarget(this.target.position);
  10810. };
  10811. ArcFollowCamera.prototype._checkInputs = function () {
  10812. _super.prototype._checkInputs.call(this);
  10813. this.follow();
  10814. };
  10815. return ArcFollowCamera;
  10816. })(BABYLON.TargetCamera);
  10817. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10818. })(BABYLON || (BABYLON = {}));
  10819. var BABYLON;
  10820. (function (BABYLON) {
  10821. // We're mainly based on the logic defined into the FreeCamera code
  10822. var TouchCamera = (function (_super) {
  10823. __extends(TouchCamera, _super);
  10824. function TouchCamera(name, position, scene) {
  10825. _super.call(this, name, position, scene);
  10826. this._offsetX = null;
  10827. this._offsetY = null;
  10828. this._pointerCount = 0;
  10829. this._pointerPressed = [];
  10830. this.angularSensibility = 200000.0;
  10831. this.moveSensibility = 500.0;
  10832. }
  10833. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10834. var _this = this;
  10835. var previousPosition;
  10836. if (this._attachedCanvas) {
  10837. return;
  10838. }
  10839. this._attachedCanvas = canvas;
  10840. if (this._onPointerDown === undefined) {
  10841. this._onPointerDown = function (evt) {
  10842. if (!noPreventDefault) {
  10843. evt.preventDefault();
  10844. }
  10845. _this._pointerPressed.push(evt.pointerId);
  10846. if (_this._pointerPressed.length !== 1) {
  10847. return;
  10848. }
  10849. previousPosition = {
  10850. x: evt.clientX,
  10851. y: evt.clientY
  10852. };
  10853. };
  10854. this._onPointerUp = function (evt) {
  10855. if (!noPreventDefault) {
  10856. evt.preventDefault();
  10857. }
  10858. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10859. if (index === -1) {
  10860. return;
  10861. }
  10862. _this._pointerPressed.splice(index, 1);
  10863. if (index != 0) {
  10864. return;
  10865. }
  10866. previousPosition = null;
  10867. _this._offsetX = null;
  10868. _this._offsetY = null;
  10869. };
  10870. this._onPointerMove = function (evt) {
  10871. if (!noPreventDefault) {
  10872. evt.preventDefault();
  10873. }
  10874. if (!previousPosition) {
  10875. return;
  10876. }
  10877. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10878. if (index != 0) {
  10879. return;
  10880. }
  10881. _this._offsetX = evt.clientX - previousPosition.x;
  10882. _this._offsetY = -(evt.clientY - previousPosition.y);
  10883. };
  10884. this._onLostFocus = function () {
  10885. _this._offsetX = null;
  10886. _this._offsetY = null;
  10887. };
  10888. }
  10889. canvas.addEventListener("pointerdown", this._onPointerDown);
  10890. canvas.addEventListener("pointerup", this._onPointerUp);
  10891. canvas.addEventListener("pointerout", this._onPointerUp);
  10892. canvas.addEventListener("pointermove", this._onPointerMove);
  10893. BABYLON.Tools.RegisterTopRootEvents([
  10894. { name: "blur", handler: this._onLostFocus }
  10895. ]);
  10896. };
  10897. TouchCamera.prototype.detachControl = function (canvas) {
  10898. if (this._attachedCanvas != canvas) {
  10899. return;
  10900. }
  10901. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10902. canvas.removeEventListener("pointerup", this._onPointerUp);
  10903. canvas.removeEventListener("pointerout", this._onPointerUp);
  10904. canvas.removeEventListener("pointermove", this._onPointerMove);
  10905. BABYLON.Tools.UnregisterTopRootEvents([
  10906. { name: "blur", handler: this._onLostFocus }
  10907. ]);
  10908. this._attachedCanvas = null;
  10909. };
  10910. TouchCamera.prototype._checkInputs = function () {
  10911. if (this._offsetX) {
  10912. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10913. if (this._pointerPressed.length > 1) {
  10914. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10915. }
  10916. else {
  10917. var speed = this._computeLocalCameraSpeed();
  10918. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10919. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10920. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10921. }
  10922. }
  10923. _super.prototype._checkInputs.call(this);
  10924. };
  10925. return TouchCamera;
  10926. })(BABYLON.FreeCamera);
  10927. BABYLON.TouchCamera = TouchCamera;
  10928. })(BABYLON || (BABYLON = {}));
  10929. var BABYLON;
  10930. (function (BABYLON) {
  10931. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10932. var ArcRotateCamera = (function (_super) {
  10933. __extends(ArcRotateCamera, _super);
  10934. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10935. var _this = this;
  10936. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10937. this.alpha = alpha;
  10938. this.beta = beta;
  10939. this.radius = radius;
  10940. this.target = target;
  10941. this.inertialAlphaOffset = 0;
  10942. this.inertialBetaOffset = 0;
  10943. this.inertialRadiusOffset = 0;
  10944. this.lowerAlphaLimit = null;
  10945. this.upperAlphaLimit = null;
  10946. this.lowerBetaLimit = 0.01;
  10947. this.upperBetaLimit = Math.PI;
  10948. this.lowerRadiusLimit = null;
  10949. this.upperRadiusLimit = null;
  10950. this.angularSensibility = 1000.0;
  10951. this.wheelPrecision = 3.0;
  10952. this.pinchPrecision = 2.0;
  10953. this.panningSensibility = 50.0;
  10954. this.inertialPanningX = 0;
  10955. this.inertialPanningY = 0;
  10956. this.keysUp = [38];
  10957. this.keysDown = [40];
  10958. this.keysLeft = [37];
  10959. this.keysRight = [39];
  10960. this.zoomOnFactor = 1;
  10961. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10962. this.pinchInwards = true;
  10963. this.allowUpsideDown = true;
  10964. this._keys = [];
  10965. this._viewMatrix = new BABYLON.Matrix();
  10966. this._isRightClick = false;
  10967. this._isCtrlPushed = false;
  10968. this.checkCollisions = false;
  10969. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10970. this._collider = new BABYLON.Collider();
  10971. this._previousPosition = BABYLON.Vector3.Zero();
  10972. this._collisionVelocity = BABYLON.Vector3.Zero();
  10973. this._newPosition = BABYLON.Vector3.Zero();
  10974. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10975. if (collidedMesh === void 0) { collidedMesh = null; }
  10976. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10977. newPosition.multiplyInPlace(_this._collider.radius);
  10978. }
  10979. if (!collidedMesh) {
  10980. _this._previousPosition.copyFrom(_this.position);
  10981. }
  10982. else {
  10983. _this.setPosition(_this.position);
  10984. if (_this.onCollide) {
  10985. _this.onCollide(collidedMesh);
  10986. }
  10987. }
  10988. // Recompute because of constraints
  10989. var cosa = Math.cos(_this.alpha);
  10990. var sina = Math.sin(_this.alpha);
  10991. var cosb = Math.cos(_this.beta);
  10992. var sinb = Math.sin(_this.beta);
  10993. var target = _this._getTargetPosition();
  10994. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10995. _this.position.copyFrom(_this._newPosition);
  10996. var up = _this.upVector;
  10997. if (_this.allowUpsideDown && _this.beta < 0) {
  10998. var up = up.clone();
  10999. up = up.negate();
  11000. }
  11001. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11002. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11003. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11004. _this._collisionTriggered = false;
  11005. };
  11006. if (!this.target) {
  11007. this.target = BABYLON.Vector3.Zero();
  11008. }
  11009. this.getViewMatrix();
  11010. }
  11011. ArcRotateCamera.prototype._getTargetPosition = function () {
  11012. return this.target.position || this.target;
  11013. };
  11014. // Cache
  11015. ArcRotateCamera.prototype._initCache = function () {
  11016. _super.prototype._initCache.call(this);
  11017. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11018. this._cache.alpha = undefined;
  11019. this._cache.beta = undefined;
  11020. this._cache.radius = undefined;
  11021. this._cache.targetScreenOffset = undefined;
  11022. };
  11023. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11024. if (!ignoreParentClass) {
  11025. _super.prototype._updateCache.call(this);
  11026. }
  11027. this._cache.target.copyFrom(this._getTargetPosition());
  11028. this._cache.alpha = this.alpha;
  11029. this._cache.beta = this.beta;
  11030. this._cache.radius = this.radius;
  11031. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11032. };
  11033. // Synchronized
  11034. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11035. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11036. return false;
  11037. return this._cache.target.equals(this._getTargetPosition())
  11038. && this._cache.alpha === this.alpha
  11039. && this._cache.beta === this.beta
  11040. && this._cache.radius === this.radius
  11041. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11042. };
  11043. // Methods
  11044. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11045. var _this = this;
  11046. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11047. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11048. var previousPinchDistance = 0;
  11049. var pointers = new BABYLON.SmartCollection();
  11050. if (this._attachedElement) {
  11051. return;
  11052. }
  11053. this._attachedElement = element;
  11054. var engine = this.getEngine();
  11055. if (this._onPointerDown === undefined) {
  11056. this._onPointerDown = function (evt) {
  11057. // Manage panning with right click
  11058. _this._isRightClick = evt.button === 2 ? true : false;
  11059. // manage pointers
  11060. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11061. cacheSoloPointer = pointers.item(evt.pointerId);
  11062. if (!noPreventDefault) {
  11063. evt.preventDefault();
  11064. }
  11065. };
  11066. this._onPointerUp = function (evt) {
  11067. cacheSoloPointer = null;
  11068. previousPinchDistance = 0;
  11069. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11070. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11071. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11072. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11073. pointers.empty();
  11074. if (!noPreventDefault) {
  11075. evt.preventDefault();
  11076. }
  11077. };
  11078. this._onContextMenu = function (evt) {
  11079. evt.preventDefault();
  11080. };
  11081. this._onPointerMove = function (evt) {
  11082. if (!noPreventDefault) {
  11083. evt.preventDefault();
  11084. }
  11085. switch (pointers.count) {
  11086. case 1:
  11087. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11088. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11089. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11090. }
  11091. else {
  11092. var offsetX = evt.clientX - cacheSoloPointer.x;
  11093. var offsetY = evt.clientY - cacheSoloPointer.y;
  11094. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  11095. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  11096. }
  11097. cacheSoloPointer.x = evt.clientX;
  11098. cacheSoloPointer.y = evt.clientY;
  11099. break;
  11100. case 2:
  11101. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11102. pointers.item(evt.pointerId).x = evt.clientX;
  11103. pointers.item(evt.pointerId).y = evt.clientY;
  11104. var direction = _this.pinchInwards ? 1 : -1;
  11105. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11106. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11107. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11108. if (previousPinchDistance === 0) {
  11109. previousPinchDistance = pinchSquaredDistance;
  11110. return;
  11111. }
  11112. if (pinchSquaredDistance !== previousPinchDistance) {
  11113. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  11114. previousPinchDistance = pinchSquaredDistance;
  11115. }
  11116. break;
  11117. default:
  11118. if (pointers.item(evt.pointerId)) {
  11119. pointers.item(evt.pointerId).x = evt.clientX;
  11120. pointers.item(evt.pointerId).y = evt.clientY;
  11121. }
  11122. }
  11123. };
  11124. this._onMouseMove = function (evt) {
  11125. if (!engine.isPointerLock) {
  11126. return;
  11127. }
  11128. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11129. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11130. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  11131. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  11132. if (!noPreventDefault) {
  11133. evt.preventDefault();
  11134. }
  11135. };
  11136. this._wheel = function (event) {
  11137. var delta = 0;
  11138. if (event.wheelDelta) {
  11139. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11140. }
  11141. else if (event.detail) {
  11142. delta = -event.detail / _this.wheelPrecision;
  11143. }
  11144. if (delta)
  11145. _this.inertialRadiusOffset += delta;
  11146. if (event.preventDefault) {
  11147. if (!noPreventDefault) {
  11148. event.preventDefault();
  11149. }
  11150. }
  11151. };
  11152. this._onKeyDown = function (evt) {
  11153. _this._isCtrlPushed = evt.ctrlKey;
  11154. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11155. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11156. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11157. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11158. var index = _this._keys.indexOf(evt.keyCode);
  11159. if (index === -1) {
  11160. _this._keys.push(evt.keyCode);
  11161. }
  11162. if (evt.preventDefault) {
  11163. if (!noPreventDefault) {
  11164. evt.preventDefault();
  11165. }
  11166. }
  11167. }
  11168. };
  11169. this._onKeyUp = function (evt) {
  11170. _this._isCtrlPushed = evt.ctrlKey;
  11171. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11172. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11173. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11174. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11175. var index = _this._keys.indexOf(evt.keyCode);
  11176. if (index >= 0) {
  11177. _this._keys.splice(index, 1);
  11178. }
  11179. if (evt.preventDefault) {
  11180. if (!noPreventDefault) {
  11181. evt.preventDefault();
  11182. }
  11183. }
  11184. }
  11185. };
  11186. this._onLostFocus = function () {
  11187. _this._keys = [];
  11188. pointers.empty();
  11189. previousPinchDistance = 0;
  11190. cacheSoloPointer = null;
  11191. };
  11192. this._onGestureStart = function (e) {
  11193. if (window.MSGesture === undefined) {
  11194. return;
  11195. }
  11196. if (!_this._MSGestureHandler) {
  11197. _this._MSGestureHandler = new MSGesture();
  11198. _this._MSGestureHandler.target = element;
  11199. }
  11200. _this._MSGestureHandler.addPointer(e.pointerId);
  11201. };
  11202. this._onGesture = function (e) {
  11203. _this.radius *= e.scale;
  11204. if (e.preventDefault) {
  11205. if (!noPreventDefault) {
  11206. e.stopPropagation();
  11207. e.preventDefault();
  11208. }
  11209. }
  11210. };
  11211. this._reset = function () {
  11212. _this._keys = [];
  11213. _this.inertialAlphaOffset = 0;
  11214. _this.inertialBetaOffset = 0;
  11215. _this.inertialRadiusOffset = 0;
  11216. pointers.empty();
  11217. previousPinchDistance = 0;
  11218. cacheSoloPointer = null;
  11219. };
  11220. }
  11221. if (!useCtrlForPanning) {
  11222. element.addEventListener("contextmenu", this._onContextMenu, false);
  11223. }
  11224. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11225. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11226. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11227. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11228. element.addEventListener("mousemove", this._onMouseMove, false);
  11229. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11230. element.addEventListener("MSGestureChange", this._onGesture, false);
  11231. element.addEventListener('mousewheel', this._wheel, false);
  11232. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11233. BABYLON.Tools.RegisterTopRootEvents([
  11234. { name: "keydown", handler: this._onKeyDown },
  11235. { name: "keyup", handler: this._onKeyUp },
  11236. { name: "blur", handler: this._onLostFocus }
  11237. ]);
  11238. };
  11239. ArcRotateCamera.prototype.detachControl = function (element) {
  11240. if (this._attachedElement !== element) {
  11241. return;
  11242. }
  11243. element.removeEventListener("contextmenu", this._onContextMenu);
  11244. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11245. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11246. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11247. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11248. element.removeEventListener("mousemove", this._onMouseMove);
  11249. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11250. element.removeEventListener("MSGestureChange", this._onGesture);
  11251. element.removeEventListener('mousewheel', this._wheel);
  11252. element.removeEventListener('DOMMouseScroll', this._wheel);
  11253. BABYLON.Tools.UnregisterTopRootEvents([
  11254. { name: "keydown", handler: this._onKeyDown },
  11255. { name: "keyup", handler: this._onKeyUp },
  11256. { name: "blur", handler: this._onLostFocus }
  11257. ]);
  11258. this._MSGestureHandler = null;
  11259. this._attachedElement = null;
  11260. if (this._reset) {
  11261. this._reset();
  11262. }
  11263. };
  11264. ArcRotateCamera.prototype._checkInputs = function () {
  11265. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11266. if (this._collisionTriggered) {
  11267. return;
  11268. }
  11269. // Keyboard
  11270. for (var index = 0; index < this._keys.length; index++) {
  11271. var keyCode = this._keys[index];
  11272. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11273. this.inertialAlphaOffset -= 0.01;
  11274. }
  11275. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11276. this.inertialBetaOffset -= 0.01;
  11277. }
  11278. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11279. this.inertialAlphaOffset += 0.01;
  11280. }
  11281. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11282. this.inertialBetaOffset += 0.01;
  11283. }
  11284. }
  11285. // Inertia
  11286. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11287. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11288. this.beta += this.inertialBetaOffset;
  11289. this.radius -= this.inertialRadiusOffset;
  11290. this.inertialAlphaOffset *= this.inertia;
  11291. this.inertialBetaOffset *= this.inertia;
  11292. this.inertialRadiusOffset *= this.inertia;
  11293. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11294. this.inertialAlphaOffset = 0;
  11295. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11296. this.inertialBetaOffset = 0;
  11297. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11298. this.inertialRadiusOffset = 0;
  11299. }
  11300. // Panning inertia
  11301. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11302. if (!this._localDirection) {
  11303. this._localDirection = BABYLON.Vector3.Zero();
  11304. this._transformedDirection = BABYLON.Vector3.Zero();
  11305. }
  11306. this.inertialPanningX *= this.inertia;
  11307. this.inertialPanningY *= this.inertia;
  11308. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11309. this.inertialPanningX = 0;
  11310. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11311. this.inertialPanningY = 0;
  11312. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11313. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11314. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11315. this.target.addInPlace(this._transformedDirection);
  11316. }
  11317. // Limits
  11318. this._checkLimits();
  11319. _super.prototype._checkInputs.call(this);
  11320. };
  11321. ArcRotateCamera.prototype._checkLimits = function () {
  11322. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11323. if (this.allowUpsideDown && this.beta > Math.PI) {
  11324. this.beta = this.beta - (2 * Math.PI);
  11325. }
  11326. }
  11327. else {
  11328. if (this.beta < this.lowerBetaLimit) {
  11329. this.beta = this.lowerBetaLimit;
  11330. }
  11331. }
  11332. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11333. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11334. this.beta = this.beta + (2 * Math.PI);
  11335. }
  11336. }
  11337. else {
  11338. if (this.beta > this.upperBetaLimit) {
  11339. this.beta = this.upperBetaLimit;
  11340. }
  11341. }
  11342. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11343. this.alpha = this.lowerAlphaLimit;
  11344. }
  11345. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11346. this.alpha = this.upperAlphaLimit;
  11347. }
  11348. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11349. this.radius = this.lowerRadiusLimit;
  11350. }
  11351. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11352. this.radius = this.upperRadiusLimit;
  11353. }
  11354. };
  11355. ArcRotateCamera.prototype.setPosition = function (position) {
  11356. var radiusv3 = position.subtract(this._getTargetPosition());
  11357. this.radius = radiusv3.length();
  11358. // Alpha
  11359. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11360. if (radiusv3.z < 0) {
  11361. this.alpha = 2 * Math.PI - this.alpha;
  11362. }
  11363. // Beta
  11364. this.beta = Math.acos(radiusv3.y / this.radius);
  11365. this._checkLimits();
  11366. };
  11367. ArcRotateCamera.prototype._getViewMatrix = function () {
  11368. // Compute
  11369. var cosa = Math.cos(this.alpha);
  11370. var sina = Math.sin(this.alpha);
  11371. var cosb = Math.cos(this.beta);
  11372. var sinb = Math.sin(this.beta);
  11373. var target = this._getTargetPosition();
  11374. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11375. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11376. this._collider.radius = this.collisionRadius;
  11377. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11378. this._collisionTriggered = true;
  11379. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11380. }
  11381. else {
  11382. this.position.copyFrom(this._newPosition);
  11383. var up = this.upVector;
  11384. if (this.allowUpsideDown && this.beta < 0) {
  11385. var up = up.clone();
  11386. up = up.negate();
  11387. }
  11388. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11389. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11390. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11391. }
  11392. return this._viewMatrix;
  11393. };
  11394. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11395. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11396. meshes = meshes || this.getScene().meshes;
  11397. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11398. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11399. this.radius = distance * this.zoomOnFactor;
  11400. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11401. };
  11402. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11403. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11404. var meshesOrMinMaxVector;
  11405. var distance;
  11406. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11407. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11408. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11409. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11410. }
  11411. else {
  11412. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11413. distance = meshesOrMinMaxVectorAndDistance.distance;
  11414. }
  11415. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11416. if (!doNotUpdateMaxZ) {
  11417. this.maxZ = distance * 2;
  11418. }
  11419. };
  11420. /**
  11421. * @override
  11422. * Override Camera.createRigCamera
  11423. */
  11424. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11425. switch (this.cameraRigMode) {
  11426. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11427. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11428. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11429. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11430. case BABYLON.Camera.RIG_MODE_VR:
  11431. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11432. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11433. }
  11434. };
  11435. /**
  11436. * @override
  11437. * Override Camera._updateRigCameras
  11438. */
  11439. ArcRotateCamera.prototype._updateRigCameras = function () {
  11440. switch (this.cameraRigMode) {
  11441. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11442. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11443. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11444. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11445. case BABYLON.Camera.RIG_MODE_VR:
  11446. var camLeft = this._rigCameras[0];
  11447. var camRight = this._rigCameras[1];
  11448. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11449. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11450. camLeft.beta = camRight.beta = this.beta;
  11451. camLeft.radius = camRight.radius = this.radius;
  11452. break;
  11453. }
  11454. _super.prototype._updateRigCameras.call(this);
  11455. };
  11456. return ArcRotateCamera;
  11457. })(BABYLON.TargetCamera);
  11458. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11459. })(BABYLON || (BABYLON = {}));
  11460. var BABYLON;
  11461. (function (BABYLON) {
  11462. // We're mainly based on the logic defined into the FreeCamera code
  11463. var DeviceOrientationCamera = (function (_super) {
  11464. __extends(DeviceOrientationCamera, _super);
  11465. function DeviceOrientationCamera(name, position, scene) {
  11466. var _this = this;
  11467. _super.call(this, name, position, scene);
  11468. this._offsetX = null;
  11469. this._offsetY = null;
  11470. this._orientationGamma = 0;
  11471. this._orientationBeta = 0;
  11472. this._initialOrientationGamma = 0;
  11473. this._initialOrientationBeta = 0;
  11474. this.angularSensibility = 10000.0;
  11475. this.moveSensibility = 50.0;
  11476. window.addEventListener("resize", function () {
  11477. _this._initialOrientationGamma = null;
  11478. }, false);
  11479. }
  11480. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11481. var _this = this;
  11482. if (this._attachedCanvas) {
  11483. return;
  11484. }
  11485. this._attachedCanvas = canvas;
  11486. if (!this._orientationChanged) {
  11487. this._orientationChanged = function (evt) {
  11488. if (!_this._initialOrientationGamma) {
  11489. _this._initialOrientationGamma = evt.gamma;
  11490. _this._initialOrientationBeta = evt.beta;
  11491. }
  11492. _this._orientationGamma = evt.gamma;
  11493. _this._orientationBeta = evt.beta;
  11494. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11495. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11496. };
  11497. }
  11498. window.addEventListener("deviceorientation", this._orientationChanged);
  11499. };
  11500. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11501. if (this._attachedCanvas != canvas) {
  11502. return;
  11503. }
  11504. window.removeEventListener("deviceorientation", this._orientationChanged);
  11505. this._attachedCanvas = null;
  11506. this._orientationGamma = 0;
  11507. this._orientationBeta = 0;
  11508. this._initialOrientationGamma = 0;
  11509. this._initialOrientationBeta = 0;
  11510. };
  11511. DeviceOrientationCamera.prototype._checkInputs = function () {
  11512. if (!this._offsetX) {
  11513. return;
  11514. }
  11515. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11516. var speed = this._computeLocalCameraSpeed();
  11517. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11518. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11519. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11520. _super.prototype._checkInputs.call(this);
  11521. };
  11522. return DeviceOrientationCamera;
  11523. })(BABYLON.FreeCamera);
  11524. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11525. })(BABYLON || (BABYLON = {}));
  11526. var BABYLON;
  11527. (function (BABYLON) {
  11528. var Gamepads = (function () {
  11529. function Gamepads(ongamedpadconnected) {
  11530. var _this = this;
  11531. this.babylonGamepads = [];
  11532. this.oneGamepadConnected = false;
  11533. this.isMonitoring = false;
  11534. this.gamepadEventSupported = 'GamepadEvent' in window;
  11535. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11536. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11537. 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=";
  11538. this._callbackGamepadConnected = ongamedpadconnected;
  11539. if (this.gamepadSupportAvailable) {
  11540. // Checking if the gamepad connected event is supported (like in Firefox)
  11541. if (this.gamepadEventSupported) {
  11542. window.addEventListener('gamepadconnected', function (evt) {
  11543. _this._onGamepadConnected(evt);
  11544. }, false);
  11545. window.addEventListener('gamepaddisconnected', function (evt) {
  11546. _this._onGamepadDisconnected(evt);
  11547. }, false);
  11548. }
  11549. else {
  11550. this._startMonitoringGamepads();
  11551. }
  11552. if (!this.oneGamepadConnected) {
  11553. this._insertGamepadDOMInstructions();
  11554. }
  11555. }
  11556. else {
  11557. this._insertGamepadDOMNotSupported();
  11558. }
  11559. }
  11560. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11561. Gamepads.gamepadDOMInfo = document.createElement("div");
  11562. var buttonAImage = document.createElement("img");
  11563. buttonAImage.src = this.buttonADataURL;
  11564. var spanMessage = document.createElement("span");
  11565. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11566. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11567. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11568. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11569. Gamepads.gamepadDOMInfo.style.width = "100%";
  11570. Gamepads.gamepadDOMInfo.style.height = "48px";
  11571. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11572. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11573. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11574. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11575. buttonAImage.style.position = "relative";
  11576. buttonAImage.style.bottom = "8px";
  11577. spanMessage.style.position = "relative";
  11578. spanMessage.style.fontSize = "32px";
  11579. spanMessage.style.bottom = "32px";
  11580. spanMessage.style.color = "green";
  11581. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11582. };
  11583. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11584. Gamepads.gamepadDOMInfo = document.createElement("div");
  11585. var spanMessage = document.createElement("span");
  11586. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11587. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11588. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11589. Gamepads.gamepadDOMInfo.style.width = "100%";
  11590. Gamepads.gamepadDOMInfo.style.height = "40px";
  11591. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11592. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11593. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11594. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11595. spanMessage.style.position = "relative";
  11596. spanMessage.style.fontSize = "32px";
  11597. spanMessage.style.color = "red";
  11598. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11599. };
  11600. Gamepads.prototype.dispose = function () {
  11601. if (Gamepads.gamepadDOMInfo) {
  11602. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11603. }
  11604. };
  11605. Gamepads.prototype._onGamepadConnected = function (evt) {
  11606. var newGamepad = this._addNewGamepad(evt.gamepad);
  11607. if (this._callbackGamepadConnected)
  11608. this._callbackGamepadConnected(newGamepad);
  11609. this._startMonitoringGamepads();
  11610. };
  11611. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11612. if (!this.oneGamepadConnected) {
  11613. this.oneGamepadConnected = true;
  11614. if (Gamepads.gamepadDOMInfo) {
  11615. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11616. Gamepads.gamepadDOMInfo = null;
  11617. }
  11618. }
  11619. var newGamepad;
  11620. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11621. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11622. }
  11623. else {
  11624. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11625. }
  11626. this.babylonGamepads.push(newGamepad);
  11627. return newGamepad;
  11628. };
  11629. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11630. // Remove the gamepad from the list of gamepads to monitor.
  11631. for (var i in this.babylonGamepads) {
  11632. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11633. this.babylonGamepads.splice(i, 1);
  11634. break;
  11635. }
  11636. }
  11637. // If no gamepads are left, stop the polling loop.
  11638. if (this.babylonGamepads.length == 0) {
  11639. this._stopMonitoringGamepads();
  11640. }
  11641. };
  11642. Gamepads.prototype._startMonitoringGamepads = function () {
  11643. if (!this.isMonitoring) {
  11644. this.isMonitoring = true;
  11645. this._checkGamepadsStatus();
  11646. }
  11647. };
  11648. Gamepads.prototype._stopMonitoringGamepads = function () {
  11649. this.isMonitoring = false;
  11650. };
  11651. Gamepads.prototype._checkGamepadsStatus = function () {
  11652. var _this = this;
  11653. // updating gamepad objects
  11654. this._updateGamepadObjects();
  11655. for (var i in this.babylonGamepads) {
  11656. this.babylonGamepads[i].update();
  11657. }
  11658. if (this.isMonitoring) {
  11659. if (window.requestAnimationFrame) {
  11660. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11661. }
  11662. else if (window.mozRequestAnimationFrame) {
  11663. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11664. }
  11665. else if (window.webkitRequestAnimationFrame) {
  11666. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11667. }
  11668. }
  11669. };
  11670. // This function is called only on Chrome, which does not yet support
  11671. // connection/disconnection events, but requires you to monitor
  11672. // an array for changes.
  11673. Gamepads.prototype._updateGamepadObjects = function () {
  11674. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11675. for (var i = 0; i < gamepads.length; i++) {
  11676. if (gamepads[i]) {
  11677. if (!(gamepads[i].index in this.babylonGamepads)) {
  11678. var newGamepad = this._addNewGamepad(gamepads[i]);
  11679. if (this._callbackGamepadConnected) {
  11680. this._callbackGamepadConnected(newGamepad);
  11681. }
  11682. }
  11683. else {
  11684. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11685. }
  11686. }
  11687. }
  11688. };
  11689. return Gamepads;
  11690. })();
  11691. BABYLON.Gamepads = Gamepads;
  11692. var StickValues = (function () {
  11693. function StickValues(x, y) {
  11694. this.x = x;
  11695. this.y = y;
  11696. }
  11697. return StickValues;
  11698. })();
  11699. BABYLON.StickValues = StickValues;
  11700. var Gamepad = (function () {
  11701. function Gamepad(id, index, browserGamepad) {
  11702. this.id = id;
  11703. this.index = index;
  11704. this.browserGamepad = browserGamepad;
  11705. if (this.browserGamepad.axes.length >= 2) {
  11706. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11707. }
  11708. if (this.browserGamepad.axes.length >= 4) {
  11709. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11710. }
  11711. }
  11712. Gamepad.prototype.onleftstickchanged = function (callback) {
  11713. this._onleftstickchanged = callback;
  11714. };
  11715. Gamepad.prototype.onrightstickchanged = function (callback) {
  11716. this._onrightstickchanged = callback;
  11717. };
  11718. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11719. get: function () {
  11720. return this._leftStick;
  11721. },
  11722. set: function (newValues) {
  11723. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11724. this._onleftstickchanged(newValues);
  11725. }
  11726. this._leftStick = newValues;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11732. get: function () {
  11733. return this._rightStick;
  11734. },
  11735. set: function (newValues) {
  11736. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11737. this._onrightstickchanged(newValues);
  11738. }
  11739. this._rightStick = newValues;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Gamepad.prototype.update = function () {
  11745. if (this._leftStick) {
  11746. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11747. }
  11748. if (this._rightStick) {
  11749. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11750. }
  11751. };
  11752. return Gamepad;
  11753. })();
  11754. BABYLON.Gamepad = Gamepad;
  11755. var GenericPad = (function (_super) {
  11756. __extends(GenericPad, _super);
  11757. function GenericPad(id, index, gamepad) {
  11758. _super.call(this, id, index, gamepad);
  11759. this.id = id;
  11760. this.index = index;
  11761. this.gamepad = gamepad;
  11762. this._buttons = new Array(gamepad.buttons.length);
  11763. }
  11764. GenericPad.prototype.onbuttondown = function (callback) {
  11765. this._onbuttondown = callback;
  11766. };
  11767. GenericPad.prototype.onbuttonup = function (callback) {
  11768. this._onbuttonup = callback;
  11769. };
  11770. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11771. if (newValue !== currentValue) {
  11772. if (this._onbuttondown && newValue === 1) {
  11773. this._onbuttondown(buttonIndex);
  11774. }
  11775. if (this._onbuttonup && newValue === 0) {
  11776. this._onbuttonup(buttonIndex);
  11777. }
  11778. }
  11779. return newValue;
  11780. };
  11781. GenericPad.prototype.update = function () {
  11782. _super.prototype.update.call(this);
  11783. for (var index = 0; index < this._buttons.length; index++) {
  11784. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11785. }
  11786. };
  11787. return GenericPad;
  11788. })(Gamepad);
  11789. BABYLON.GenericPad = GenericPad;
  11790. (function (Xbox360Button) {
  11791. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11792. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11793. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11794. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11795. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11796. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11797. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11798. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11799. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11800. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11801. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11802. var Xbox360Button = BABYLON.Xbox360Button;
  11803. (function (Xbox360Dpad) {
  11804. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11805. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11806. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11807. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11808. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11809. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11810. var Xbox360Pad = (function (_super) {
  11811. __extends(Xbox360Pad, _super);
  11812. function Xbox360Pad() {
  11813. _super.apply(this, arguments);
  11814. this._leftTrigger = 0;
  11815. this._rightTrigger = 0;
  11816. this._buttonA = 0;
  11817. this._buttonB = 0;
  11818. this._buttonX = 0;
  11819. this._buttonY = 0;
  11820. this._buttonBack = 0;
  11821. this._buttonStart = 0;
  11822. this._buttonLB = 0;
  11823. this._buttonRB = 0;
  11824. this._buttonLeftStick = 0;
  11825. this._buttonRightStick = 0;
  11826. this._dPadUp = 0;
  11827. this._dPadDown = 0;
  11828. this._dPadLeft = 0;
  11829. this._dPadRight = 0;
  11830. }
  11831. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11832. this._onlefttriggerchanged = callback;
  11833. };
  11834. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11835. this._onrighttriggerchanged = callback;
  11836. };
  11837. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11838. get: function () {
  11839. return this._leftTrigger;
  11840. },
  11841. set: function (newValue) {
  11842. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11843. this._onlefttriggerchanged(newValue);
  11844. }
  11845. this._leftTrigger = newValue;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11851. get: function () {
  11852. return this._rightTrigger;
  11853. },
  11854. set: function (newValue) {
  11855. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11856. this._onrighttriggerchanged(newValue);
  11857. }
  11858. this._rightTrigger = newValue;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11864. this._onbuttondown = callback;
  11865. };
  11866. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11867. this._onbuttonup = callback;
  11868. };
  11869. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11870. this._ondpaddown = callback;
  11871. };
  11872. Xbox360Pad.prototype.ondpadup = function (callback) {
  11873. this._ondpadup = callback;
  11874. };
  11875. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11876. if (newValue !== currentValue) {
  11877. if (this._onbuttondown && newValue === 1) {
  11878. this._onbuttondown(buttonType);
  11879. }
  11880. if (this._onbuttonup && newValue === 0) {
  11881. this._onbuttonup(buttonType);
  11882. }
  11883. }
  11884. return newValue;
  11885. };
  11886. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11887. if (newValue !== currentValue) {
  11888. if (this._ondpaddown && newValue === 1) {
  11889. this._ondpaddown(buttonType);
  11890. }
  11891. if (this._ondpadup && newValue === 0) {
  11892. this._ondpadup(buttonType);
  11893. }
  11894. }
  11895. return newValue;
  11896. };
  11897. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11898. get: function () {
  11899. return this._buttonA;
  11900. },
  11901. set: function (value) {
  11902. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11908. get: function () {
  11909. return this._buttonB;
  11910. },
  11911. set: function (value) {
  11912. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11918. get: function () {
  11919. return this._buttonX;
  11920. },
  11921. set: function (value) {
  11922. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11928. get: function () {
  11929. return this._buttonY;
  11930. },
  11931. set: function (value) {
  11932. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11938. get: function () {
  11939. return this._buttonStart;
  11940. },
  11941. set: function (value) {
  11942. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11948. get: function () {
  11949. return this._buttonBack;
  11950. },
  11951. set: function (value) {
  11952. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11958. get: function () {
  11959. return this._buttonLB;
  11960. },
  11961. set: function (value) {
  11962. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11968. get: function () {
  11969. return this._buttonRB;
  11970. },
  11971. set: function (value) {
  11972. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11978. get: function () {
  11979. return this._buttonLeftStick;
  11980. },
  11981. set: function (value) {
  11982. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11988. get: function () {
  11989. return this._buttonRightStick;
  11990. },
  11991. set: function (value) {
  11992. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11993. },
  11994. enumerable: true,
  11995. configurable: true
  11996. });
  11997. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11998. get: function () {
  11999. return this._dPadUp;
  12000. },
  12001. set: function (value) {
  12002. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12003. },
  12004. enumerable: true,
  12005. configurable: true
  12006. });
  12007. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12008. get: function () {
  12009. return this._dPadDown;
  12010. },
  12011. set: function (value) {
  12012. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12018. get: function () {
  12019. return this._dPadLeft;
  12020. },
  12021. set: function (value) {
  12022. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12028. get: function () {
  12029. return this._dPadRight;
  12030. },
  12031. set: function (value) {
  12032. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Xbox360Pad.prototype.update = function () {
  12038. _super.prototype.update.call(this);
  12039. this.buttonA = this.browserGamepad.buttons[0].value;
  12040. this.buttonB = this.browserGamepad.buttons[1].value;
  12041. this.buttonX = this.browserGamepad.buttons[2].value;
  12042. this.buttonY = this.browserGamepad.buttons[3].value;
  12043. this.buttonLB = this.browserGamepad.buttons[4].value;
  12044. this.buttonRB = this.browserGamepad.buttons[5].value;
  12045. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12046. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12047. this.buttonBack = this.browserGamepad.buttons[8].value;
  12048. this.buttonStart = this.browserGamepad.buttons[9].value;
  12049. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12050. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12051. this.dPadUp = this.browserGamepad.buttons[12].value;
  12052. this.dPadDown = this.browserGamepad.buttons[13].value;
  12053. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12054. this.dPadRight = this.browserGamepad.buttons[15].value;
  12055. };
  12056. return Xbox360Pad;
  12057. })(Gamepad);
  12058. BABYLON.Xbox360Pad = Xbox360Pad;
  12059. })(BABYLON || (BABYLON = {}));
  12060. var BABYLON;
  12061. (function (BABYLON) {
  12062. // We're mainly based on the logic defined into the FreeCamera code
  12063. var GamepadCamera = (function (_super) {
  12064. __extends(GamepadCamera, _super);
  12065. function GamepadCamera(name, position, scene) {
  12066. var _this = this;
  12067. _super.call(this, name, position, scene);
  12068. this.angularSensibility = 200;
  12069. this.moveSensibility = 75;
  12070. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12071. }
  12072. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12073. // Only the first gamepad can control the camera
  12074. if (gamepad.index === 0) {
  12075. this._gamepad = gamepad;
  12076. }
  12077. };
  12078. GamepadCamera.prototype._checkInputs = function () {
  12079. if (this._gamepad) {
  12080. var LSValues = this._gamepad.leftStick;
  12081. var normalizedLX = LSValues.x / this.moveSensibility;
  12082. var normalizedLY = LSValues.y / this.moveSensibility;
  12083. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12084. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12085. var RSValues = this._gamepad.rightStick;
  12086. var normalizedRX = RSValues.x / this.angularSensibility;
  12087. var normalizedRY = RSValues.y / this.angularSensibility;
  12088. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12089. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12090. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12091. var speed = this._computeLocalCameraSpeed() * 50.0;
  12092. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12093. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12094. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12095. }
  12096. _super.prototype._checkInputs.call(this);
  12097. };
  12098. GamepadCamera.prototype.dispose = function () {
  12099. this._gamepads.dispose();
  12100. _super.prototype.dispose.call(this);
  12101. };
  12102. return GamepadCamera;
  12103. })(BABYLON.FreeCamera);
  12104. BABYLON.GamepadCamera = GamepadCamera;
  12105. })(BABYLON || (BABYLON = {}));
  12106. var BABYLON;
  12107. (function (BABYLON) {
  12108. var RenderingManager = (function () {
  12109. function RenderingManager(scene) {
  12110. this._renderingGroups = new Array();
  12111. this._scene = scene;
  12112. }
  12113. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12114. if (this._scene._activeParticleSystems.length === 0) {
  12115. return;
  12116. }
  12117. // Particles
  12118. var beforeParticlesDate = BABYLON.Tools.Now;
  12119. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12120. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12121. if (particleSystem.renderingGroupId !== index) {
  12122. continue;
  12123. }
  12124. this._clearDepthBuffer();
  12125. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12126. this._scene._activeParticles += particleSystem.render();
  12127. }
  12128. }
  12129. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12130. };
  12131. RenderingManager.prototype._renderSprites = function (index) {
  12132. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12133. return;
  12134. }
  12135. // Sprites
  12136. var beforeSpritessDate = BABYLON.Tools.Now;
  12137. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12138. var spriteManager = this._scene.spriteManagers[id];
  12139. if (spriteManager.renderingGroupId === index) {
  12140. this._clearDepthBuffer();
  12141. spriteManager.render();
  12142. }
  12143. }
  12144. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12145. };
  12146. RenderingManager.prototype._clearDepthBuffer = function () {
  12147. if (this._depthBufferAlreadyCleaned) {
  12148. return;
  12149. }
  12150. this._scene.getEngine().clear(0, false, true);
  12151. this._depthBufferAlreadyCleaned = true;
  12152. };
  12153. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12154. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12155. this._depthBufferAlreadyCleaned = false;
  12156. var renderingGroup = this._renderingGroups[index];
  12157. var needToStepBack = false;
  12158. if (renderingGroup) {
  12159. this._clearDepthBuffer();
  12160. if (!renderingGroup.render(customRenderFunction)) {
  12161. this._renderingGroups.splice(index, 1);
  12162. needToStepBack = true;
  12163. }
  12164. }
  12165. if (renderSprites) {
  12166. this._renderSprites(index);
  12167. }
  12168. if (renderParticles) {
  12169. this._renderParticles(index, activeMeshes);
  12170. }
  12171. if (needToStepBack) {
  12172. index--;
  12173. }
  12174. }
  12175. };
  12176. RenderingManager.prototype.reset = function () {
  12177. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12178. if (renderingGroup) {
  12179. renderingGroup.prepare();
  12180. }
  12181. });
  12182. };
  12183. RenderingManager.prototype.dispatch = function (subMesh) {
  12184. var mesh = subMesh.getMesh();
  12185. var renderingGroupId = mesh.renderingGroupId || 0;
  12186. if (!this._renderingGroups[renderingGroupId]) {
  12187. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12188. }
  12189. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12190. };
  12191. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12192. return RenderingManager;
  12193. })();
  12194. BABYLON.RenderingManager = RenderingManager;
  12195. })(BABYLON || (BABYLON = {}));
  12196. var BABYLON;
  12197. (function (BABYLON) {
  12198. var RenderingGroup = (function () {
  12199. function RenderingGroup(index, scene) {
  12200. this.index = index;
  12201. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12202. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12203. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12204. this._scene = scene;
  12205. }
  12206. RenderingGroup.prototype.render = function (customRenderFunction) {
  12207. if (customRenderFunction) {
  12208. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12209. return true;
  12210. }
  12211. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12212. return false;
  12213. }
  12214. var engine = this._scene.getEngine();
  12215. // Opaque
  12216. var subIndex;
  12217. var submesh;
  12218. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12219. submesh = this._opaqueSubMeshes.data[subIndex];
  12220. submesh.render(false);
  12221. }
  12222. // Alpha test
  12223. engine.setAlphaTesting(true);
  12224. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12225. submesh = this._alphaTestSubMeshes.data[subIndex];
  12226. submesh.render(false);
  12227. }
  12228. engine.setAlphaTesting(false);
  12229. // Transparent
  12230. if (this._transparentSubMeshes.length) {
  12231. // Sorting
  12232. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12233. submesh = this._transparentSubMeshes.data[subIndex];
  12234. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12235. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12236. }
  12237. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12238. sortedArray.sort(function (a, b) {
  12239. // Alpha index first
  12240. if (a._alphaIndex > b._alphaIndex) {
  12241. return 1;
  12242. }
  12243. if (a._alphaIndex < b._alphaIndex) {
  12244. return -1;
  12245. }
  12246. // Then distance to camera
  12247. if (a._distanceToCamera < b._distanceToCamera) {
  12248. return 1;
  12249. }
  12250. if (a._distanceToCamera > b._distanceToCamera) {
  12251. return -1;
  12252. }
  12253. return 0;
  12254. });
  12255. // Rendering
  12256. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12257. submesh = sortedArray[subIndex];
  12258. submesh.render(true);
  12259. }
  12260. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12261. }
  12262. return true;
  12263. };
  12264. RenderingGroup.prototype.prepare = function () {
  12265. this._opaqueSubMeshes.reset();
  12266. this._transparentSubMeshes.reset();
  12267. this._alphaTestSubMeshes.reset();
  12268. };
  12269. RenderingGroup.prototype.dispatch = function (subMesh) {
  12270. var material = subMesh.getMaterial();
  12271. var mesh = subMesh.getMesh();
  12272. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12273. this._transparentSubMeshes.push(subMesh);
  12274. }
  12275. else if (material.needAlphaTesting()) {
  12276. this._alphaTestSubMeshes.push(subMesh);
  12277. }
  12278. else {
  12279. this._opaqueSubMeshes.push(subMesh); // Opaque
  12280. }
  12281. };
  12282. return RenderingGroup;
  12283. })();
  12284. BABYLON.RenderingGroup = RenderingGroup;
  12285. })(BABYLON || (BABYLON = {}));
  12286. var BABYLON;
  12287. (function (BABYLON) {
  12288. /**
  12289. * Represents a scene to be rendered by the engine.
  12290. * @see http://doc.babylonjs.com/page.php?p=21911
  12291. */
  12292. var Scene = (function () {
  12293. /**
  12294. * @constructor
  12295. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12296. */
  12297. function Scene(engine) {
  12298. // Members
  12299. this.autoClear = true;
  12300. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12301. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12302. this.forceWireframe = false;
  12303. this.forcePointsCloud = false;
  12304. this.forceShowBoundingBoxes = false;
  12305. this.animationsEnabled = true;
  12306. 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
  12307. // Fog
  12308. /**
  12309. * is fog enabled on this scene.
  12310. * @type {boolean}
  12311. */
  12312. this.fogEnabled = true;
  12313. this.fogMode = Scene.FOGMODE_NONE;
  12314. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12315. this.fogDensity = 0.1;
  12316. this.fogStart = 0;
  12317. this.fogEnd = 1000.0;
  12318. // Lights
  12319. /**
  12320. * is shadow enabled on this scene.
  12321. * @type {boolean}
  12322. */
  12323. this.shadowsEnabled = true;
  12324. /**
  12325. * is light enabled on this scene.
  12326. * @type {boolean}
  12327. */
  12328. this.lightsEnabled = true;
  12329. /**
  12330. * All of the lights added to this scene.
  12331. * @see BABYLON.Light
  12332. * @type {BABYLON.Light[]}
  12333. */
  12334. this.lights = new Array();
  12335. // Cameras
  12336. /**
  12337. * All of the cameras added to this scene.
  12338. * @see BABYLON.Camera
  12339. * @type {BABYLON.Camera[]}
  12340. */
  12341. this.cameras = new Array();
  12342. this.activeCameras = new Array();
  12343. // Meshes
  12344. /**
  12345. * All of the (abstract) meshes added to this scene.
  12346. * @see BABYLON.AbstractMesh
  12347. * @type {BABYLON.AbstractMesh[]}
  12348. */
  12349. this.meshes = new Array();
  12350. // Geometries
  12351. this._geometries = new Array();
  12352. this.materials = new Array();
  12353. this.multiMaterials = new Array();
  12354. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12355. // Textures
  12356. this.texturesEnabled = true;
  12357. this.textures = new Array();
  12358. // Particles
  12359. this.particlesEnabled = true;
  12360. this.particleSystems = new Array();
  12361. // Sprites
  12362. this.spritesEnabled = true;
  12363. this.spriteManagers = new Array();
  12364. // Layers
  12365. this.layers = new Array();
  12366. // Skeletons
  12367. this.skeletonsEnabled = true;
  12368. this.skeletons = new Array();
  12369. // Lens flares
  12370. this.lensFlaresEnabled = true;
  12371. this.lensFlareSystems = new Array();
  12372. // Collisions
  12373. this.collisionsEnabled = true;
  12374. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12375. // Postprocesses
  12376. this.postProcessesEnabled = true;
  12377. // Customs render targets
  12378. this.renderTargetsEnabled = true;
  12379. this.dumpNextRenderTargets = false;
  12380. this.customRenderTargets = new Array();
  12381. // Imported meshes
  12382. this.importedMeshesFiles = new Array();
  12383. this._actionManagers = new Array();
  12384. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12385. // Procedural textures
  12386. this.proceduralTexturesEnabled = true;
  12387. this._proceduralTextures = new Array();
  12388. this.soundTracks = new Array();
  12389. this._audioEnabled = true;
  12390. this._headphone = false;
  12391. this._totalVertices = 0;
  12392. this._activeIndices = 0;
  12393. this._activeParticles = 0;
  12394. this._lastFrameDuration = 0;
  12395. this._evaluateActiveMeshesDuration = 0;
  12396. this._renderTargetsDuration = 0;
  12397. this._particlesDuration = 0;
  12398. this._renderDuration = 0;
  12399. this._spritesDuration = 0;
  12400. this._animationRatio = 0;
  12401. this._renderId = 0;
  12402. this._executeWhenReadyTimeoutId = -1;
  12403. this._toBeDisposed = new BABYLON.SmartArray(256);
  12404. this._onReadyCallbacks = new Array();
  12405. this._pendingData = []; //ANY
  12406. this._onBeforeRenderCallbacks = new Array();
  12407. this._onAfterRenderCallbacks = new Array();
  12408. this._activeMeshes = new BABYLON.SmartArray(256);
  12409. this._processedMaterials = new BABYLON.SmartArray(256);
  12410. this._renderTargets = new BABYLON.SmartArray(256);
  12411. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12412. this._activeSkeletons = new BABYLON.SmartArray(32);
  12413. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12414. this._activeBones = 0;
  12415. this._activeAnimatables = new Array();
  12416. this._transformMatrix = BABYLON.Matrix.Zero();
  12417. this._uniqueIdCounter = 0;
  12418. this._engine = engine;
  12419. engine.scenes.push(this);
  12420. this._renderingManager = new BABYLON.RenderingManager(this);
  12421. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12422. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12423. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12424. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12425. this.attachControl();
  12426. this._debugLayer = new BABYLON.DebugLayer(this);
  12427. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12428. //simplification queue
  12429. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12430. //collision coordinator initialization. For now legacy per default.
  12431. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12432. }
  12433. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12434. get: function () {
  12435. return Scene._FOGMODE_NONE;
  12436. },
  12437. enumerable: true,
  12438. configurable: true
  12439. });
  12440. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12441. get: function () {
  12442. return Scene._FOGMODE_EXP;
  12443. },
  12444. enumerable: true,
  12445. configurable: true
  12446. });
  12447. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12448. get: function () {
  12449. return Scene._FOGMODE_EXP2;
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12455. get: function () {
  12456. return Scene._FOGMODE_LINEAR;
  12457. },
  12458. enumerable: true,
  12459. configurable: true
  12460. });
  12461. Object.defineProperty(Scene.prototype, "debugLayer", {
  12462. // Properties
  12463. get: function () {
  12464. return this._debugLayer;
  12465. },
  12466. enumerable: true,
  12467. configurable: true
  12468. });
  12469. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12470. get: function () {
  12471. return this._workerCollisions;
  12472. },
  12473. set: function (enabled) {
  12474. enabled = (enabled && !!Worker);
  12475. this._workerCollisions = enabled;
  12476. if (this.collisionCoordinator) {
  12477. this.collisionCoordinator.destroy();
  12478. }
  12479. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12480. this.collisionCoordinator.init(this);
  12481. },
  12482. enumerable: true,
  12483. configurable: true
  12484. });
  12485. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12486. get: function () {
  12487. return this._selectionOctree;
  12488. },
  12489. enumerable: true,
  12490. configurable: true
  12491. });
  12492. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12493. /**
  12494. * The mesh that is currently under the pointer.
  12495. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12496. */
  12497. get: function () {
  12498. return this._meshUnderPointer;
  12499. },
  12500. enumerable: true,
  12501. configurable: true
  12502. });
  12503. Object.defineProperty(Scene.prototype, "pointerX", {
  12504. /**
  12505. * Current on-screen X position of the pointer
  12506. * @return {number} X position of the pointer
  12507. */
  12508. get: function () {
  12509. return this._pointerX;
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(Scene.prototype, "pointerY", {
  12515. /**
  12516. * Current on-screen Y position of the pointer
  12517. * @return {number} Y position of the pointer
  12518. */
  12519. get: function () {
  12520. return this._pointerY;
  12521. },
  12522. enumerable: true,
  12523. configurable: true
  12524. });
  12525. Scene.prototype.getCachedMaterial = function () {
  12526. return this._cachedMaterial;
  12527. };
  12528. Scene.prototype.getBoundingBoxRenderer = function () {
  12529. return this._boundingBoxRenderer;
  12530. };
  12531. Scene.prototype.getOutlineRenderer = function () {
  12532. return this._outlineRenderer;
  12533. };
  12534. Scene.prototype.getEngine = function () {
  12535. return this._engine;
  12536. };
  12537. Scene.prototype.getTotalVertices = function () {
  12538. return this._totalVertices;
  12539. };
  12540. Scene.prototype.getActiveIndices = function () {
  12541. return this._activeIndices;
  12542. };
  12543. Scene.prototype.getActiveParticles = function () {
  12544. return this._activeParticles;
  12545. };
  12546. Scene.prototype.getActiveBones = function () {
  12547. return this._activeBones;
  12548. };
  12549. // Stats
  12550. Scene.prototype.getLastFrameDuration = function () {
  12551. return this._lastFrameDuration;
  12552. };
  12553. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12554. return this._evaluateActiveMeshesDuration;
  12555. };
  12556. Scene.prototype.getActiveMeshes = function () {
  12557. return this._activeMeshes;
  12558. };
  12559. Scene.prototype.getRenderTargetsDuration = function () {
  12560. return this._renderTargetsDuration;
  12561. };
  12562. Scene.prototype.getRenderDuration = function () {
  12563. return this._renderDuration;
  12564. };
  12565. Scene.prototype.getParticlesDuration = function () {
  12566. return this._particlesDuration;
  12567. };
  12568. Scene.prototype.getSpritesDuration = function () {
  12569. return this._spritesDuration;
  12570. };
  12571. Scene.prototype.getAnimationRatio = function () {
  12572. return this._animationRatio;
  12573. };
  12574. Scene.prototype.getRenderId = function () {
  12575. return this._renderId;
  12576. };
  12577. Scene.prototype.incrementRenderId = function () {
  12578. this._renderId++;
  12579. };
  12580. Scene.prototype._updatePointerPosition = function (evt) {
  12581. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12582. this._pointerX = evt.clientX - canvasRect.left;
  12583. this._pointerY = evt.clientY - canvasRect.top;
  12584. if (this.cameraToUseForPointers) {
  12585. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12586. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12587. }
  12588. };
  12589. // Pointers handling
  12590. Scene.prototype.attachControl = function () {
  12591. var _this = this;
  12592. this._onPointerMove = function (evt) {
  12593. var canvas = _this._engine.getRenderingCanvas();
  12594. _this._updatePointerPosition(evt);
  12595. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12596. if (pickResult.hit) {
  12597. _this._meshUnderPointer = pickResult.pickedMesh;
  12598. _this.setPointerOverMesh(pickResult.pickedMesh);
  12599. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12600. canvas.style.cursor = "pointer";
  12601. }
  12602. else {
  12603. canvas.style.cursor = "";
  12604. }
  12605. }
  12606. else {
  12607. _this.setPointerOverMesh(null);
  12608. canvas.style.cursor = "";
  12609. _this._meshUnderPointer = null;
  12610. }
  12611. };
  12612. this._onPointerDown = function (evt) {
  12613. var predicate = null;
  12614. if (!_this.onPointerDown) {
  12615. predicate = function (mesh) {
  12616. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12617. };
  12618. }
  12619. _this._updatePointerPosition(evt);
  12620. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12621. if (pickResult.hit) {
  12622. if (pickResult.pickedMesh.actionManager) {
  12623. switch (evt.button) {
  12624. case 0:
  12625. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12626. break;
  12627. case 1:
  12628. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12629. break;
  12630. case 2:
  12631. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12632. break;
  12633. }
  12634. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12635. }
  12636. }
  12637. if (_this.onPointerDown) {
  12638. _this.onPointerDown(evt, pickResult);
  12639. }
  12640. };
  12641. this._onPointerUp = function (evt) {
  12642. var predicate = null;
  12643. if (!_this.onPointerUp) {
  12644. predicate = function (mesh) {
  12645. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12646. };
  12647. }
  12648. _this._updatePointerPosition(evt);
  12649. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12650. if (pickResult.hit) {
  12651. if (pickResult.pickedMesh.actionManager) {
  12652. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12653. }
  12654. }
  12655. if (_this.onPointerUp) {
  12656. _this.onPointerUp(evt, pickResult);
  12657. }
  12658. };
  12659. this._onKeyDown = function (evt) {
  12660. if (_this.actionManager) {
  12661. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12662. }
  12663. };
  12664. this._onKeyUp = function (evt) {
  12665. if (_this.actionManager) {
  12666. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12667. }
  12668. };
  12669. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12670. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12671. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12672. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12673. // Wheel
  12674. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12675. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12676. BABYLON.Tools.RegisterTopRootEvents([
  12677. { name: "keydown", handler: this._onKeyDown },
  12678. { name: "keyup", handler: this._onKeyUp }
  12679. ]);
  12680. };
  12681. Scene.prototype.detachControl = function () {
  12682. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12683. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12684. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12685. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12686. // Wheel
  12687. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12688. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12689. BABYLON.Tools.UnregisterTopRootEvents([
  12690. { name: "keydown", handler: this._onKeyDown },
  12691. { name: "keyup", handler: this._onKeyUp }
  12692. ]);
  12693. };
  12694. // Ready
  12695. Scene.prototype.isReady = function () {
  12696. if (this._pendingData.length > 0) {
  12697. return false;
  12698. }
  12699. for (var index = 0; index < this._geometries.length; index++) {
  12700. var geometry = this._geometries[index];
  12701. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12702. return false;
  12703. }
  12704. }
  12705. for (index = 0; index < this.meshes.length; index++) {
  12706. var mesh = this.meshes[index];
  12707. if (!mesh.isReady()) {
  12708. return false;
  12709. }
  12710. var mat = mesh.material;
  12711. if (mat) {
  12712. if (!mat.isReady(mesh)) {
  12713. return false;
  12714. }
  12715. }
  12716. }
  12717. return true;
  12718. };
  12719. Scene.prototype.resetCachedMaterial = function () {
  12720. this._cachedMaterial = null;
  12721. };
  12722. Scene.prototype.registerBeforeRender = function (func) {
  12723. this._onBeforeRenderCallbacks.push(func);
  12724. };
  12725. Scene.prototype.unregisterBeforeRender = function (func) {
  12726. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12727. if (index > -1) {
  12728. this._onBeforeRenderCallbacks.splice(index, 1);
  12729. }
  12730. };
  12731. Scene.prototype.registerAfterRender = function (func) {
  12732. this._onAfterRenderCallbacks.push(func);
  12733. };
  12734. Scene.prototype.unregisterAfterRender = function (func) {
  12735. var index = this._onAfterRenderCallbacks.indexOf(func);
  12736. if (index > -1) {
  12737. this._onAfterRenderCallbacks.splice(index, 1);
  12738. }
  12739. };
  12740. Scene.prototype._addPendingData = function (data) {
  12741. this._pendingData.push(data);
  12742. };
  12743. Scene.prototype._removePendingData = function (data) {
  12744. var index = this._pendingData.indexOf(data);
  12745. if (index !== -1) {
  12746. this._pendingData.splice(index, 1);
  12747. }
  12748. };
  12749. Scene.prototype.getWaitingItemsCount = function () {
  12750. return this._pendingData.length;
  12751. };
  12752. /**
  12753. * Registers a function to be executed when the scene is ready.
  12754. * @param {Function} func - the function to be executed.
  12755. */
  12756. Scene.prototype.executeWhenReady = function (func) {
  12757. var _this = this;
  12758. this._onReadyCallbacks.push(func);
  12759. if (this._executeWhenReadyTimeoutId !== -1) {
  12760. return;
  12761. }
  12762. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12763. _this._checkIsReady();
  12764. }, 150);
  12765. };
  12766. Scene.prototype._checkIsReady = function () {
  12767. var _this = this;
  12768. if (this.isReady()) {
  12769. this._onReadyCallbacks.forEach(function (func) {
  12770. func();
  12771. });
  12772. this._onReadyCallbacks = [];
  12773. this._executeWhenReadyTimeoutId = -1;
  12774. return;
  12775. }
  12776. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12777. _this._checkIsReady();
  12778. }, 150);
  12779. };
  12780. // Animations
  12781. /**
  12782. * Will start the animation sequence of a given target
  12783. * @param target - the target
  12784. * @param {number} from - from which frame should animation start
  12785. * @param {number} to - till which frame should animation run.
  12786. * @param {boolean} [loop] - should the animation loop
  12787. * @param {number} [speedRatio] - the speed in which to run the animation
  12788. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12789. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12790. * @return {BABYLON.Animatable} the animatable object created for this animation
  12791. * @see BABYLON.Animatable
  12792. * @see http://doc.babylonjs.com/page.php?p=22081
  12793. */
  12794. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12795. if (speedRatio === undefined) {
  12796. speedRatio = 1.0;
  12797. }
  12798. this.stopAnimation(target);
  12799. if (!animatable) {
  12800. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12801. }
  12802. // Local animations
  12803. if (target.animations) {
  12804. animatable.appendAnimations(target, target.animations);
  12805. }
  12806. // Children animations
  12807. if (target.getAnimatables) {
  12808. var animatables = target.getAnimatables();
  12809. for (var index = 0; index < animatables.length; index++) {
  12810. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12811. }
  12812. }
  12813. return animatable;
  12814. };
  12815. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12816. if (speedRatio === undefined) {
  12817. speedRatio = 1.0;
  12818. }
  12819. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12820. return animatable;
  12821. };
  12822. Scene.prototype.getAnimatableByTarget = function (target) {
  12823. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12824. if (this._activeAnimatables[index].target === target) {
  12825. return this._activeAnimatables[index];
  12826. }
  12827. }
  12828. return null;
  12829. };
  12830. /**
  12831. * Will stop the animation of the given target
  12832. * @param target - the target
  12833. * @see beginAnimation
  12834. */
  12835. Scene.prototype.stopAnimation = function (target) {
  12836. var animatable = this.getAnimatableByTarget(target);
  12837. if (animatable) {
  12838. animatable.stop();
  12839. }
  12840. };
  12841. Scene.prototype._animate = function () {
  12842. if (!this.animationsEnabled) {
  12843. return;
  12844. }
  12845. if (!this._animationStartDate) {
  12846. this._animationStartDate = BABYLON.Tools.Now;
  12847. }
  12848. // Getting time
  12849. var now = BABYLON.Tools.Now;
  12850. var delay = now - this._animationStartDate;
  12851. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12852. this._activeAnimatables[index]._animate(delay);
  12853. }
  12854. };
  12855. // Matrix
  12856. Scene.prototype.getViewMatrix = function () {
  12857. return this._viewMatrix;
  12858. };
  12859. Scene.prototype.getProjectionMatrix = function () {
  12860. return this._projectionMatrix;
  12861. };
  12862. Scene.prototype.getTransformMatrix = function () {
  12863. return this._transformMatrix;
  12864. };
  12865. Scene.prototype.setTransformMatrix = function (view, projection) {
  12866. this._viewMatrix = view;
  12867. this._projectionMatrix = projection;
  12868. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12869. };
  12870. // Methods
  12871. Scene.prototype.addMesh = function (newMesh) {
  12872. newMesh.uniqueId = this._uniqueIdCounter++;
  12873. var position = this.meshes.push(newMesh);
  12874. //notify the collision coordinator
  12875. this.collisionCoordinator.onMeshAdded(newMesh);
  12876. if (this.onNewMeshAdded) {
  12877. this.onNewMeshAdded(newMesh, position, this);
  12878. }
  12879. };
  12880. Scene.prototype.removeMesh = function (toRemove) {
  12881. var index = this.meshes.indexOf(toRemove);
  12882. if (index !== -1) {
  12883. // Remove from the scene if mesh found
  12884. this.meshes.splice(index, 1);
  12885. }
  12886. //notify the collision coordinator
  12887. this.collisionCoordinator.onMeshRemoved(toRemove);
  12888. if (this.onMeshRemoved) {
  12889. this.onMeshRemoved(toRemove);
  12890. }
  12891. return index;
  12892. };
  12893. Scene.prototype.removeLight = function (toRemove) {
  12894. var index = this.lights.indexOf(toRemove);
  12895. if (index !== -1) {
  12896. // Remove from the scene if mesh found
  12897. this.lights.splice(index, 1);
  12898. }
  12899. if (this.onLightRemoved) {
  12900. this.onLightRemoved(toRemove);
  12901. }
  12902. return index;
  12903. };
  12904. Scene.prototype.removeCamera = function (toRemove) {
  12905. var index = this.cameras.indexOf(toRemove);
  12906. if (index !== -1) {
  12907. // Remove from the scene if mesh found
  12908. this.cameras.splice(index, 1);
  12909. }
  12910. // Remove from activeCameras
  12911. var index2 = this.activeCameras.indexOf(toRemove);
  12912. if (index2 !== -1) {
  12913. // Remove from the scene if mesh found
  12914. this.activeCameras.splice(index2, 1);
  12915. }
  12916. // Reset the activeCamera
  12917. if (this.activeCamera === toRemove) {
  12918. if (this.cameras.length > 0) {
  12919. this.activeCamera = this.cameras[0];
  12920. }
  12921. else {
  12922. this.activeCamera = null;
  12923. }
  12924. }
  12925. if (this.onCameraRemoved) {
  12926. this.onCameraRemoved(toRemove);
  12927. }
  12928. return index;
  12929. };
  12930. Scene.prototype.addLight = function (newLight) {
  12931. newLight.uniqueId = this._uniqueIdCounter++;
  12932. var position = this.lights.push(newLight);
  12933. if (this.onNewLightAdded) {
  12934. this.onNewLightAdded(newLight, position, this);
  12935. }
  12936. };
  12937. Scene.prototype.addCamera = function (newCamera) {
  12938. newCamera.uniqueId = this._uniqueIdCounter++;
  12939. var position = this.cameras.push(newCamera);
  12940. if (this.onNewCameraAdded) {
  12941. this.onNewCameraAdded(newCamera, position, this);
  12942. }
  12943. };
  12944. /**
  12945. * sets the active camera of the scene using its ID
  12946. * @param {string} id - the camera's ID
  12947. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12948. * @see activeCamera
  12949. */
  12950. Scene.prototype.setActiveCameraByID = function (id) {
  12951. var camera = this.getCameraByID(id);
  12952. if (camera) {
  12953. this.activeCamera = camera;
  12954. return camera;
  12955. }
  12956. return null;
  12957. };
  12958. /**
  12959. * sets the active camera of the scene using its name
  12960. * @param {string} name - the camera's name
  12961. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12962. * @see activeCamera
  12963. */
  12964. Scene.prototype.setActiveCameraByName = function (name) {
  12965. var camera = this.getCameraByName(name);
  12966. if (camera) {
  12967. this.activeCamera = camera;
  12968. return camera;
  12969. }
  12970. return null;
  12971. };
  12972. /**
  12973. * get a material using its id
  12974. * @param {string} the material's ID
  12975. * @return {BABYLON.Material|null} the material or null if none found.
  12976. */
  12977. Scene.prototype.getMaterialByID = function (id) {
  12978. for (var index = 0; index < this.materials.length; index++) {
  12979. if (this.materials[index].id === id) {
  12980. return this.materials[index];
  12981. }
  12982. }
  12983. return null;
  12984. };
  12985. /**
  12986. * get a material using its name
  12987. * @param {string} the material's name
  12988. * @return {BABYLON.Material|null} the material or null if none found.
  12989. */
  12990. Scene.prototype.getMaterialByName = function (name) {
  12991. for (var index = 0; index < this.materials.length; index++) {
  12992. if (this.materials[index].name === name) {
  12993. return this.materials[index];
  12994. }
  12995. }
  12996. return null;
  12997. };
  12998. Scene.prototype.getLensFlareSystemByName = function (name) {
  12999. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13000. if (this.lensFlareSystems[index].name === name) {
  13001. return this.lensFlareSystems[index];
  13002. }
  13003. }
  13004. return null;
  13005. };
  13006. Scene.prototype.getCameraByID = function (id) {
  13007. for (var index = 0; index < this.cameras.length; index++) {
  13008. if (this.cameras[index].id === id) {
  13009. return this.cameras[index];
  13010. }
  13011. }
  13012. return null;
  13013. };
  13014. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13015. for (var index = 0; index < this.cameras.length; index++) {
  13016. if (this.cameras[index].uniqueId === uniqueId) {
  13017. return this.cameras[index];
  13018. }
  13019. }
  13020. return null;
  13021. };
  13022. /**
  13023. * get a camera using its name
  13024. * @param {string} the camera's name
  13025. * @return {BABYLON.Camera|null} the camera or null if none found.
  13026. */
  13027. Scene.prototype.getCameraByName = function (name) {
  13028. for (var index = 0; index < this.cameras.length; index++) {
  13029. if (this.cameras[index].name === name) {
  13030. return this.cameras[index];
  13031. }
  13032. }
  13033. return null;
  13034. };
  13035. /**
  13036. * get a light node using its name
  13037. * @param {string} the light's name
  13038. * @return {BABYLON.Light|null} the light or null if none found.
  13039. */
  13040. Scene.prototype.getLightByName = function (name) {
  13041. for (var index = 0; index < this.lights.length; index++) {
  13042. if (this.lights[index].name === name) {
  13043. return this.lights[index];
  13044. }
  13045. }
  13046. return null;
  13047. };
  13048. /**
  13049. * get a light node using its ID
  13050. * @param {string} the light's id
  13051. * @return {BABYLON.Light|null} the light or null if none found.
  13052. */
  13053. Scene.prototype.getLightByID = function (id) {
  13054. for (var index = 0; index < this.lights.length; index++) {
  13055. if (this.lights[index].id === id) {
  13056. return this.lights[index];
  13057. }
  13058. }
  13059. return null;
  13060. };
  13061. /**
  13062. * get a light node using its scene-generated unique ID
  13063. * @param {number} the light's unique id
  13064. * @return {BABYLON.Light|null} the light or null if none found.
  13065. */
  13066. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13067. for (var index = 0; index < this.lights.length; index++) {
  13068. if (this.lights[index].uniqueId === uniqueId) {
  13069. return this.lights[index];
  13070. }
  13071. }
  13072. return null;
  13073. };
  13074. /**
  13075. * get a geometry using its ID
  13076. * @param {string} the geometry's id
  13077. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13078. */
  13079. Scene.prototype.getGeometryByID = function (id) {
  13080. for (var index = 0; index < this._geometries.length; index++) {
  13081. if (this._geometries[index].id === id) {
  13082. return this._geometries[index];
  13083. }
  13084. }
  13085. return null;
  13086. };
  13087. /**
  13088. * add a new geometry to this scene.
  13089. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13090. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13091. * @return {boolean} was the geometry added or not
  13092. */
  13093. Scene.prototype.pushGeometry = function (geometry, force) {
  13094. if (!force && this.getGeometryByID(geometry.id)) {
  13095. return false;
  13096. }
  13097. this._geometries.push(geometry);
  13098. //notify the collision coordinator
  13099. this.collisionCoordinator.onGeometryAdded(geometry);
  13100. if (this.onGeometryAdded) {
  13101. this.onGeometryAdded(geometry);
  13102. }
  13103. return true;
  13104. };
  13105. /**
  13106. * Removes an existing geometry
  13107. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13108. * @return {boolean} was the geometry removed or not
  13109. */
  13110. Scene.prototype.removeGeometry = function (geometry) {
  13111. var index = this._geometries.indexOf(geometry);
  13112. if (index > -1) {
  13113. this._geometries.splice(index, 1);
  13114. //notify the collision coordinator
  13115. this.collisionCoordinator.onGeometryDeleted(geometry);
  13116. if (this.onGeometryRemoved) {
  13117. this.onGeometryRemoved(geometry);
  13118. }
  13119. return true;
  13120. }
  13121. return false;
  13122. };
  13123. Scene.prototype.getGeometries = function () {
  13124. return this._geometries;
  13125. };
  13126. /**
  13127. * Get the first added mesh found of a given ID
  13128. * @param {string} id - the id to search for
  13129. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13130. */
  13131. Scene.prototype.getMeshByID = function (id) {
  13132. for (var index = 0; index < this.meshes.length; index++) {
  13133. if (this.meshes[index].id === id) {
  13134. return this.meshes[index];
  13135. }
  13136. }
  13137. return null;
  13138. };
  13139. /**
  13140. * Get a mesh with its auto-generated unique id
  13141. * @param {number} uniqueId - the unique id to search for
  13142. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13143. */
  13144. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13145. for (var index = 0; index < this.meshes.length; index++) {
  13146. if (this.meshes[index].uniqueId === uniqueId) {
  13147. return this.meshes[index];
  13148. }
  13149. }
  13150. return null;
  13151. };
  13152. /**
  13153. * Get a the last added mesh found of a given ID
  13154. * @param {string} id - the id to search for
  13155. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13156. */
  13157. Scene.prototype.getLastMeshByID = function (id) {
  13158. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13159. if (this.meshes[index].id === id) {
  13160. return this.meshes[index];
  13161. }
  13162. }
  13163. return null;
  13164. };
  13165. /**
  13166. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13167. * @param {string} id - the id to search for
  13168. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13169. */
  13170. Scene.prototype.getLastEntryByID = function (id) {
  13171. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13172. if (this.meshes[index].id === id) {
  13173. return this.meshes[index];
  13174. }
  13175. }
  13176. for (index = this.cameras.length - 1; index >= 0; index--) {
  13177. if (this.cameras[index].id === id) {
  13178. return this.cameras[index];
  13179. }
  13180. }
  13181. for (index = this.lights.length - 1; index >= 0; index--) {
  13182. if (this.lights[index].id === id) {
  13183. return this.lights[index];
  13184. }
  13185. }
  13186. return null;
  13187. };
  13188. Scene.prototype.getNodeByID = function (id) {
  13189. var mesh = this.getMeshByID(id);
  13190. if (mesh) {
  13191. return mesh;
  13192. }
  13193. var light = this.getLightByID(id);
  13194. if (light) {
  13195. return light;
  13196. }
  13197. return this.getCameraByID(id);
  13198. };
  13199. Scene.prototype.getNodeByName = function (name) {
  13200. var mesh = this.getMeshByName(name);
  13201. if (mesh) {
  13202. return mesh;
  13203. }
  13204. var light = this.getLightByName(name);
  13205. if (light) {
  13206. return light;
  13207. }
  13208. return this.getCameraByName(name);
  13209. };
  13210. Scene.prototype.getMeshByName = function (name) {
  13211. for (var index = 0; index < this.meshes.length; index++) {
  13212. if (this.meshes[index].name === name) {
  13213. return this.meshes[index];
  13214. }
  13215. }
  13216. return null;
  13217. };
  13218. Scene.prototype.getSoundByName = function (name) {
  13219. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13220. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13221. return this.mainSoundTrack.soundCollection[index];
  13222. }
  13223. }
  13224. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13225. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13226. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13227. return this.soundTracks[sdIndex].soundCollection[index];
  13228. }
  13229. }
  13230. }
  13231. return null;
  13232. };
  13233. Scene.prototype.getLastSkeletonByID = function (id) {
  13234. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13235. if (this.skeletons[index].id === id) {
  13236. return this.skeletons[index];
  13237. }
  13238. }
  13239. return null;
  13240. };
  13241. Scene.prototype.getSkeletonById = function (id) {
  13242. for (var index = 0; index < this.skeletons.length; index++) {
  13243. if (this.skeletons[index].id === id) {
  13244. return this.skeletons[index];
  13245. }
  13246. }
  13247. return null;
  13248. };
  13249. Scene.prototype.getSkeletonByName = function (name) {
  13250. for (var index = 0; index < this.skeletons.length; index++) {
  13251. if (this.skeletons[index].name === name) {
  13252. return this.skeletons[index];
  13253. }
  13254. }
  13255. return null;
  13256. };
  13257. Scene.prototype.isActiveMesh = function (mesh) {
  13258. return (this._activeMeshes.indexOf(mesh) !== -1);
  13259. };
  13260. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13261. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13262. var material = subMesh.getMaterial();
  13263. if (mesh.showSubMeshesBoundingBox) {
  13264. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13265. }
  13266. if (material) {
  13267. // Render targets
  13268. if (material.getRenderTargetTextures) {
  13269. if (this._processedMaterials.indexOf(material) === -1) {
  13270. this._processedMaterials.push(material);
  13271. this._renderTargets.concat(material.getRenderTargetTextures());
  13272. }
  13273. }
  13274. // Dispatch
  13275. this._activeIndices += subMesh.indexCount;
  13276. this._renderingManager.dispatch(subMesh);
  13277. }
  13278. }
  13279. };
  13280. Scene.prototype._evaluateActiveMeshes = function () {
  13281. this.activeCamera._activeMeshes.reset();
  13282. this._activeMeshes.reset();
  13283. this._renderingManager.reset();
  13284. this._processedMaterials.reset();
  13285. this._activeParticleSystems.reset();
  13286. this._activeSkeletons.reset();
  13287. this._softwareSkinnedMeshes.reset();
  13288. this._boundingBoxRenderer.reset();
  13289. if (!this._frustumPlanes) {
  13290. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13291. }
  13292. else {
  13293. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13294. }
  13295. // Meshes
  13296. var meshes;
  13297. var len;
  13298. if (this._selectionOctree) {
  13299. var selection = this._selectionOctree.select(this._frustumPlanes);
  13300. meshes = selection.data;
  13301. len = selection.length;
  13302. }
  13303. else {
  13304. len = this.meshes.length;
  13305. meshes = this.meshes;
  13306. }
  13307. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13308. var mesh = meshes[meshIndex];
  13309. if (mesh.isBlocked) {
  13310. continue;
  13311. }
  13312. this._totalVertices += mesh.getTotalVertices();
  13313. if (!mesh.isReady() || !mesh.isEnabled()) {
  13314. continue;
  13315. }
  13316. mesh.computeWorldMatrix();
  13317. // Intersections
  13318. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13319. this._meshesForIntersections.pushNoDuplicate(mesh);
  13320. }
  13321. // Switch to current LOD
  13322. var meshLOD = mesh.getLOD(this.activeCamera);
  13323. if (!meshLOD) {
  13324. continue;
  13325. }
  13326. mesh._preActivate();
  13327. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13328. this._activeMeshes.push(mesh);
  13329. this.activeCamera._activeMeshes.push(mesh);
  13330. mesh._activate(this._renderId);
  13331. this._activeMesh(meshLOD);
  13332. }
  13333. }
  13334. // Particle systems
  13335. var beforeParticlesDate = BABYLON.Tools.Now;
  13336. if (this.particlesEnabled) {
  13337. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13338. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13339. var particleSystem = this.particleSystems[particleIndex];
  13340. if (!particleSystem.isStarted()) {
  13341. continue;
  13342. }
  13343. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13344. this._activeParticleSystems.push(particleSystem);
  13345. particleSystem.animate();
  13346. }
  13347. }
  13348. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13349. }
  13350. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13351. };
  13352. Scene.prototype._activeMesh = function (mesh) {
  13353. if (mesh.skeleton && this.skeletonsEnabled) {
  13354. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13355. if (!mesh.computeBonesUsingShaders) {
  13356. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13357. }
  13358. }
  13359. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13360. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13361. }
  13362. if (mesh && mesh.subMeshes) {
  13363. // Submeshes Octrees
  13364. var len;
  13365. var subMeshes;
  13366. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13367. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13368. len = intersections.length;
  13369. subMeshes = intersections.data;
  13370. }
  13371. else {
  13372. subMeshes = mesh.subMeshes;
  13373. len = subMeshes.length;
  13374. }
  13375. for (var subIndex = 0; subIndex < len; subIndex++) {
  13376. var subMesh = subMeshes[subIndex];
  13377. this._evaluateSubMesh(subMesh, mesh);
  13378. }
  13379. }
  13380. };
  13381. Scene.prototype.updateTransformMatrix = function (force) {
  13382. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13383. };
  13384. Scene.prototype._renderForCamera = function (camera) {
  13385. var engine = this._engine;
  13386. this.activeCamera = camera;
  13387. if (!this.activeCamera)
  13388. throw new Error("Active camera not set");
  13389. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13390. // Viewport
  13391. engine.setViewport(this.activeCamera.viewport);
  13392. // Camera
  13393. this.resetCachedMaterial();
  13394. this._renderId++;
  13395. this.updateTransformMatrix();
  13396. if (this.beforeCameraRender) {
  13397. this.beforeCameraRender(this.activeCamera);
  13398. }
  13399. // Meshes
  13400. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13401. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13402. this._evaluateActiveMeshes();
  13403. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13404. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13405. // Skeletons
  13406. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13407. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13408. skeleton.prepare();
  13409. }
  13410. // Software skinning
  13411. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13412. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13413. mesh.applySkeleton(mesh.skeleton);
  13414. }
  13415. // Render targets
  13416. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13417. if (this.renderTargetsEnabled) {
  13418. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13419. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13420. var renderTarget = this._renderTargets.data[renderIndex];
  13421. if (renderTarget._shouldRender()) {
  13422. this._renderId++;
  13423. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13424. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13425. }
  13426. }
  13427. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13428. this._renderId++;
  13429. }
  13430. if (this._renderTargets.length > 0) {
  13431. engine.restoreDefaultFramebuffer();
  13432. }
  13433. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13434. // Prepare Frame
  13435. this.postProcessManager._prepareFrame();
  13436. var beforeRenderDate = BABYLON.Tools.Now;
  13437. // Backgrounds
  13438. if (this.layers.length) {
  13439. engine.setDepthBuffer(false);
  13440. var layerIndex;
  13441. var layer;
  13442. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13443. layer = this.layers[layerIndex];
  13444. if (layer.isBackground) {
  13445. layer.render();
  13446. }
  13447. }
  13448. engine.setDepthBuffer(true);
  13449. }
  13450. // Render
  13451. BABYLON.Tools.StartPerformanceCounter("Main render");
  13452. this._renderingManager.render(null, null, true, true);
  13453. BABYLON.Tools.EndPerformanceCounter("Main render");
  13454. // Bounding boxes
  13455. this._boundingBoxRenderer.render();
  13456. // Lens flares
  13457. if (this.lensFlaresEnabled) {
  13458. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13459. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13460. this.lensFlareSystems[lensFlareSystemIndex].render();
  13461. }
  13462. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13463. }
  13464. // Foregrounds
  13465. if (this.layers.length) {
  13466. engine.setDepthBuffer(false);
  13467. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13468. layer = this.layers[layerIndex];
  13469. if (!layer.isBackground) {
  13470. layer.render();
  13471. }
  13472. }
  13473. engine.setDepthBuffer(true);
  13474. }
  13475. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13476. // Finalize frame
  13477. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13478. // Update camera
  13479. this.activeCamera._updateFromScene();
  13480. // Reset some special arrays
  13481. this._renderTargets.reset();
  13482. if (this.afterCameraRender) {
  13483. this.afterCameraRender(this.activeCamera);
  13484. }
  13485. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13486. };
  13487. Scene.prototype._processSubCameras = function (camera) {
  13488. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13489. this._renderForCamera(camera);
  13490. return;
  13491. }
  13492. // rig cameras
  13493. for (var index = 0; index < camera._rigCameras.length; index++) {
  13494. this._renderForCamera(camera._rigCameras[index]);
  13495. }
  13496. this.activeCamera = camera;
  13497. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13498. // Update camera
  13499. this.activeCamera._updateFromScene();
  13500. };
  13501. Scene.prototype._checkIntersections = function () {
  13502. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13503. var sourceMesh = this._meshesForIntersections.data[index];
  13504. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13505. var action = sourceMesh.actionManager.actions[actionIndex];
  13506. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13507. var parameters = action.getTriggerParameter();
  13508. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13509. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13510. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13511. if (areIntersecting && currentIntersectionInProgress === -1) {
  13512. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13513. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13514. sourceMesh._intersectionsInProgress.push(otherMesh);
  13515. }
  13516. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13517. sourceMesh._intersectionsInProgress.push(otherMesh);
  13518. }
  13519. }
  13520. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13521. //They intersected, and now they don't.
  13522. //is this trigger an exit trigger? execute an event.
  13523. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13524. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13525. }
  13526. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13527. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13528. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13529. }
  13530. }
  13531. }
  13532. }
  13533. }
  13534. };
  13535. Scene.prototype.render = function () {
  13536. var startDate = BABYLON.Tools.Now;
  13537. this._particlesDuration = 0;
  13538. this._spritesDuration = 0;
  13539. this._activeParticles = 0;
  13540. this._renderDuration = 0;
  13541. this._renderTargetsDuration = 0;
  13542. this._evaluateActiveMeshesDuration = 0;
  13543. this._totalVertices = 0;
  13544. this._activeIndices = 0;
  13545. this._activeBones = 0;
  13546. this.getEngine().resetDrawCalls();
  13547. this._meshesForIntersections.reset();
  13548. this.resetCachedMaterial();
  13549. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13550. // Actions
  13551. if (this.actionManager) {
  13552. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13553. }
  13554. //Simplification Queue
  13555. if (!this.simplificationQueue.running) {
  13556. this.simplificationQueue.executeNext();
  13557. }
  13558. // Before render
  13559. if (this.beforeRender) {
  13560. this.beforeRender();
  13561. }
  13562. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13563. this._onBeforeRenderCallbacks[callbackIndex]();
  13564. }
  13565. // Animations
  13566. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13567. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13568. this._animate();
  13569. // Physics
  13570. if (this._physicsEngine) {
  13571. BABYLON.Tools.StartPerformanceCounter("Physics");
  13572. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13573. BABYLON.Tools.EndPerformanceCounter("Physics");
  13574. }
  13575. // Customs render targets
  13576. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13577. var engine = this.getEngine();
  13578. var currentActiveCamera = this.activeCamera;
  13579. if (this.renderTargetsEnabled) {
  13580. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13581. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13582. var renderTarget = this.customRenderTargets[customIndex];
  13583. if (renderTarget._shouldRender()) {
  13584. this._renderId++;
  13585. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13586. if (!this.activeCamera)
  13587. throw new Error("Active camera not set");
  13588. // Viewport
  13589. engine.setViewport(this.activeCamera.viewport);
  13590. // Camera
  13591. this.updateTransformMatrix();
  13592. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13593. }
  13594. }
  13595. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13596. this._renderId++;
  13597. }
  13598. if (this.customRenderTargets.length > 0) {
  13599. engine.restoreDefaultFramebuffer();
  13600. }
  13601. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13602. this.activeCamera = currentActiveCamera;
  13603. // Procedural textures
  13604. if (this.proceduralTexturesEnabled) {
  13605. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13606. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13607. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13608. if (proceduralTexture._shouldRender()) {
  13609. proceduralTexture.render();
  13610. }
  13611. }
  13612. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13613. }
  13614. // Clear
  13615. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13616. // Shadows
  13617. if (this.shadowsEnabled) {
  13618. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13619. var light = this.lights[lightIndex];
  13620. var shadowGenerator = light.getShadowGenerator();
  13621. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13622. this._renderTargets.push(shadowGenerator.getShadowMap());
  13623. }
  13624. }
  13625. }
  13626. // Depth renderer
  13627. if (this._depthRenderer) {
  13628. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13629. }
  13630. // RenderPipeline
  13631. this.postProcessRenderPipelineManager.update();
  13632. // Multi-cameras?
  13633. if (this.activeCameras.length > 0) {
  13634. var currentRenderId = this._renderId;
  13635. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13636. this._renderId = currentRenderId;
  13637. this._processSubCameras(this.activeCameras[cameraIndex]);
  13638. }
  13639. }
  13640. else {
  13641. if (!this.activeCamera) {
  13642. throw new Error("No camera defined");
  13643. }
  13644. this._processSubCameras(this.activeCamera);
  13645. }
  13646. // Intersection checks
  13647. this._checkIntersections();
  13648. // Update the audio listener attached to the camera
  13649. this._updateAudioParameters();
  13650. // After render
  13651. if (this.afterRender) {
  13652. this.afterRender();
  13653. }
  13654. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13655. this._onAfterRenderCallbacks[callbackIndex]();
  13656. }
  13657. // Cleaning
  13658. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13659. this._toBeDisposed.data[index].dispose();
  13660. this._toBeDisposed[index] = null;
  13661. }
  13662. this._toBeDisposed.reset();
  13663. if (this.dumpNextRenderTargets) {
  13664. this.dumpNextRenderTargets = false;
  13665. }
  13666. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13667. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13668. };
  13669. Scene.prototype._updateAudioParameters = function () {
  13670. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13671. return;
  13672. }
  13673. var listeningCamera;
  13674. var audioEngine = BABYLON.Engine.audioEngine;
  13675. if (this.activeCameras.length > 0) {
  13676. listeningCamera = this.activeCameras[0];
  13677. }
  13678. else {
  13679. listeningCamera = this.activeCamera;
  13680. }
  13681. if (listeningCamera && audioEngine.canUseWebAudio) {
  13682. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13683. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13684. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13685. cameraDirection.normalize();
  13686. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13687. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13688. var sound = this.mainSoundTrack.soundCollection[i];
  13689. if (sound.useCustomAttenuation) {
  13690. sound.updateDistanceFromListener();
  13691. }
  13692. }
  13693. for (i = 0; i < this.soundTracks.length; i++) {
  13694. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13695. sound = this.soundTracks[i].soundCollection[j];
  13696. if (sound.useCustomAttenuation) {
  13697. sound.updateDistanceFromListener();
  13698. }
  13699. }
  13700. }
  13701. }
  13702. };
  13703. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13704. // Audio
  13705. get: function () {
  13706. return this._audioEnabled;
  13707. },
  13708. set: function (value) {
  13709. this._audioEnabled = value;
  13710. if (this._audioEnabled) {
  13711. this._enableAudio();
  13712. }
  13713. else {
  13714. this._disableAudio();
  13715. }
  13716. },
  13717. enumerable: true,
  13718. configurable: true
  13719. });
  13720. Scene.prototype._disableAudio = function () {
  13721. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13722. this.mainSoundTrack.soundCollection[i].pause();
  13723. }
  13724. for (i = 0; i < this.soundTracks.length; i++) {
  13725. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13726. this.soundTracks[i].soundCollection[j].pause();
  13727. }
  13728. }
  13729. };
  13730. Scene.prototype._enableAudio = function () {
  13731. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13732. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13733. this.mainSoundTrack.soundCollection[i].play();
  13734. }
  13735. }
  13736. for (i = 0; i < this.soundTracks.length; i++) {
  13737. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13738. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13739. this.soundTracks[i].soundCollection[j].play();
  13740. }
  13741. }
  13742. }
  13743. };
  13744. Object.defineProperty(Scene.prototype, "headphone", {
  13745. get: function () {
  13746. return this._headphone;
  13747. },
  13748. set: function (value) {
  13749. this._headphone = value;
  13750. if (this._headphone) {
  13751. this._switchAudioModeForHeadphones();
  13752. }
  13753. else {
  13754. this._switchAudioModeForNormalSpeakers();
  13755. }
  13756. },
  13757. enumerable: true,
  13758. configurable: true
  13759. });
  13760. Scene.prototype._switchAudioModeForHeadphones = function () {
  13761. this.mainSoundTrack.switchPanningModelToHRTF();
  13762. for (var i = 0; i < this.soundTracks.length; i++) {
  13763. this.soundTracks[i].switchPanningModelToHRTF();
  13764. }
  13765. };
  13766. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13767. this.mainSoundTrack.switchPanningModelToEqualPower();
  13768. for (var i = 0; i < this.soundTracks.length; i++) {
  13769. this.soundTracks[i].switchPanningModelToEqualPower();
  13770. }
  13771. };
  13772. Scene.prototype.enableDepthRenderer = function () {
  13773. if (this._depthRenderer) {
  13774. return this._depthRenderer;
  13775. }
  13776. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13777. return this._depthRenderer;
  13778. };
  13779. Scene.prototype.disableDepthRenderer = function () {
  13780. if (!this._depthRenderer) {
  13781. return;
  13782. }
  13783. this._depthRenderer.dispose();
  13784. this._depthRenderer = null;
  13785. };
  13786. Scene.prototype.dispose = function () {
  13787. this.beforeRender = null;
  13788. this.afterRender = null;
  13789. this.skeletons = [];
  13790. this._boundingBoxRenderer.dispose();
  13791. if (this._depthRenderer) {
  13792. this._depthRenderer.dispose();
  13793. }
  13794. // Debug layer
  13795. this.debugLayer.hide();
  13796. // Events
  13797. if (this.onDispose) {
  13798. this.onDispose();
  13799. }
  13800. this._onBeforeRenderCallbacks = [];
  13801. this._onAfterRenderCallbacks = [];
  13802. this.detachControl();
  13803. // Release sounds & sounds tracks
  13804. this.disposeSounds();
  13805. // Detach cameras
  13806. var canvas = this._engine.getRenderingCanvas();
  13807. var index;
  13808. for (index = 0; index < this.cameras.length; index++) {
  13809. this.cameras[index].detachControl(canvas);
  13810. }
  13811. // Release lights
  13812. while (this.lights.length) {
  13813. this.lights[0].dispose();
  13814. }
  13815. // Release meshes
  13816. while (this.meshes.length) {
  13817. this.meshes[0].dispose(true);
  13818. }
  13819. // Release cameras
  13820. while (this.cameras.length) {
  13821. this.cameras[0].dispose();
  13822. }
  13823. // Release materials
  13824. while (this.materials.length) {
  13825. this.materials[0].dispose();
  13826. }
  13827. // Release particles
  13828. while (this.particleSystems.length) {
  13829. this.particleSystems[0].dispose();
  13830. }
  13831. // Release sprites
  13832. while (this.spriteManagers.length) {
  13833. this.spriteManagers[0].dispose();
  13834. }
  13835. // Release layers
  13836. while (this.layers.length) {
  13837. this.layers[0].dispose();
  13838. }
  13839. // Release textures
  13840. while (this.textures.length) {
  13841. this.textures[0].dispose();
  13842. }
  13843. // Post-processes
  13844. this.postProcessManager.dispose();
  13845. // Physics
  13846. if (this._physicsEngine) {
  13847. this.disablePhysicsEngine();
  13848. }
  13849. // Remove from engine
  13850. index = this._engine.scenes.indexOf(this);
  13851. if (index > -1) {
  13852. this._engine.scenes.splice(index, 1);
  13853. }
  13854. this._engine.wipeCaches();
  13855. };
  13856. // Release sounds & sounds tracks
  13857. Scene.prototype.disposeSounds = function () {
  13858. this.mainSoundTrack.dispose();
  13859. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13860. this.soundTracks[scIndex].dispose();
  13861. }
  13862. };
  13863. // Octrees
  13864. Scene.prototype.getWorldExtends = function () {
  13865. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13866. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13867. for (var index = 0; index < this.meshes.length; index++) {
  13868. var mesh = this.meshes[index];
  13869. mesh.computeWorldMatrix(true);
  13870. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13871. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13872. BABYLON.Tools.CheckExtends(minBox, min, max);
  13873. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13874. }
  13875. return {
  13876. min: min,
  13877. max: max
  13878. };
  13879. };
  13880. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13881. if (maxCapacity === void 0) { maxCapacity = 64; }
  13882. if (maxDepth === void 0) { maxDepth = 2; }
  13883. if (!this._selectionOctree) {
  13884. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13885. }
  13886. var worldExtends = this.getWorldExtends();
  13887. // Update octree
  13888. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13889. return this._selectionOctree;
  13890. };
  13891. // Picking
  13892. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13893. var engine = this._engine;
  13894. if (!camera) {
  13895. if (!this.activeCamera)
  13896. throw new Error("Active camera not set");
  13897. camera = this.activeCamera;
  13898. }
  13899. var cameraViewport = camera.viewport;
  13900. var viewport = cameraViewport.toGlobal(engine);
  13901. // Moving coordinates to local viewport world
  13902. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13903. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13904. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13905. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13906. };
  13907. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13908. var pickingInfo = null;
  13909. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13910. var mesh = this.meshes[meshIndex];
  13911. if (predicate) {
  13912. if (!predicate(mesh)) {
  13913. continue;
  13914. }
  13915. }
  13916. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13917. continue;
  13918. }
  13919. var world = mesh.getWorldMatrix();
  13920. var ray = rayFunction(world);
  13921. var result = mesh.intersects(ray, fastCheck);
  13922. if (!result || !result.hit)
  13923. continue;
  13924. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13925. continue;
  13926. pickingInfo = result;
  13927. if (fastCheck) {
  13928. break;
  13929. }
  13930. }
  13931. return pickingInfo || new BABYLON.PickingInfo();
  13932. };
  13933. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13934. var _this = this;
  13935. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13936. /// <param name="x">X position on screen</param>
  13937. /// <param name="y">Y position on screen</param>
  13938. /// <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>
  13939. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13940. /// <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>
  13941. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13942. };
  13943. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13944. var _this = this;
  13945. return this._internalPick(function (world) {
  13946. if (!_this._pickWithRayInverseMatrix) {
  13947. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13948. }
  13949. world.invertToRef(_this._pickWithRayInverseMatrix);
  13950. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13951. }, predicate, fastCheck);
  13952. };
  13953. Scene.prototype.setPointerOverMesh = function (mesh) {
  13954. if (this._pointerOverMesh === mesh) {
  13955. return;
  13956. }
  13957. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13958. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13959. }
  13960. this._pointerOverMesh = mesh;
  13961. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13962. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13963. }
  13964. };
  13965. Scene.prototype.getPointerOverMesh = function () {
  13966. return this._pointerOverMesh;
  13967. };
  13968. // Physics
  13969. Scene.prototype.getPhysicsEngine = function () {
  13970. return this._physicsEngine;
  13971. };
  13972. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13973. if (this._physicsEngine) {
  13974. return true;
  13975. }
  13976. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13977. if (!this._physicsEngine.isSupported()) {
  13978. this._physicsEngine = null;
  13979. return false;
  13980. }
  13981. this._physicsEngine._initialize(gravity);
  13982. return true;
  13983. };
  13984. Scene.prototype.disablePhysicsEngine = function () {
  13985. if (!this._physicsEngine) {
  13986. return;
  13987. }
  13988. this._physicsEngine.dispose();
  13989. this._physicsEngine = undefined;
  13990. };
  13991. Scene.prototype.isPhysicsEnabled = function () {
  13992. return this._physicsEngine !== undefined;
  13993. };
  13994. Scene.prototype.setGravity = function (gravity) {
  13995. if (!this._physicsEngine) {
  13996. return;
  13997. }
  13998. this._physicsEngine._setGravity(gravity);
  13999. };
  14000. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14001. if (parts.parts) {
  14002. options = parts;
  14003. parts = parts.parts;
  14004. }
  14005. if (!this._physicsEngine) {
  14006. return null;
  14007. }
  14008. for (var index = 0; index < parts.length; index++) {
  14009. var mesh = parts[index].mesh;
  14010. mesh._physicImpostor = parts[index].impostor;
  14011. mesh._physicsMass = options.mass / parts.length;
  14012. mesh._physicsFriction = options.friction;
  14013. mesh._physicRestitution = options.restitution;
  14014. }
  14015. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14016. };
  14017. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14018. for (var index = 0; index < compound.parts.length; index++) {
  14019. var mesh = compound.parts[index].mesh;
  14020. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14021. this._physicsEngine._unregisterMesh(mesh);
  14022. }
  14023. };
  14024. // Misc.
  14025. Scene.prototype.createDefaultCameraOrLight = function () {
  14026. // Light
  14027. if (this.lights.length === 0) {
  14028. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14029. }
  14030. // Camera
  14031. if (!this.activeCamera) {
  14032. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14033. // Compute position
  14034. var worldExtends = this.getWorldExtends();
  14035. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14036. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14037. camera.setTarget(worldCenter);
  14038. this.activeCamera = camera;
  14039. }
  14040. };
  14041. // Tags
  14042. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14043. if (tagsQuery === undefined) {
  14044. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14045. return list;
  14046. }
  14047. var listByTags = [];
  14048. forEach = forEach || (function (item) { return; });
  14049. for (var i in list) {
  14050. var item = list[i];
  14051. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14052. listByTags.push(item);
  14053. forEach(item);
  14054. }
  14055. }
  14056. return listByTags;
  14057. };
  14058. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14059. return this._getByTags(this.meshes, tagsQuery, forEach);
  14060. };
  14061. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14062. return this._getByTags(this.cameras, tagsQuery, forEach);
  14063. };
  14064. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14065. return this._getByTags(this.lights, tagsQuery, forEach);
  14066. };
  14067. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14068. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14069. };
  14070. // Statics
  14071. Scene._FOGMODE_NONE = 0;
  14072. Scene._FOGMODE_EXP = 1;
  14073. Scene._FOGMODE_EXP2 = 2;
  14074. Scene._FOGMODE_LINEAR = 3;
  14075. Scene.MinDeltaTime = 1.0;
  14076. Scene.MaxDeltaTime = 1000.0;
  14077. return Scene;
  14078. })();
  14079. BABYLON.Scene = Scene;
  14080. })(BABYLON || (BABYLON = {}));
  14081. var BABYLON;
  14082. (function (BABYLON) {
  14083. var VertexBuffer = (function () {
  14084. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14085. if (engine instanceof BABYLON.Mesh) {
  14086. this._engine = engine.getScene().getEngine();
  14087. }
  14088. else {
  14089. this._engine = engine;
  14090. }
  14091. this._updatable = updatable;
  14092. this._data = data;
  14093. if (!postponeInternalCreation) {
  14094. this.create();
  14095. }
  14096. this._kind = kind;
  14097. if (stride) {
  14098. this._strideSize = stride;
  14099. return;
  14100. }
  14101. // Deduce stride from kind
  14102. switch (kind) {
  14103. case VertexBuffer.PositionKind:
  14104. this._strideSize = 3;
  14105. break;
  14106. case VertexBuffer.NormalKind:
  14107. this._strideSize = 3;
  14108. break;
  14109. case VertexBuffer.UVKind:
  14110. case VertexBuffer.UV2Kind:
  14111. case VertexBuffer.UV3Kind:
  14112. case VertexBuffer.UV4Kind:
  14113. case VertexBuffer.UV5Kind:
  14114. case VertexBuffer.UV6Kind:
  14115. this._strideSize = 2;
  14116. break;
  14117. case VertexBuffer.ColorKind:
  14118. this._strideSize = 4;
  14119. break;
  14120. case VertexBuffer.MatricesIndicesKind:
  14121. this._strideSize = 4;
  14122. break;
  14123. case VertexBuffer.MatricesWeightsKind:
  14124. this._strideSize = 4;
  14125. break;
  14126. }
  14127. }
  14128. // Properties
  14129. VertexBuffer.prototype.isUpdatable = function () {
  14130. return this._updatable;
  14131. };
  14132. VertexBuffer.prototype.getData = function () {
  14133. return this._data;
  14134. };
  14135. VertexBuffer.prototype.getBuffer = function () {
  14136. return this._buffer;
  14137. };
  14138. VertexBuffer.prototype.getStrideSize = function () {
  14139. return this._strideSize;
  14140. };
  14141. // Methods
  14142. VertexBuffer.prototype.create = function (data) {
  14143. if (!data && this._buffer) {
  14144. return; // nothing to do
  14145. }
  14146. data = data || this._data;
  14147. if (!this._buffer) {
  14148. if (this._updatable) {
  14149. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14150. }
  14151. else {
  14152. this._buffer = this._engine.createVertexBuffer(data);
  14153. }
  14154. }
  14155. if (this._updatable) {
  14156. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14157. this._data = data;
  14158. }
  14159. };
  14160. VertexBuffer.prototype.update = function (data) {
  14161. this.create(data);
  14162. };
  14163. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14164. if (!this._buffer) {
  14165. return;
  14166. }
  14167. if (this._updatable) {
  14168. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14169. this._data = null;
  14170. }
  14171. };
  14172. VertexBuffer.prototype.dispose = function () {
  14173. if (!this._buffer) {
  14174. return;
  14175. }
  14176. if (this._engine._releaseBuffer(this._buffer)) {
  14177. this._buffer = null;
  14178. }
  14179. };
  14180. Object.defineProperty(VertexBuffer, "PositionKind", {
  14181. get: function () {
  14182. return VertexBuffer._PositionKind;
  14183. },
  14184. enumerable: true,
  14185. configurable: true
  14186. });
  14187. Object.defineProperty(VertexBuffer, "NormalKind", {
  14188. get: function () {
  14189. return VertexBuffer._NormalKind;
  14190. },
  14191. enumerable: true,
  14192. configurable: true
  14193. });
  14194. Object.defineProperty(VertexBuffer, "UVKind", {
  14195. get: function () {
  14196. return VertexBuffer._UVKind;
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14202. get: function () {
  14203. return VertexBuffer._UV2Kind;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14209. get: function () {
  14210. return VertexBuffer._UV3Kind;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14216. get: function () {
  14217. return VertexBuffer._UV4Kind;
  14218. },
  14219. enumerable: true,
  14220. configurable: true
  14221. });
  14222. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14223. get: function () {
  14224. return VertexBuffer._UV5Kind;
  14225. },
  14226. enumerable: true,
  14227. configurable: true
  14228. });
  14229. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14230. get: function () {
  14231. return VertexBuffer._UV6Kind;
  14232. },
  14233. enumerable: true,
  14234. configurable: true
  14235. });
  14236. Object.defineProperty(VertexBuffer, "ColorKind", {
  14237. get: function () {
  14238. return VertexBuffer._ColorKind;
  14239. },
  14240. enumerable: true,
  14241. configurable: true
  14242. });
  14243. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14244. get: function () {
  14245. return VertexBuffer._MatricesIndicesKind;
  14246. },
  14247. enumerable: true,
  14248. configurable: true
  14249. });
  14250. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14251. get: function () {
  14252. return VertexBuffer._MatricesWeightsKind;
  14253. },
  14254. enumerable: true,
  14255. configurable: true
  14256. });
  14257. // Enums
  14258. VertexBuffer._PositionKind = "position";
  14259. VertexBuffer._NormalKind = "normal";
  14260. VertexBuffer._UVKind = "uv";
  14261. VertexBuffer._UV2Kind = "uv2";
  14262. VertexBuffer._UV3Kind = "uv3";
  14263. VertexBuffer._UV4Kind = "uv4";
  14264. VertexBuffer._UV5Kind = "uv5";
  14265. VertexBuffer._UV6Kind = "uv6";
  14266. VertexBuffer._ColorKind = "color";
  14267. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14268. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14269. return VertexBuffer;
  14270. })();
  14271. BABYLON.VertexBuffer = VertexBuffer;
  14272. })(BABYLON || (BABYLON = {}));
  14273. var BABYLON;
  14274. (function (BABYLON) {
  14275. /**
  14276. * Creates an instance based on a source mesh.
  14277. */
  14278. var InstancedMesh = (function (_super) {
  14279. __extends(InstancedMesh, _super);
  14280. function InstancedMesh(name, source) {
  14281. _super.call(this, name, source.getScene());
  14282. source.instances.push(this);
  14283. this._sourceMesh = source;
  14284. this.position.copyFrom(source.position);
  14285. this.rotation.copyFrom(source.rotation);
  14286. this.scaling.copyFrom(source.scaling);
  14287. if (source.rotationQuaternion) {
  14288. this.rotationQuaternion = source.rotationQuaternion.clone();
  14289. }
  14290. this.infiniteDistance = source.infiniteDistance;
  14291. this.setPivotMatrix(source.getPivotMatrix());
  14292. this.refreshBoundingInfo();
  14293. this._syncSubMeshes();
  14294. }
  14295. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14296. // Methods
  14297. get: function () {
  14298. return this._sourceMesh.receiveShadows;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(InstancedMesh.prototype, "material", {
  14304. get: function () {
  14305. return this._sourceMesh.material;
  14306. },
  14307. enumerable: true,
  14308. configurable: true
  14309. });
  14310. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14311. get: function () {
  14312. return this._sourceMesh.visibility;
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14318. get: function () {
  14319. return this._sourceMesh.skeleton;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. InstancedMesh.prototype.getTotalVertices = function () {
  14325. return this._sourceMesh.getTotalVertices();
  14326. };
  14327. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14328. get: function () {
  14329. return this._sourceMesh;
  14330. },
  14331. enumerable: true,
  14332. configurable: true
  14333. });
  14334. InstancedMesh.prototype.getVerticesData = function (kind) {
  14335. return this._sourceMesh.getVerticesData(kind);
  14336. };
  14337. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14338. return this._sourceMesh.isVerticesDataPresent(kind);
  14339. };
  14340. InstancedMesh.prototype.getIndices = function () {
  14341. return this._sourceMesh.getIndices();
  14342. };
  14343. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14344. get: function () {
  14345. return this._sourceMesh._positions;
  14346. },
  14347. enumerable: true,
  14348. configurable: true
  14349. });
  14350. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14351. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14352. if (data) {
  14353. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14354. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14355. }
  14356. this._updateBoundingInfo();
  14357. };
  14358. InstancedMesh.prototype._preActivate = function () {
  14359. if (this._currentLOD) {
  14360. this._currentLOD._preActivate();
  14361. }
  14362. };
  14363. InstancedMesh.prototype._activate = function (renderId) {
  14364. if (this._currentLOD) {
  14365. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14366. }
  14367. };
  14368. InstancedMesh.prototype.getLOD = function (camera) {
  14369. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14370. if (this._currentLOD === this.sourceMesh) {
  14371. return this;
  14372. }
  14373. return this._currentLOD;
  14374. };
  14375. InstancedMesh.prototype._syncSubMeshes = function () {
  14376. this.releaseSubMeshes();
  14377. if (this._sourceMesh.subMeshes) {
  14378. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14379. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14380. }
  14381. }
  14382. };
  14383. InstancedMesh.prototype._generatePointsArray = function () {
  14384. return this._sourceMesh._generatePointsArray();
  14385. };
  14386. // Clone
  14387. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14388. var result = this._sourceMesh.createInstance(name);
  14389. // Deep copy
  14390. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14391. // Bounding info
  14392. this.refreshBoundingInfo();
  14393. // Parent
  14394. if (newParent) {
  14395. result.parent = newParent;
  14396. }
  14397. if (!doNotCloneChildren) {
  14398. // Children
  14399. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14400. var mesh = this.getScene().meshes[index];
  14401. if (mesh.parent === this) {
  14402. mesh.clone(mesh.name, result);
  14403. }
  14404. }
  14405. }
  14406. result.computeWorldMatrix(true);
  14407. return result;
  14408. };
  14409. // Dispoe
  14410. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14411. // Remove from mesh
  14412. var index = this._sourceMesh.instances.indexOf(this);
  14413. this._sourceMesh.instances.splice(index, 1);
  14414. _super.prototype.dispose.call(this, doNotRecurse);
  14415. };
  14416. return InstancedMesh;
  14417. })(BABYLON.AbstractMesh);
  14418. BABYLON.InstancedMesh = InstancedMesh;
  14419. })(BABYLON || (BABYLON = {}));
  14420. var BABYLON;
  14421. (function (BABYLON) {
  14422. var _InstancesBatch = (function () {
  14423. function _InstancesBatch() {
  14424. this.mustReturn = false;
  14425. this.visibleInstances = new Array();
  14426. this.renderSelf = new Array();
  14427. }
  14428. return _InstancesBatch;
  14429. })();
  14430. BABYLON._InstancesBatch = _InstancesBatch;
  14431. var Mesh = (function (_super) {
  14432. __extends(Mesh, _super);
  14433. /**
  14434. * @constructor
  14435. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14436. * @param {Scene} scene - The scene to add this mesh to.
  14437. * @param {Node} parent - The parent of this mesh, if it has one
  14438. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14439. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14440. * When false, achieved by calling a clone(), also passing False.
  14441. * This will make creation of children, recursive.
  14442. */
  14443. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14444. if (parent === void 0) { parent = null; }
  14445. _super.call(this, name, scene);
  14446. // Members
  14447. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14448. this.instances = new Array();
  14449. this._LODLevels = new Array();
  14450. this._onBeforeRenderCallbacks = new Array();
  14451. this._onAfterRenderCallbacks = new Array();
  14452. this._visibleInstances = {};
  14453. this._renderIdForInstances = new Array();
  14454. this._batchCache = new _InstancesBatch();
  14455. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14456. this._sideOrientation = Mesh._DEFAULTSIDE;
  14457. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14458. if (source) {
  14459. // Geometry
  14460. if (source._geometry) {
  14461. source._geometry.applyToMesh(this);
  14462. }
  14463. // Deep copy
  14464. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14465. // Material
  14466. this.material = source.material;
  14467. if (!doNotCloneChildren) {
  14468. // Children
  14469. for (var index = 0; index < scene.meshes.length; index++) {
  14470. var mesh = scene.meshes[index];
  14471. if (mesh.parent === source) {
  14472. // doNotCloneChildren is always going to be False
  14473. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14474. }
  14475. }
  14476. }
  14477. // Particles
  14478. for (index = 0; index < scene.particleSystems.length; index++) {
  14479. var system = scene.particleSystems[index];
  14480. if (system.emitter === source) {
  14481. system.clone(system.name, this);
  14482. }
  14483. }
  14484. this.computeWorldMatrix(true);
  14485. }
  14486. // Parent
  14487. if (parent !== null) {
  14488. this.parent = parent;
  14489. }
  14490. }
  14491. Object.defineProperty(Mesh, "FRONTSIDE", {
  14492. get: function () {
  14493. return Mesh._FRONTSIDE;
  14494. },
  14495. enumerable: true,
  14496. configurable: true
  14497. });
  14498. Object.defineProperty(Mesh, "BACKSIDE", {
  14499. get: function () {
  14500. return Mesh._BACKSIDE;
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14506. get: function () {
  14507. return Mesh._DOUBLESIDE;
  14508. },
  14509. enumerable: true,
  14510. configurable: true
  14511. });
  14512. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14513. get: function () {
  14514. return Mesh._DEFAULTSIDE;
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. Object.defineProperty(Mesh, "NO_CAP", {
  14520. get: function () {
  14521. return Mesh._NO_CAP;
  14522. },
  14523. enumerable: true,
  14524. configurable: true
  14525. });
  14526. Object.defineProperty(Mesh, "CAP_START", {
  14527. get: function () {
  14528. return Mesh._CAP_START;
  14529. },
  14530. enumerable: true,
  14531. configurable: true
  14532. });
  14533. Object.defineProperty(Mesh, "CAP_END", {
  14534. get: function () {
  14535. return Mesh._CAP_END;
  14536. },
  14537. enumerable: true,
  14538. configurable: true
  14539. });
  14540. Object.defineProperty(Mesh, "CAP_ALL", {
  14541. get: function () {
  14542. return Mesh._CAP_ALL;
  14543. },
  14544. enumerable: true,
  14545. configurable: true
  14546. });
  14547. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14548. // Methods
  14549. get: function () {
  14550. return this._LODLevels.length > 0;
  14551. },
  14552. enumerable: true,
  14553. configurable: true
  14554. });
  14555. Mesh.prototype._sortLODLevels = function () {
  14556. this._LODLevels.sort(function (a, b) {
  14557. if (a.distance < b.distance) {
  14558. return 1;
  14559. }
  14560. if (a.distance > b.distance) {
  14561. return -1;
  14562. }
  14563. return 0;
  14564. });
  14565. };
  14566. /**
  14567. * Add a mesh as LOD level triggered at the given distance.
  14568. * @param {number} distance - the distance from the center of the object to show this level
  14569. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14570. * @return {BABYLON.Mesh} this mesh (for chaining)
  14571. */
  14572. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14573. if (mesh && mesh._masterMesh) {
  14574. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14575. return this;
  14576. }
  14577. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14578. this._LODLevels.push(level);
  14579. if (mesh) {
  14580. mesh._masterMesh = this;
  14581. }
  14582. this._sortLODLevels();
  14583. return this;
  14584. };
  14585. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14586. for (var index = 0; index < this._LODLevels.length; index++) {
  14587. var level = this._LODLevels[index];
  14588. if (level.distance === distance) {
  14589. return level.mesh;
  14590. }
  14591. }
  14592. return null;
  14593. };
  14594. /**
  14595. * Remove a mesh from the LOD array
  14596. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14597. * @return {BABYLON.Mesh} this mesh (for chaining)
  14598. */
  14599. Mesh.prototype.removeLODLevel = function (mesh) {
  14600. for (var index = 0; index < this._LODLevels.length; index++) {
  14601. if (this._LODLevels[index].mesh === mesh) {
  14602. this._LODLevels.splice(index, 1);
  14603. if (mesh) {
  14604. mesh._masterMesh = null;
  14605. }
  14606. }
  14607. }
  14608. this._sortLODLevels();
  14609. return this;
  14610. };
  14611. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14612. if (!this._LODLevels || this._LODLevels.length === 0) {
  14613. return this;
  14614. }
  14615. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14616. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14617. if (this.onLODLevelSelection) {
  14618. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14619. }
  14620. return this;
  14621. }
  14622. for (var index = 0; index < this._LODLevels.length; index++) {
  14623. var level = this._LODLevels[index];
  14624. if (level.distance < distanceToCamera) {
  14625. if (level.mesh) {
  14626. level.mesh._preActivate();
  14627. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14628. }
  14629. if (this.onLODLevelSelection) {
  14630. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14631. }
  14632. return level.mesh;
  14633. }
  14634. }
  14635. if (this.onLODLevelSelection) {
  14636. this.onLODLevelSelection(distanceToCamera, this, this);
  14637. }
  14638. return this;
  14639. };
  14640. Object.defineProperty(Mesh.prototype, "geometry", {
  14641. get: function () {
  14642. return this._geometry;
  14643. },
  14644. enumerable: true,
  14645. configurable: true
  14646. });
  14647. Mesh.prototype.getTotalVertices = function () {
  14648. if (!this._geometry) {
  14649. return 0;
  14650. }
  14651. return this._geometry.getTotalVertices();
  14652. };
  14653. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14654. if (!this._geometry) {
  14655. return null;
  14656. }
  14657. return this._geometry.getVerticesData(kind, copyWhenShared);
  14658. };
  14659. Mesh.prototype.getVertexBuffer = function (kind) {
  14660. if (!this._geometry) {
  14661. return undefined;
  14662. }
  14663. return this._geometry.getVertexBuffer(kind);
  14664. };
  14665. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14666. if (!this._geometry) {
  14667. if (this._delayInfo) {
  14668. return this._delayInfo.indexOf(kind) !== -1;
  14669. }
  14670. return false;
  14671. }
  14672. return this._geometry.isVerticesDataPresent(kind);
  14673. };
  14674. Mesh.prototype.getVerticesDataKinds = function () {
  14675. if (!this._geometry) {
  14676. var result = [];
  14677. if (this._delayInfo) {
  14678. for (var kind in this._delayInfo) {
  14679. result.push(kind);
  14680. }
  14681. }
  14682. return result;
  14683. }
  14684. return this._geometry.getVerticesDataKinds();
  14685. };
  14686. Mesh.prototype.getTotalIndices = function () {
  14687. if (!this._geometry) {
  14688. return 0;
  14689. }
  14690. return this._geometry.getTotalIndices();
  14691. };
  14692. Mesh.prototype.getIndices = function (copyWhenShared) {
  14693. if (!this._geometry) {
  14694. return [];
  14695. }
  14696. return this._geometry.getIndices(copyWhenShared);
  14697. };
  14698. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14699. get: function () {
  14700. return this._masterMesh !== null && this._masterMesh !== undefined;
  14701. },
  14702. enumerable: true,
  14703. configurable: true
  14704. });
  14705. Mesh.prototype.isReady = function () {
  14706. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14707. return false;
  14708. }
  14709. return _super.prototype.isReady.call(this);
  14710. };
  14711. Mesh.prototype.isDisposed = function () {
  14712. return this._isDisposed;
  14713. };
  14714. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14715. get: function () {
  14716. return this._sideOrientation;
  14717. },
  14718. set: function (sideO) {
  14719. this._sideOrientation = sideO;
  14720. },
  14721. enumerable: true,
  14722. configurable: true
  14723. });
  14724. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14725. get: function () {
  14726. return this._areNormalsFrozen;
  14727. },
  14728. enumerable: true,
  14729. configurable: true
  14730. });
  14731. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14732. Mesh.prototype.freezeNormals = function () {
  14733. this._areNormalsFrozen = true;
  14734. };
  14735. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14736. Mesh.prototype.unfreezeNormals = function () {
  14737. this._areNormalsFrozen = false;
  14738. };
  14739. // Methods
  14740. Mesh.prototype._preActivate = function () {
  14741. var sceneRenderId = this.getScene().getRenderId();
  14742. if (this._preActivateId === sceneRenderId) {
  14743. return;
  14744. }
  14745. this._preActivateId = sceneRenderId;
  14746. this._visibleInstances = null;
  14747. };
  14748. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14749. if (!this._visibleInstances) {
  14750. this._visibleInstances = {};
  14751. this._visibleInstances.defaultRenderId = renderId;
  14752. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14753. }
  14754. if (!this._visibleInstances[renderId]) {
  14755. this._visibleInstances[renderId] = new Array();
  14756. }
  14757. this._visibleInstances[renderId].push(instance);
  14758. };
  14759. Mesh.prototype.refreshBoundingInfo = function () {
  14760. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14761. if (data) {
  14762. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14763. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14764. }
  14765. if (this.subMeshes) {
  14766. for (var index = 0; index < this.subMeshes.length; index++) {
  14767. this.subMeshes[index].refreshBoundingInfo();
  14768. }
  14769. }
  14770. this._updateBoundingInfo();
  14771. };
  14772. Mesh.prototype._createGlobalSubMesh = function () {
  14773. var totalVertices = this.getTotalVertices();
  14774. if (!totalVertices || !this.getIndices()) {
  14775. return null;
  14776. }
  14777. this.releaseSubMeshes();
  14778. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14779. };
  14780. Mesh.prototype.subdivide = function (count) {
  14781. if (count < 1) {
  14782. return;
  14783. }
  14784. var totalIndices = this.getTotalIndices();
  14785. var subdivisionSize = (totalIndices / count) | 0;
  14786. var offset = 0;
  14787. // Ensure that subdivisionSize is a multiple of 3
  14788. while (subdivisionSize % 3 !== 0) {
  14789. subdivisionSize++;
  14790. }
  14791. this.releaseSubMeshes();
  14792. for (var index = 0; index < count; index++) {
  14793. if (offset >= totalIndices) {
  14794. break;
  14795. }
  14796. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14797. offset += subdivisionSize;
  14798. }
  14799. this.synchronizeInstances();
  14800. };
  14801. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14802. if (kind instanceof Array) {
  14803. var temp = data;
  14804. data = kind;
  14805. kind = temp;
  14806. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14807. }
  14808. if (!this._geometry) {
  14809. var vertexData = new BABYLON.VertexData();
  14810. vertexData.set(data, kind);
  14811. var scene = this.getScene();
  14812. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14813. }
  14814. else {
  14815. this._geometry.setVerticesData(kind, data, updatable, stride);
  14816. }
  14817. };
  14818. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14819. if (!this._geometry) {
  14820. return;
  14821. }
  14822. if (!makeItUnique) {
  14823. this._geometry.updateVerticesData(kind, data, updateExtends);
  14824. }
  14825. else {
  14826. this.makeGeometryUnique();
  14827. this.updateVerticesData(kind, data, updateExtends, false);
  14828. }
  14829. };
  14830. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14831. if (!this._geometry) {
  14832. return;
  14833. }
  14834. if (!makeItUnique) {
  14835. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14836. }
  14837. else {
  14838. this.makeGeometryUnique();
  14839. this.updateVerticesDataDirectly(kind, data, offset, false);
  14840. }
  14841. };
  14842. // Mesh positions update function :
  14843. // updates the mesh positions according to the positionFunction returned values.
  14844. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14845. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14846. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14847. if (computeNormals === void 0) { computeNormals = true; }
  14848. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14849. positionFunction(positions);
  14850. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14851. if (computeNormals) {
  14852. var indices = this.getIndices();
  14853. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14854. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14855. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14856. }
  14857. };
  14858. Mesh.prototype.makeGeometryUnique = function () {
  14859. if (!this._geometry) {
  14860. return;
  14861. }
  14862. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14863. geometry.applyToMesh(this);
  14864. };
  14865. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14866. if (!this._geometry) {
  14867. var vertexData = new BABYLON.VertexData();
  14868. vertexData.indices = indices;
  14869. var scene = this.getScene();
  14870. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14871. }
  14872. else {
  14873. this._geometry.setIndices(indices, totalVertices);
  14874. }
  14875. };
  14876. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14877. var engine = this.getScene().getEngine();
  14878. // Wireframe
  14879. var indexToBind;
  14880. switch (fillMode) {
  14881. case BABYLON.Material.PointFillMode:
  14882. indexToBind = null;
  14883. break;
  14884. case BABYLON.Material.WireFrameFillMode:
  14885. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14886. break;
  14887. default:
  14888. case BABYLON.Material.TriangleFillMode:
  14889. indexToBind = this._geometry.getIndexBuffer();
  14890. break;
  14891. }
  14892. // VBOs
  14893. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14894. };
  14895. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14896. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14897. return;
  14898. }
  14899. var engine = this.getScene().getEngine();
  14900. // Draw order
  14901. switch (fillMode) {
  14902. case BABYLON.Material.PointFillMode:
  14903. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14904. break;
  14905. case BABYLON.Material.WireFrameFillMode:
  14906. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14907. break;
  14908. default:
  14909. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14910. }
  14911. };
  14912. Mesh.prototype.registerBeforeRender = function (func) {
  14913. this._onBeforeRenderCallbacks.push(func);
  14914. };
  14915. Mesh.prototype.unregisterBeforeRender = function (func) {
  14916. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14917. if (index > -1) {
  14918. this._onBeforeRenderCallbacks.splice(index, 1);
  14919. }
  14920. };
  14921. Mesh.prototype.registerAfterRender = function (func) {
  14922. this._onAfterRenderCallbacks.push(func);
  14923. };
  14924. Mesh.prototype.unregisterAfterRender = function (func) {
  14925. var index = this._onAfterRenderCallbacks.indexOf(func);
  14926. if (index > -1) {
  14927. this._onAfterRenderCallbacks.splice(index, 1);
  14928. }
  14929. };
  14930. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14931. var scene = this.getScene();
  14932. this._batchCache.mustReturn = false;
  14933. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14934. this._batchCache.visibleInstances[subMeshId] = null;
  14935. if (this._visibleInstances) {
  14936. var currentRenderId = scene.getRenderId();
  14937. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14938. var selfRenderId = this._renderId;
  14939. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14940. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14941. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14942. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14943. }
  14944. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14945. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14946. this._batchCache.mustReturn = true;
  14947. return this._batchCache;
  14948. }
  14949. if (currentRenderId !== selfRenderId) {
  14950. this._batchCache.renderSelf[subMeshId] = false;
  14951. }
  14952. }
  14953. this._renderIdForInstances[subMeshId] = currentRenderId;
  14954. }
  14955. return this._batchCache;
  14956. };
  14957. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14958. var visibleInstances = batch.visibleInstances[subMesh._id];
  14959. var matricesCount = visibleInstances.length + 1;
  14960. var bufferSize = matricesCount * 16 * 4;
  14961. while (this._instancesBufferSize < bufferSize) {
  14962. this._instancesBufferSize *= 2;
  14963. }
  14964. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14965. if (this._worldMatricesInstancesBuffer) {
  14966. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14967. }
  14968. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14969. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14970. }
  14971. var offset = 0;
  14972. var instancesCount = 0;
  14973. var world = this.getWorldMatrix();
  14974. if (batch.renderSelf[subMesh._id]) {
  14975. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14976. offset += 16;
  14977. instancesCount++;
  14978. }
  14979. if (visibleInstances) {
  14980. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14981. var instance = visibleInstances[instanceIndex];
  14982. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14983. offset += 16;
  14984. instancesCount++;
  14985. }
  14986. }
  14987. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14988. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14989. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14990. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14991. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14992. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14993. this._draw(subMesh, fillMode, instancesCount);
  14994. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14995. };
  14996. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14997. var scene = this.getScene();
  14998. var engine = scene.getEngine();
  14999. if (hardwareInstancedRendering) {
  15000. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15001. }
  15002. else {
  15003. if (batch.renderSelf[subMesh._id]) {
  15004. // Draw
  15005. if (onBeforeDraw) {
  15006. onBeforeDraw(false, this.getWorldMatrix());
  15007. }
  15008. this._draw(subMesh, fillMode);
  15009. }
  15010. if (batch.visibleInstances[subMesh._id]) {
  15011. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15012. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15013. // World
  15014. var world = instance.getWorldMatrix();
  15015. if (onBeforeDraw) {
  15016. onBeforeDraw(true, world);
  15017. }
  15018. // Draw
  15019. this._draw(subMesh, fillMode);
  15020. }
  15021. }
  15022. }
  15023. };
  15024. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15025. var scene = this.getScene();
  15026. // Managing instances
  15027. var batch = this._getInstancesRenderList(subMesh._id);
  15028. if (batch.mustReturn) {
  15029. return;
  15030. }
  15031. // Checking geometry state
  15032. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15033. return;
  15034. }
  15035. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15036. this._onBeforeRenderCallbacks[callbackIndex](this);
  15037. }
  15038. var engine = scene.getEngine();
  15039. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15040. // Material
  15041. var effectiveMaterial = subMesh.getMaterial();
  15042. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15043. return;
  15044. }
  15045. // Outline - step 1
  15046. var savedDepthWrite = engine.getDepthWrite();
  15047. if (this.renderOutline) {
  15048. engine.setDepthWrite(false);
  15049. scene.getOutlineRenderer().render(subMesh, batch);
  15050. engine.setDepthWrite(savedDepthWrite);
  15051. }
  15052. effectiveMaterial._preBind();
  15053. var effect = effectiveMaterial.getEffect();
  15054. // Bind
  15055. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15056. this._bind(subMesh, effect, fillMode);
  15057. var world = this.getWorldMatrix();
  15058. effectiveMaterial.bind(world, this);
  15059. // Alpha mode
  15060. if (enableAlphaMode) {
  15061. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15062. }
  15063. // Draw
  15064. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15065. if (isInstance) {
  15066. effectiveMaterial.bindOnlyWorldMatrix(world);
  15067. }
  15068. });
  15069. // Unbind
  15070. effectiveMaterial.unbind();
  15071. // Outline - step 2
  15072. if (this.renderOutline && savedDepthWrite) {
  15073. engine.setDepthWrite(true);
  15074. engine.setColorWrite(false);
  15075. scene.getOutlineRenderer().render(subMesh, batch);
  15076. engine.setColorWrite(true);
  15077. }
  15078. // Overlay
  15079. if (this.renderOverlay) {
  15080. var currentMode = engine.getAlphaMode();
  15081. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15082. scene.getOutlineRenderer().render(subMesh, batch, true);
  15083. engine.setAlphaMode(currentMode);
  15084. }
  15085. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15086. this._onAfterRenderCallbacks[callbackIndex](this);
  15087. }
  15088. };
  15089. Mesh.prototype.getEmittedParticleSystems = function () {
  15090. var results = new Array();
  15091. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15092. var particleSystem = this.getScene().particleSystems[index];
  15093. if (particleSystem.emitter === this) {
  15094. results.push(particleSystem);
  15095. }
  15096. }
  15097. return results;
  15098. };
  15099. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15100. var results = new Array();
  15101. var descendants = this.getDescendants();
  15102. descendants.push(this);
  15103. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15104. var particleSystem = this.getScene().particleSystems[index];
  15105. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15106. results.push(particleSystem);
  15107. }
  15108. }
  15109. return results;
  15110. };
  15111. Mesh.prototype.getChildren = function () {
  15112. var results = [];
  15113. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15114. var mesh = this.getScene().meshes[index];
  15115. if (mesh.parent === this) {
  15116. results.push(mesh);
  15117. }
  15118. }
  15119. return results;
  15120. };
  15121. Mesh.prototype._checkDelayState = function () {
  15122. var _this = this;
  15123. var that = this;
  15124. var scene = this.getScene();
  15125. if (this._geometry) {
  15126. this._geometry.load(scene);
  15127. }
  15128. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15129. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15130. scene._addPendingData(that);
  15131. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15132. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15133. if (data instanceof ArrayBuffer) {
  15134. _this._delayLoadingFunction(data, _this);
  15135. }
  15136. else {
  15137. _this._delayLoadingFunction(JSON.parse(data), _this);
  15138. }
  15139. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15140. scene._removePendingData(_this);
  15141. }, function () { }, scene.database, getBinaryData);
  15142. }
  15143. };
  15144. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15145. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15146. return false;
  15147. }
  15148. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15149. return false;
  15150. }
  15151. this._checkDelayState();
  15152. return true;
  15153. };
  15154. Mesh.prototype.setMaterialByID = function (id) {
  15155. var materials = this.getScene().materials;
  15156. for (var index = 0; index < materials.length; index++) {
  15157. if (materials[index].id === id) {
  15158. this.material = materials[index];
  15159. return;
  15160. }
  15161. }
  15162. // Multi
  15163. var multiMaterials = this.getScene().multiMaterials;
  15164. for (index = 0; index < multiMaterials.length; index++) {
  15165. if (multiMaterials[index].id === id) {
  15166. this.material = multiMaterials[index];
  15167. return;
  15168. }
  15169. }
  15170. };
  15171. Mesh.prototype.getAnimatables = function () {
  15172. var results = [];
  15173. if (this.material) {
  15174. results.push(this.material);
  15175. }
  15176. if (this.skeleton) {
  15177. results.push(this.skeleton);
  15178. }
  15179. return results;
  15180. };
  15181. // Geometry
  15182. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15183. // Position
  15184. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15185. return;
  15186. }
  15187. this._resetPointsArrayCache();
  15188. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15189. var temp = [];
  15190. for (var index = 0; index < data.length; index += 3) {
  15191. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15192. }
  15193. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15194. // Normals
  15195. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15196. return;
  15197. }
  15198. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15199. temp = [];
  15200. for (index = 0; index < data.length; index += 3) {
  15201. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15202. }
  15203. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15204. // flip faces?
  15205. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15206. this.flipFaces();
  15207. }
  15208. };
  15209. // Will apply current transform to mesh and reset world matrix
  15210. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15211. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15212. this.scaling.copyFromFloats(1, 1, 1);
  15213. this.position.copyFromFloats(0, 0, 0);
  15214. this.rotation.copyFromFloats(0, 0, 0);
  15215. //only if quaternion is already set
  15216. if (this.rotationQuaternion) {
  15217. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15218. }
  15219. this._worldMatrix = BABYLON.Matrix.Identity();
  15220. };
  15221. // Cache
  15222. Mesh.prototype._resetPointsArrayCache = function () {
  15223. this._positions = null;
  15224. };
  15225. Mesh.prototype._generatePointsArray = function () {
  15226. if (this._positions)
  15227. return true;
  15228. this._positions = [];
  15229. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15230. if (!data) {
  15231. return false;
  15232. }
  15233. for (var index = 0; index < data.length; index += 3) {
  15234. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15235. }
  15236. return true;
  15237. };
  15238. // Clone
  15239. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15240. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15241. };
  15242. // Dispose
  15243. Mesh.prototype.dispose = function (doNotRecurse) {
  15244. if (this._geometry) {
  15245. this._geometry.releaseForMesh(this, true);
  15246. }
  15247. // Instances
  15248. if (this._worldMatricesInstancesBuffer) {
  15249. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15250. this._worldMatricesInstancesBuffer = null;
  15251. }
  15252. while (this.instances.length) {
  15253. this.instances[0].dispose();
  15254. }
  15255. _super.prototype.dispose.call(this, doNotRecurse);
  15256. };
  15257. // Geometric tools
  15258. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15259. var _this = this;
  15260. var scene = this.getScene();
  15261. var onload = function (img) {
  15262. // Getting height map data
  15263. var canvas = document.createElement("canvas");
  15264. var context = canvas.getContext("2d");
  15265. var heightMapWidth = img.width;
  15266. var heightMapHeight = img.height;
  15267. canvas.width = heightMapWidth;
  15268. canvas.height = heightMapHeight;
  15269. context.drawImage(img, 0, 0);
  15270. // Create VertexData from map data
  15271. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15272. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15273. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15274. //execute success callback, if set
  15275. if (onSuccess) {
  15276. onSuccess(_this);
  15277. }
  15278. };
  15279. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15280. };
  15281. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15282. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15283. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15284. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15285. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15286. return;
  15287. }
  15288. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15289. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15290. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15291. var position = BABYLON.Vector3.Zero();
  15292. var normal = BABYLON.Vector3.Zero();
  15293. var uv = BABYLON.Vector2.Zero();
  15294. for (var index = 0; index < positions.length; index += 3) {
  15295. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15296. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15297. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15298. // Compute height
  15299. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15300. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15301. var pos = (u + v * heightMapWidth) * 4;
  15302. var r = buffer[pos] / 255.0;
  15303. var g = buffer[pos + 1] / 255.0;
  15304. var b = buffer[pos + 2] / 255.0;
  15305. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15306. normal.normalize();
  15307. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15308. position = position.add(normal);
  15309. position.toArray(positions, index);
  15310. }
  15311. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15312. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15313. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15314. };
  15315. Mesh.prototype.convertToFlatShadedMesh = function () {
  15316. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15317. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15318. var kinds = this.getVerticesDataKinds();
  15319. var vbs = [];
  15320. var data = [];
  15321. var newdata = [];
  15322. var updatableNormals = false;
  15323. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15324. var kind = kinds[kindIndex];
  15325. var vertexBuffer = this.getVertexBuffer(kind);
  15326. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15327. updatableNormals = vertexBuffer.isUpdatable();
  15328. kinds.splice(kindIndex, 1);
  15329. kindIndex--;
  15330. continue;
  15331. }
  15332. vbs[kind] = vertexBuffer;
  15333. data[kind] = vbs[kind].getData();
  15334. newdata[kind] = [];
  15335. }
  15336. // Save previous submeshes
  15337. var previousSubmeshes = this.subMeshes.slice(0);
  15338. var indices = this.getIndices();
  15339. var totalIndices = this.getTotalIndices();
  15340. // Generating unique vertices per face
  15341. for (var index = 0; index < totalIndices; index++) {
  15342. var vertexIndex = indices[index];
  15343. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15344. kind = kinds[kindIndex];
  15345. var stride = vbs[kind].getStrideSize();
  15346. for (var offset = 0; offset < stride; offset++) {
  15347. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15348. }
  15349. }
  15350. }
  15351. // Updating faces & normal
  15352. var normals = [];
  15353. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15354. for (index = 0; index < totalIndices; index += 3) {
  15355. indices[index] = index;
  15356. indices[index + 1] = index + 1;
  15357. indices[index + 2] = index + 2;
  15358. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15359. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15360. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15361. var p1p2 = p1.subtract(p2);
  15362. var p3p2 = p3.subtract(p2);
  15363. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15364. // Store same normals for every vertex
  15365. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15366. normals.push(normal.x);
  15367. normals.push(normal.y);
  15368. normals.push(normal.z);
  15369. }
  15370. }
  15371. this.setIndices(indices);
  15372. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15373. // Updating vertex buffers
  15374. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15375. kind = kinds[kindIndex];
  15376. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15377. }
  15378. // Updating submeshes
  15379. this.releaseSubMeshes();
  15380. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15381. var previousOne = previousSubmeshes[submeshIndex];
  15382. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15383. }
  15384. this.synchronizeInstances();
  15385. };
  15386. // will inverse faces orientations, and invert normals too if specified
  15387. Mesh.prototype.flipFaces = function (flipNormals) {
  15388. if (flipNormals === void 0) { flipNormals = false; }
  15389. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15390. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15391. for (var i = 0; i < vertex_data.normals.length; i++) {
  15392. vertex_data.normals[i] *= -1;
  15393. }
  15394. }
  15395. var temp;
  15396. for (var i = 0; i < vertex_data.indices.length; i += 3) {
  15397. // reassign indices
  15398. temp = vertex_data.indices[i + 1];
  15399. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15400. vertex_data.indices[i + 2] = temp;
  15401. }
  15402. vertex_data.applyToMesh(this);
  15403. };
  15404. // Instances
  15405. Mesh.prototype.createInstance = function (name) {
  15406. return new BABYLON.InstancedMesh(name, this);
  15407. };
  15408. Mesh.prototype.synchronizeInstances = function () {
  15409. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15410. var instance = this.instances[instanceIndex];
  15411. instance._syncSubMeshes();
  15412. }
  15413. };
  15414. /**
  15415. * Simplify the mesh according to the given array of settings.
  15416. * Function will return immediately and will simplify async.
  15417. * @param settings a collection of simplification settings.
  15418. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15419. * @param type the type of simplification to run.
  15420. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15421. */
  15422. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15423. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15424. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15425. this.getScene().simplificationQueue.addTask({
  15426. settings: settings,
  15427. parallelProcessing: parallelProcessing,
  15428. mesh: this,
  15429. simplificationType: simplificationType,
  15430. successCallback: successCallback
  15431. });
  15432. };
  15433. /**
  15434. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15435. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15436. * This should be used together with the simplification to avoid disappearing triangles.
  15437. * @param successCallback an optional success callback to be called after the optimization finished.
  15438. */
  15439. Mesh.prototype.optimizeIndices = function (successCallback) {
  15440. var _this = this;
  15441. var indices = this.getIndices();
  15442. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15443. var vectorPositions = [];
  15444. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15445. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15446. }
  15447. var dupes = [];
  15448. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15449. var realPos = vectorPositions.length - 1 - iteration;
  15450. var testedPosition = vectorPositions[realPos];
  15451. for (var j = 0; j < realPos; ++j) {
  15452. var againstPosition = vectorPositions[j];
  15453. if (testedPosition.equals(againstPosition)) {
  15454. dupes[realPos] = j;
  15455. break;
  15456. }
  15457. }
  15458. }, function () {
  15459. for (var i = 0; i < indices.length; ++i) {
  15460. indices[i] = dupes[indices[i]] || indices[i];
  15461. }
  15462. //indices are now reordered
  15463. var originalSubMeshes = _this.subMeshes.slice(0);
  15464. _this.setIndices(indices);
  15465. _this.subMeshes = originalSubMeshes;
  15466. if (successCallback) {
  15467. successCallback(_this);
  15468. }
  15469. });
  15470. };
  15471. // Statics
  15472. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15473. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15474. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15475. if (ribbonInstance) {
  15476. // positionFunction : ribbon case
  15477. // only pathArray and sideOrientation parameters are taken into account for positions update
  15478. var positionFunction = function (positions) {
  15479. var minlg = pathArray[0].length;
  15480. var i = 0;
  15481. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15482. for (var si = 1; si <= ns; si++) {
  15483. for (var p = 0; p < pathArray.length; p++) {
  15484. var path = pathArray[p];
  15485. var l = path.length;
  15486. minlg = (minlg < l) ? minlg : l;
  15487. var j = 0;
  15488. while (j < minlg) {
  15489. positions[i] = path[j].x;
  15490. positions[i + 1] = path[j].y;
  15491. positions[i + 2] = path[j].z;
  15492. j++;
  15493. i += 3;
  15494. }
  15495. if (ribbonInstance._closePath) {
  15496. positions[i] = path[0].x;
  15497. positions[i + 1] = path[0].y;
  15498. positions[i + 2] = path[0].z;
  15499. i += 3;
  15500. }
  15501. }
  15502. }
  15503. };
  15504. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15505. positionFunction(positions);
  15506. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15507. if (!(ribbonInstance.areNormalsFrozen)) {
  15508. var indices = ribbonInstance.getIndices();
  15509. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15510. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15511. if (ribbonInstance._closePath) {
  15512. var indexFirst = 0;
  15513. var indexLast = 0;
  15514. for (var p = 0; p < pathArray.length; p++) {
  15515. indexFirst = ribbonInstance._idx[p] * 3;
  15516. if (p + 1 < pathArray.length) {
  15517. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15518. }
  15519. else {
  15520. indexLast = normals.length - 3;
  15521. }
  15522. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15523. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15524. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15525. normals[indexLast] = normals[indexFirst];
  15526. normals[indexLast + 1] = normals[indexFirst + 1];
  15527. normals[indexLast + 2] = normals[indexFirst + 2];
  15528. }
  15529. }
  15530. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15531. }
  15532. return ribbonInstance;
  15533. }
  15534. else {
  15535. var ribbon = new Mesh(name, scene);
  15536. ribbon.sideOrientation = sideOrientation;
  15537. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15538. if (closePath) {
  15539. ribbon._idx = vertexData._idx;
  15540. }
  15541. ribbon._closePath = closePath;
  15542. vertexData.applyToMesh(ribbon, updatable);
  15543. return ribbon;
  15544. }
  15545. };
  15546. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15547. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15548. var disc = new Mesh(name, scene);
  15549. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15550. vertexData.applyToMesh(disc, updatable);
  15551. return disc;
  15552. };
  15553. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15554. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15555. var box = new Mesh(name, scene);
  15556. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15557. vertexData.applyToMesh(box, updatable);
  15558. return box;
  15559. };
  15560. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15561. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15562. var sphere = new Mesh(name, scene);
  15563. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15564. vertexData.applyToMesh(sphere, updatable);
  15565. return sphere;
  15566. };
  15567. // Cylinder and cone
  15568. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15569. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15570. // subdivisions is a new parameter, we need to support old signature
  15571. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15572. if (scene !== undefined) {
  15573. updatable = scene;
  15574. }
  15575. scene = subdivisions;
  15576. subdivisions = 1;
  15577. }
  15578. var cylinder = new Mesh(name, scene);
  15579. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15580. vertexData.applyToMesh(cylinder, updatable);
  15581. return cylinder;
  15582. };
  15583. // Torus (Code from SharpDX.org)
  15584. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15585. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15586. var torus = new Mesh(name, scene);
  15587. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15588. vertexData.applyToMesh(torus, updatable);
  15589. return torus;
  15590. };
  15591. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15592. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15593. var torusKnot = new Mesh(name, scene);
  15594. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15595. vertexData.applyToMesh(torusKnot, updatable);
  15596. return torusKnot;
  15597. };
  15598. // Lines
  15599. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15600. if (linesInstance === void 0) { linesInstance = null; }
  15601. if (linesInstance) {
  15602. var positionFunction = function (positions) {
  15603. var i = 0;
  15604. for (var p = 0; p < points.length; p++) {
  15605. positions[i] = points[p].x;
  15606. positions[i + 1] = points[p].y;
  15607. positions[i + 2] = points[p].z;
  15608. i += 3;
  15609. }
  15610. };
  15611. linesInstance.updateMeshPositions(positionFunction, false);
  15612. return linesInstance;
  15613. }
  15614. // lines creation
  15615. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15616. var vertexData = BABYLON.VertexData.CreateLines(points);
  15617. vertexData.applyToMesh(lines, updatable);
  15618. return lines;
  15619. };
  15620. // Dashed Lines
  15621. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15622. if (linesInstance === void 0) { linesInstance = null; }
  15623. if (linesInstance) {
  15624. var positionFunction = function (positions) {
  15625. var curvect = BABYLON.Vector3.Zero();
  15626. var nbSeg = positions.length / 6;
  15627. var lg = 0;
  15628. var nb = 0;
  15629. var shft = 0;
  15630. var dashshft = 0;
  15631. var curshft = 0;
  15632. var p = 0;
  15633. var i = 0;
  15634. var j = 0;
  15635. for (i = 0; i < points.length - 1; i++) {
  15636. points[i + 1].subtractToRef(points[i], curvect);
  15637. lg += curvect.length();
  15638. }
  15639. shft = lg / nbSeg;
  15640. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15641. for (i = 0; i < points.length - 1; i++) {
  15642. points[i + 1].subtractToRef(points[i], curvect);
  15643. nb = Math.floor(curvect.length() / shft);
  15644. curvect.normalize();
  15645. j = 0;
  15646. while (j < nb && p < positions.length) {
  15647. curshft = shft * j;
  15648. positions[p] = points[i].x + curshft * curvect.x;
  15649. positions[p + 1] = points[i].y + curshft * curvect.y;
  15650. positions[p + 2] = points[i].z + curshft * curvect.z;
  15651. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15652. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15653. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15654. p += 6;
  15655. j++;
  15656. }
  15657. }
  15658. while (p < positions.length) {
  15659. positions[p] = points[i].x;
  15660. positions[p + 1] = points[i].y;
  15661. positions[p + 2] = points[i].z;
  15662. p += 3;
  15663. }
  15664. };
  15665. linesInstance.updateMeshPositions(positionFunction, false);
  15666. return linesInstance;
  15667. }
  15668. // dashed lines creation
  15669. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15670. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15671. vertexData.applyToMesh(dashedLines, updatable);
  15672. dashedLines.dashSize = dashSize;
  15673. dashedLines.gapSize = gapSize;
  15674. return dashedLines;
  15675. };
  15676. // Extrusion
  15677. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15678. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15679. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15680. scale = scale || 1;
  15681. rotation = rotation || 0;
  15682. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15683. return extruded;
  15684. };
  15685. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15686. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15687. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15688. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15689. return extrudedCustom;
  15690. };
  15691. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15692. // extrusion geometry
  15693. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15694. var tangents = path3D.getTangents();
  15695. var normals = path3D.getNormals();
  15696. var binormals = path3D.getBinormals();
  15697. var distances = path3D.getDistances();
  15698. var angle = 0;
  15699. var returnScale = function (i, distance) { return scale; };
  15700. var returnRotation = function (i, distance) { return rotation; };
  15701. var rotate = custom ? rotateFunction : returnRotation;
  15702. var scl = custom ? scaleFunction : returnScale;
  15703. var index = 0;
  15704. for (var i = 0; i < curve.length; i++) {
  15705. var shapePath = new Array();
  15706. var angleStep = rotate(i, distances[i]);
  15707. var scaleRatio = scl(i, distances[i]);
  15708. for (var p = 0; p < shape.length; p++) {
  15709. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15710. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15711. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15712. shapePath.push(rotated);
  15713. }
  15714. shapePaths[index] = shapePath;
  15715. angle += angleStep;
  15716. index++;
  15717. }
  15718. // cap
  15719. var capPath = function (shapePath) {
  15720. var pointCap = Array();
  15721. var barycenter = BABYLON.Vector3.Zero();
  15722. var i;
  15723. for (i = 0; i < shapePath.length; i++) {
  15724. barycenter.addInPlace(shapePath[i]);
  15725. }
  15726. barycenter.scaleInPlace(1 / shapePath.length);
  15727. for (i = 0; i < shapePath.length; i++) {
  15728. pointCap.push(barycenter);
  15729. }
  15730. return pointCap;
  15731. };
  15732. switch (cap) {
  15733. case Mesh.NO_CAP:
  15734. break;
  15735. case Mesh.CAP_START:
  15736. shapePaths.unshift(capPath(shapePaths[0]));
  15737. break;
  15738. case Mesh.CAP_END:
  15739. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15740. break;
  15741. case Mesh.CAP_ALL:
  15742. shapePaths.unshift(capPath(shapePaths[0]));
  15743. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15744. break;
  15745. default:
  15746. break;
  15747. }
  15748. return shapePaths;
  15749. };
  15750. if (instance) {
  15751. var path3D = (instance.path3D).update(curve);
  15752. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15753. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15754. return instance;
  15755. }
  15756. // extruded shape creation
  15757. var path3D = new BABYLON.Path3D(curve);
  15758. var newShapePaths = new Array();
  15759. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15760. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15761. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15762. extrudedGeneric.pathArray = pathArray;
  15763. extrudedGeneric.path3D = path3D;
  15764. extrudedGeneric.cap = cap;
  15765. return extrudedGeneric;
  15766. };
  15767. // Lathe
  15768. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15769. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15770. radius = radius || 1;
  15771. tessellation = tessellation || radius * 60;
  15772. var pi2 = Math.PI * 2;
  15773. var Y = BABYLON.Axis.Y;
  15774. var shapeLathe = new Array();
  15775. // first rotatable point
  15776. var i = 0;
  15777. while (shape[i].x === 0) {
  15778. i++;
  15779. }
  15780. var pt = shape[i];
  15781. for (i = 0; i < shape.length; i++) {
  15782. shapeLathe.push(shape[i].subtract(pt));
  15783. }
  15784. // circle path
  15785. var step = pi2 / tessellation;
  15786. var rotated;
  15787. var path = new Array();
  15788. ;
  15789. for (i = 0; i < tessellation; i++) {
  15790. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15791. path.push(rotated);
  15792. }
  15793. path.push(path[0]);
  15794. // extrusion
  15795. var scaleFunction = function () { return 1; };
  15796. var rotateFunction = function () { return 0; };
  15797. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15798. return lathe;
  15799. };
  15800. // Plane & ground
  15801. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15802. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15803. var plane = new Mesh(name, scene);
  15804. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15805. vertexData.applyToMesh(plane, updatable);
  15806. return plane;
  15807. };
  15808. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15809. var ground = new BABYLON.GroundMesh(name, scene);
  15810. ground._setReady(false);
  15811. ground._subdivisions = subdivisions;
  15812. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15813. vertexData.applyToMesh(ground, updatable);
  15814. ground._setReady(true);
  15815. return ground;
  15816. };
  15817. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15818. var tiledGround = new Mesh(name, scene);
  15819. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15820. vertexData.applyToMesh(tiledGround, updatable);
  15821. return tiledGround;
  15822. };
  15823. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15824. var ground = new BABYLON.GroundMesh(name, scene);
  15825. ground._subdivisions = subdivisions;
  15826. ground._setReady(false);
  15827. var onload = function (img) {
  15828. // Getting height map data
  15829. var canvas = document.createElement("canvas");
  15830. var context = canvas.getContext("2d");
  15831. var heightMapWidth = img.width;
  15832. var heightMapHeight = img.height;
  15833. canvas.width = heightMapWidth;
  15834. canvas.height = heightMapHeight;
  15835. context.drawImage(img, 0, 0);
  15836. // Create VertexData from map data
  15837. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15838. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15839. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15840. vertexData.applyToMesh(ground, updatable);
  15841. ground._setReady(true);
  15842. //execute ready callback, if set
  15843. if (onReady) {
  15844. onReady(ground);
  15845. }
  15846. };
  15847. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15848. return ground;
  15849. };
  15850. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15851. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15852. if (tubeInstance === void 0) { tubeInstance = null; }
  15853. // tube geometry
  15854. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15855. var tangents = path3D.getTangents();
  15856. var normals = path3D.getNormals();
  15857. var distances = path3D.getDistances();
  15858. var pi2 = Math.PI * 2;
  15859. var step = pi2 / tessellation;
  15860. var returnRadius = function (i, distance) { return radius; };
  15861. var radiusFunctionFinal = radiusFunction || returnRadius;
  15862. var circlePath;
  15863. var rad;
  15864. var normal;
  15865. var rotated;
  15866. var rotationMatrix;
  15867. var index = 0;
  15868. for (var i = 0; i < path.length; i++) {
  15869. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15870. circlePath = Array(); // current circle array
  15871. normal = normals[i]; // current normal
  15872. for (var t = 0; t < tessellation; t++) {
  15873. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15874. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15875. circlePath.push(rotated);
  15876. }
  15877. circlePaths[index] = circlePath;
  15878. index++;
  15879. }
  15880. // cap
  15881. var capPath = function (nbPoints, pathIndex) {
  15882. var pointCap = Array();
  15883. for (var i = 0; i < nbPoints; i++) {
  15884. pointCap.push(path[pathIndex]);
  15885. }
  15886. return pointCap;
  15887. };
  15888. switch (cap) {
  15889. case Mesh.NO_CAP:
  15890. break;
  15891. case Mesh.CAP_START:
  15892. circlePaths.unshift(capPath(tessellation + 1, 0));
  15893. break;
  15894. case Mesh.CAP_END:
  15895. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15896. break;
  15897. case Mesh.CAP_ALL:
  15898. circlePaths.unshift(capPath(tessellation + 1, 0));
  15899. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15900. break;
  15901. default:
  15902. break;
  15903. }
  15904. return circlePaths;
  15905. };
  15906. if (tubeInstance) {
  15907. var path3D = (tubeInstance.path3D).update(path);
  15908. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15909. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15910. return tubeInstance;
  15911. }
  15912. // tube creation
  15913. var path3D = new BABYLON.Path3D(path);
  15914. var newPathArray = new Array();
  15915. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15916. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15917. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15918. tube.pathArray = pathArray;
  15919. tube.path3D = path3D;
  15920. tube.tessellation = tessellation;
  15921. tube.cap = cap;
  15922. return tube;
  15923. };
  15924. // Decals
  15925. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15926. if (angle === void 0) { angle = 0; }
  15927. var indices = sourceMesh.getIndices();
  15928. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15929. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15930. // Getting correct rotation
  15931. if (!normal) {
  15932. var target = new BABYLON.Vector3(0, 0, 1);
  15933. var camera = sourceMesh.getScene().activeCamera;
  15934. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15935. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15936. }
  15937. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15938. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15939. var pitch = Math.atan2(normal.y, len);
  15940. // Matrix
  15941. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15942. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15943. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15944. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15945. var vertexData = new BABYLON.VertexData();
  15946. vertexData.indices = [];
  15947. vertexData.positions = [];
  15948. vertexData.normals = [];
  15949. vertexData.uvs = [];
  15950. var currentVertexDataIndex = 0;
  15951. var extractDecalVector3 = function (indexId) {
  15952. var vertexId = indices[indexId];
  15953. var result = new BABYLON.PositionNormalVertex();
  15954. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15955. // Send vector to decal local world
  15956. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15957. // Get normal
  15958. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15959. return result;
  15960. };
  15961. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15962. var clip = function (vertices, axis) {
  15963. if (vertices.length === 0) {
  15964. return vertices;
  15965. }
  15966. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15967. var clipVertices = function (v0, v1) {
  15968. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15969. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15970. };
  15971. var result = new Array();
  15972. for (var index = 0; index < vertices.length; index += 3) {
  15973. var v1Out;
  15974. var v2Out;
  15975. var v3Out;
  15976. var total = 0;
  15977. var nV1, nV2, nV3, nV4;
  15978. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15979. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15980. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15981. v1Out = d1 > 0;
  15982. v2Out = d2 > 0;
  15983. v3Out = d3 > 0;
  15984. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15985. switch (total) {
  15986. case 0:
  15987. result.push(vertices[index]);
  15988. result.push(vertices[index + 1]);
  15989. result.push(vertices[index + 2]);
  15990. break;
  15991. case 1:
  15992. if (v1Out) {
  15993. nV1 = vertices[index + 1];
  15994. nV2 = vertices[index + 2];
  15995. nV3 = clipVertices(vertices[index], nV1);
  15996. nV4 = clipVertices(vertices[index], nV2);
  15997. }
  15998. if (v2Out) {
  15999. nV1 = vertices[index];
  16000. nV2 = vertices[index + 2];
  16001. nV3 = clipVertices(vertices[index + 1], nV1);
  16002. nV4 = clipVertices(vertices[index + 1], nV2);
  16003. result.push(nV3);
  16004. result.push(nV2.clone());
  16005. result.push(nV1.clone());
  16006. result.push(nV2.clone());
  16007. result.push(nV3.clone());
  16008. result.push(nV4);
  16009. break;
  16010. }
  16011. if (v3Out) {
  16012. nV1 = vertices[index];
  16013. nV2 = vertices[index + 1];
  16014. nV3 = clipVertices(vertices[index + 2], nV1);
  16015. nV4 = clipVertices(vertices[index + 2], nV2);
  16016. }
  16017. result.push(nV1.clone());
  16018. result.push(nV2.clone());
  16019. result.push(nV3);
  16020. result.push(nV4);
  16021. result.push(nV3.clone());
  16022. result.push(nV2.clone());
  16023. break;
  16024. case 2:
  16025. if (!v1Out) {
  16026. nV1 = vertices[index].clone();
  16027. nV2 = clipVertices(nV1, vertices[index + 1]);
  16028. nV3 = clipVertices(nV1, vertices[index + 2]);
  16029. result.push(nV1);
  16030. result.push(nV2);
  16031. result.push(nV3);
  16032. }
  16033. if (!v2Out) {
  16034. nV1 = vertices[index + 1].clone();
  16035. nV2 = clipVertices(nV1, vertices[index + 2]);
  16036. nV3 = clipVertices(nV1, vertices[index]);
  16037. result.push(nV1);
  16038. result.push(nV2);
  16039. result.push(nV3);
  16040. }
  16041. if (!v3Out) {
  16042. nV1 = vertices[index + 2].clone();
  16043. nV2 = clipVertices(nV1, vertices[index]);
  16044. nV3 = clipVertices(nV1, vertices[index + 1]);
  16045. result.push(nV1);
  16046. result.push(nV2);
  16047. result.push(nV3);
  16048. }
  16049. break;
  16050. case 3:
  16051. break;
  16052. }
  16053. }
  16054. return result;
  16055. };
  16056. for (var index = 0; index < indices.length; index += 3) {
  16057. var faceVertices = new Array();
  16058. faceVertices.push(extractDecalVector3(index));
  16059. faceVertices.push(extractDecalVector3(index + 1));
  16060. faceVertices.push(extractDecalVector3(index + 2));
  16061. // Clip
  16062. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16063. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16064. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16065. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16066. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16067. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16068. if (faceVertices.length === 0) {
  16069. continue;
  16070. }
  16071. // Add UVs and get back to world
  16072. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  16073. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16074. var vertex = faceVertices[vIndex];
  16075. vertexData.indices.push(currentVertexDataIndex);
  16076. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16077. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16078. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16079. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16080. currentVertexDataIndex++;
  16081. }
  16082. }
  16083. // Return mesh
  16084. var decal = new Mesh(name, sourceMesh.getScene());
  16085. vertexData.applyToMesh(decal);
  16086. decal.position = position.clone();
  16087. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16088. return decal;
  16089. };
  16090. // Skeletons
  16091. /**
  16092. * Update the vertex buffers by applying transformation from the bones
  16093. * @param {skeleton} skeleton to apply
  16094. */
  16095. Mesh.prototype.applySkeleton = function (skeleton) {
  16096. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16097. return this;
  16098. }
  16099. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16100. return this;
  16101. }
  16102. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16103. return this;
  16104. }
  16105. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16106. return this;
  16107. }
  16108. if (!this._sourcePositions) {
  16109. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16110. this._sourcePositions = new Float32Array(source);
  16111. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16112. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16113. }
  16114. }
  16115. if (!this._sourceNormals) {
  16116. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16117. this._sourceNormals = new Float32Array(source);
  16118. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16119. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16120. }
  16121. }
  16122. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16123. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16124. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16125. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16126. var skeletonMatrices = skeleton.getTransformMatrices();
  16127. var tempVector3 = BABYLON.Vector3.Zero();
  16128. var finalMatrix = new BABYLON.Matrix();
  16129. var tempMatrix = new BABYLON.Matrix();
  16130. for (var index = 0; index < positionsData.length; index += 3) {
  16131. var index4 = (index / 3) * 4;
  16132. var matricesWeight0 = matricesWeightsData[index4];
  16133. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16134. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16135. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16136. if (matricesWeight0 > 0) {
  16137. var matricesIndex0 = matricesIndicesData[index4];
  16138. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16139. finalMatrix.addToSelf(tempMatrix);
  16140. }
  16141. if (matricesWeight1 > 0) {
  16142. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16143. finalMatrix.addToSelf(tempMatrix);
  16144. }
  16145. if (matricesWeight2 > 0) {
  16146. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16147. finalMatrix.addToSelf(tempMatrix);
  16148. }
  16149. if (matricesWeight3 > 0) {
  16150. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16151. finalMatrix.addToSelf(tempMatrix);
  16152. }
  16153. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16154. tempVector3.toArray(positionsData, index);
  16155. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16156. tempVector3.toArray(normalsData, index);
  16157. finalMatrix.reset();
  16158. }
  16159. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16160. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16161. return this;
  16162. };
  16163. // Tools
  16164. Mesh.MinMax = function (meshes) {
  16165. var minVector = null;
  16166. var maxVector = null;
  16167. for (var i in meshes) {
  16168. var mesh = meshes[i];
  16169. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16170. if (!minVector) {
  16171. minVector = boundingBox.minimumWorld;
  16172. maxVector = boundingBox.maximumWorld;
  16173. continue;
  16174. }
  16175. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16176. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16177. }
  16178. return {
  16179. min: minVector,
  16180. max: maxVector
  16181. };
  16182. };
  16183. Mesh.Center = function (meshesOrMinMaxVector) {
  16184. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16185. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16186. };
  16187. /**
  16188. * Merge the array of meshes into a single mesh for performance reasons.
  16189. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16190. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16191. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16192. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16193. */
  16194. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16195. if (disposeSource === void 0) { disposeSource = true; }
  16196. if (!allow32BitsIndices) {
  16197. var totalVertices = 0;
  16198. // Counting vertices
  16199. for (var index = 0; index < meshes.length; index++) {
  16200. if (meshes[index]) {
  16201. totalVertices += meshes[index].getTotalVertices();
  16202. if (totalVertices > 65536) {
  16203. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16204. return null;
  16205. }
  16206. }
  16207. }
  16208. }
  16209. // Merge
  16210. var vertexData;
  16211. var otherVertexData;
  16212. var source;
  16213. for (index = 0; index < meshes.length; index++) {
  16214. if (meshes[index]) {
  16215. meshes[index].computeWorldMatrix(true);
  16216. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16217. otherVertexData.transform(meshes[index].getWorldMatrix());
  16218. if (vertexData) {
  16219. vertexData.merge(otherVertexData);
  16220. }
  16221. else {
  16222. vertexData = otherVertexData;
  16223. source = meshes[index];
  16224. }
  16225. }
  16226. }
  16227. if (!meshSubclass) {
  16228. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16229. }
  16230. vertexData.applyToMesh(meshSubclass);
  16231. // Setting properties
  16232. meshSubclass.material = source.material;
  16233. meshSubclass.checkCollisions = source.checkCollisions;
  16234. // Cleaning
  16235. if (disposeSource) {
  16236. for (index = 0; index < meshes.length; index++) {
  16237. if (meshes[index]) {
  16238. meshes[index].dispose();
  16239. }
  16240. }
  16241. }
  16242. return meshSubclass;
  16243. };
  16244. // Consts
  16245. Mesh._FRONTSIDE = 0;
  16246. Mesh._BACKSIDE = 1;
  16247. Mesh._DOUBLESIDE = 2;
  16248. Mesh._DEFAULTSIDE = 0;
  16249. Mesh._NO_CAP = 0;
  16250. Mesh._CAP_START = 1;
  16251. Mesh._CAP_END = 2;
  16252. Mesh._CAP_ALL = 3;
  16253. return Mesh;
  16254. })(BABYLON.AbstractMesh);
  16255. BABYLON.Mesh = Mesh;
  16256. })(BABYLON || (BABYLON = {}));
  16257. var BABYLON;
  16258. (function (BABYLON) {
  16259. var SubMesh = (function () {
  16260. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16261. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16262. this.materialIndex = materialIndex;
  16263. this.verticesStart = verticesStart;
  16264. this.verticesCount = verticesCount;
  16265. this.indexStart = indexStart;
  16266. this.indexCount = indexCount;
  16267. this._renderId = 0;
  16268. this._mesh = mesh;
  16269. this._renderingMesh = renderingMesh || mesh;
  16270. mesh.subMeshes.push(this);
  16271. this._trianglePlanes = [];
  16272. this._id = mesh.subMeshes.length - 1;
  16273. if (createBoundingBox) {
  16274. this.refreshBoundingInfo();
  16275. mesh.computeWorldMatrix(true);
  16276. }
  16277. }
  16278. SubMesh.prototype.getBoundingInfo = function () {
  16279. return this._boundingInfo;
  16280. };
  16281. SubMesh.prototype.getMesh = function () {
  16282. return this._mesh;
  16283. };
  16284. SubMesh.prototype.getRenderingMesh = function () {
  16285. return this._renderingMesh;
  16286. };
  16287. SubMesh.prototype.getMaterial = function () {
  16288. var rootMaterial = this._renderingMesh.material;
  16289. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16290. var multiMaterial = rootMaterial;
  16291. return multiMaterial.getSubMaterial(this.materialIndex);
  16292. }
  16293. if (!rootMaterial) {
  16294. return this._mesh.getScene().defaultMaterial;
  16295. }
  16296. return rootMaterial;
  16297. };
  16298. // Methods
  16299. SubMesh.prototype.refreshBoundingInfo = function () {
  16300. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16301. if (!data) {
  16302. this._boundingInfo = this._mesh._boundingInfo;
  16303. return;
  16304. }
  16305. var indices = this._renderingMesh.getIndices();
  16306. var extend;
  16307. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16308. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16309. }
  16310. else {
  16311. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16312. }
  16313. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16314. };
  16315. SubMesh.prototype._checkCollision = function (collider) {
  16316. return this._boundingInfo._checkCollision(collider);
  16317. };
  16318. SubMesh.prototype.updateBoundingInfo = function (world) {
  16319. if (!this._boundingInfo) {
  16320. this.refreshBoundingInfo();
  16321. }
  16322. this._boundingInfo._update(world);
  16323. };
  16324. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16325. return this._boundingInfo.isInFrustum(frustumPlanes);
  16326. };
  16327. SubMesh.prototype.render = function (enableAlphaMode) {
  16328. this._renderingMesh.render(this, enableAlphaMode);
  16329. };
  16330. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16331. if (!this._linesIndexBuffer) {
  16332. var linesIndices = [];
  16333. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16334. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16335. }
  16336. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16337. this.linesIndexCount = linesIndices.length;
  16338. }
  16339. return this._linesIndexBuffer;
  16340. };
  16341. SubMesh.prototype.canIntersects = function (ray) {
  16342. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16343. };
  16344. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16345. var intersectInfo = null;
  16346. // Triangles test
  16347. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16348. var p0 = positions[indices[index]];
  16349. var p1 = positions[indices[index + 1]];
  16350. var p2 = positions[indices[index + 2]];
  16351. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16352. if (currentIntersectInfo) {
  16353. if (currentIntersectInfo.distance < 0) {
  16354. continue;
  16355. }
  16356. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16357. intersectInfo = currentIntersectInfo;
  16358. intersectInfo.faceId = index / 3;
  16359. if (fastCheck) {
  16360. break;
  16361. }
  16362. }
  16363. }
  16364. }
  16365. return intersectInfo;
  16366. };
  16367. // Clone
  16368. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16369. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16370. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16371. return result;
  16372. };
  16373. // Dispose
  16374. SubMesh.prototype.dispose = function () {
  16375. if (this._linesIndexBuffer) {
  16376. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16377. this._linesIndexBuffer = null;
  16378. }
  16379. // Remove from mesh
  16380. var index = this._mesh.subMeshes.indexOf(this);
  16381. this._mesh.subMeshes.splice(index, 1);
  16382. };
  16383. // Statics
  16384. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16385. var minVertexIndex = Number.MAX_VALUE;
  16386. var maxVertexIndex = -Number.MAX_VALUE;
  16387. renderingMesh = renderingMesh || mesh;
  16388. var indices = renderingMesh.getIndices();
  16389. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16390. var vertexIndex = indices[index];
  16391. if (vertexIndex < minVertexIndex)
  16392. minVertexIndex = vertexIndex;
  16393. if (vertexIndex > maxVertexIndex)
  16394. maxVertexIndex = vertexIndex;
  16395. }
  16396. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16397. };
  16398. return SubMesh;
  16399. })();
  16400. BABYLON.SubMesh = SubMesh;
  16401. })(BABYLON || (BABYLON = {}));
  16402. var BABYLON;
  16403. (function (BABYLON) {
  16404. var BaseTexture = (function () {
  16405. function BaseTexture(scene) {
  16406. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16407. this.hasAlpha = false;
  16408. this.getAlphaFromRGB = false;
  16409. this.level = 1;
  16410. this.isCube = false;
  16411. this.isRenderTarget = false;
  16412. this.animations = new Array();
  16413. this.coordinatesIndex = 0;
  16414. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16415. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16416. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16417. this.anisotropicFilteringLevel = 4;
  16418. this._scene = scene;
  16419. this._scene.textures.push(this);
  16420. }
  16421. BaseTexture.prototype.getScene = function () {
  16422. return this._scene;
  16423. };
  16424. BaseTexture.prototype.getTextureMatrix = function () {
  16425. return null;
  16426. };
  16427. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16428. return null;
  16429. };
  16430. BaseTexture.prototype.getInternalTexture = function () {
  16431. return this._texture;
  16432. };
  16433. BaseTexture.prototype.isReady = function () {
  16434. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16435. return true;
  16436. }
  16437. if (this._texture) {
  16438. return this._texture.isReady;
  16439. }
  16440. return false;
  16441. };
  16442. BaseTexture.prototype.getSize = function () {
  16443. if (this._texture._width) {
  16444. return { width: this._texture._width, height: this._texture._height };
  16445. }
  16446. if (this._texture._size) {
  16447. return { width: this._texture._size, height: this._texture._size };
  16448. }
  16449. return { width: 0, height: 0 };
  16450. };
  16451. BaseTexture.prototype.getBaseSize = function () {
  16452. if (!this.isReady())
  16453. return { width: 0, height: 0 };
  16454. if (this._texture._size) {
  16455. return { width: this._texture._size, height: this._texture._size };
  16456. }
  16457. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16458. };
  16459. BaseTexture.prototype.scale = function (ratio) {
  16460. };
  16461. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16462. get: function () {
  16463. return false;
  16464. },
  16465. enumerable: true,
  16466. configurable: true
  16467. });
  16468. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16469. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16470. for (var index = 0; index < texturesCache.length; index++) {
  16471. var texturesCacheEntry = texturesCache[index];
  16472. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16473. texturesCache.splice(index, 1);
  16474. return;
  16475. }
  16476. }
  16477. };
  16478. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16479. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16480. for (var index = 0; index < texturesCache.length; index++) {
  16481. var texturesCacheEntry = texturesCache[index];
  16482. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16483. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16484. texturesCacheEntry.references++;
  16485. return texturesCacheEntry;
  16486. }
  16487. }
  16488. }
  16489. return null;
  16490. };
  16491. BaseTexture.prototype.delayLoad = function () {
  16492. };
  16493. BaseTexture.prototype.releaseInternalTexture = function () {
  16494. if (!this._texture) {
  16495. return;
  16496. }
  16497. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16498. this._texture.references--;
  16499. // Final reference ?
  16500. if (this._texture.references === 0) {
  16501. var index = texturesCache.indexOf(this._texture);
  16502. texturesCache.splice(index, 1);
  16503. this._scene.getEngine()._releaseTexture(this._texture);
  16504. delete this._texture;
  16505. }
  16506. };
  16507. BaseTexture.prototype.clone = function () {
  16508. return null;
  16509. };
  16510. BaseTexture.prototype.dispose = function () {
  16511. // Remove from scene
  16512. var index = this._scene.textures.indexOf(this);
  16513. if (index >= 0) {
  16514. this._scene.textures.splice(index, 1);
  16515. }
  16516. if (this._texture === undefined) {
  16517. return;
  16518. }
  16519. this.releaseInternalTexture();
  16520. // Callback
  16521. if (this.onDispose) {
  16522. this.onDispose();
  16523. }
  16524. };
  16525. return BaseTexture;
  16526. })();
  16527. BABYLON.BaseTexture = BaseTexture;
  16528. })(BABYLON || (BABYLON = {}));
  16529. var BABYLON;
  16530. (function (BABYLON) {
  16531. var Texture = (function (_super) {
  16532. __extends(Texture, _super);
  16533. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16534. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16535. if (onLoad === void 0) { onLoad = null; }
  16536. if (onError === void 0) { onError = null; }
  16537. if (buffer === void 0) { buffer = null; }
  16538. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16539. _super.call(this, scene);
  16540. this.uOffset = 0;
  16541. this.vOffset = 0;
  16542. this.uScale = 1.0;
  16543. this.vScale = 1.0;
  16544. this.uAng = 0;
  16545. this.vAng = 0;
  16546. this.wAng = 0;
  16547. this.name = url;
  16548. this.url = url;
  16549. this._noMipmap = noMipmap;
  16550. this._invertY = invertY;
  16551. this._samplingMode = samplingMode;
  16552. this._buffer = buffer;
  16553. this._deleteBuffer = deleteBuffer;
  16554. if (!url) {
  16555. return;
  16556. }
  16557. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16558. if (!this._texture) {
  16559. if (!scene.useDelayedTextureLoading) {
  16560. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16561. if (deleteBuffer) {
  16562. delete this._buffer;
  16563. }
  16564. }
  16565. else {
  16566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16567. }
  16568. }
  16569. else {
  16570. BABYLON.Tools.SetImmediate(function () {
  16571. if (onLoad) {
  16572. onLoad();
  16573. }
  16574. });
  16575. }
  16576. }
  16577. Texture.prototype.delayLoad = function () {
  16578. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16579. return;
  16580. }
  16581. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16582. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16583. if (!this._texture) {
  16584. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16585. if (this._deleteBuffer) {
  16586. delete this._buffer;
  16587. }
  16588. }
  16589. };
  16590. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16591. if (!this._texture) {
  16592. return;
  16593. }
  16594. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16595. };
  16596. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16597. x -= this.uOffset + 0.5;
  16598. y -= this.vOffset + 0.5;
  16599. z -= 0.5;
  16600. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16601. t.x *= this.uScale;
  16602. t.y *= this.vScale;
  16603. t.x += 0.5;
  16604. t.y += 0.5;
  16605. t.z += 0.5;
  16606. };
  16607. Texture.prototype.getTextureMatrix = function () {
  16608. if (this.uOffset === this._cachedUOffset &&
  16609. this.vOffset === this._cachedVOffset &&
  16610. this.uScale === this._cachedUScale &&
  16611. this.vScale === this._cachedVScale &&
  16612. this.uAng === this._cachedUAng &&
  16613. this.vAng === this._cachedVAng &&
  16614. this.wAng === this._cachedWAng) {
  16615. return this._cachedTextureMatrix;
  16616. }
  16617. this._cachedUOffset = this.uOffset;
  16618. this._cachedVOffset = this.vOffset;
  16619. this._cachedUScale = this.uScale;
  16620. this._cachedVScale = this.vScale;
  16621. this._cachedUAng = this.uAng;
  16622. this._cachedVAng = this.vAng;
  16623. this._cachedWAng = this.wAng;
  16624. if (!this._cachedTextureMatrix) {
  16625. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16626. this._rowGenerationMatrix = new BABYLON.Matrix();
  16627. this._t0 = BABYLON.Vector3.Zero();
  16628. this._t1 = BABYLON.Vector3.Zero();
  16629. this._t2 = BABYLON.Vector3.Zero();
  16630. }
  16631. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16632. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16633. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16634. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16635. this._t1.subtractInPlace(this._t0);
  16636. this._t2.subtractInPlace(this._t0);
  16637. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16638. this._cachedTextureMatrix.m[0] = this._t1.x;
  16639. this._cachedTextureMatrix.m[1] = this._t1.y;
  16640. this._cachedTextureMatrix.m[2] = this._t1.z;
  16641. this._cachedTextureMatrix.m[4] = this._t2.x;
  16642. this._cachedTextureMatrix.m[5] = this._t2.y;
  16643. this._cachedTextureMatrix.m[6] = this._t2.z;
  16644. this._cachedTextureMatrix.m[8] = this._t0.x;
  16645. this._cachedTextureMatrix.m[9] = this._t0.y;
  16646. this._cachedTextureMatrix.m[10] = this._t0.z;
  16647. return this._cachedTextureMatrix;
  16648. };
  16649. Texture.prototype.getReflectionTextureMatrix = function () {
  16650. if (this.uOffset === this._cachedUOffset &&
  16651. this.vOffset === this._cachedVOffset &&
  16652. this.uScale === this._cachedUScale &&
  16653. this.vScale === this._cachedVScale &&
  16654. this.coordinatesMode === this._cachedCoordinatesMode) {
  16655. return this._cachedTextureMatrix;
  16656. }
  16657. if (!this._cachedTextureMatrix) {
  16658. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16659. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16660. }
  16661. this._cachedCoordinatesMode = this.coordinatesMode;
  16662. switch (this.coordinatesMode) {
  16663. case Texture.SPHERICAL_MODE:
  16664. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16665. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16666. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16667. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16668. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16669. break;
  16670. case Texture.PLANAR_MODE:
  16671. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16672. this._cachedTextureMatrix[0] = this.uScale;
  16673. this._cachedTextureMatrix[5] = this.vScale;
  16674. this._cachedTextureMatrix[12] = this.uOffset;
  16675. this._cachedTextureMatrix[13] = this.vOffset;
  16676. break;
  16677. case Texture.PROJECTION_MODE:
  16678. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16679. this._projectionModeMatrix.m[0] = 0.5;
  16680. this._projectionModeMatrix.m[5] = -0.5;
  16681. this._projectionModeMatrix.m[10] = 0.0;
  16682. this._projectionModeMatrix.m[12] = 0.5;
  16683. this._projectionModeMatrix.m[13] = 0.5;
  16684. this._projectionModeMatrix.m[14] = 1.0;
  16685. this._projectionModeMatrix.m[15] = 1.0;
  16686. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16687. break;
  16688. default:
  16689. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16690. break;
  16691. }
  16692. return this._cachedTextureMatrix;
  16693. };
  16694. Texture.prototype.clone = function () {
  16695. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16696. // Base texture
  16697. newTexture.hasAlpha = this.hasAlpha;
  16698. newTexture.level = this.level;
  16699. newTexture.wrapU = this.wrapU;
  16700. newTexture.wrapV = this.wrapV;
  16701. newTexture.coordinatesIndex = this.coordinatesIndex;
  16702. newTexture.coordinatesMode = this.coordinatesMode;
  16703. // Texture
  16704. newTexture.uOffset = this.uOffset;
  16705. newTexture.vOffset = this.vOffset;
  16706. newTexture.uScale = this.uScale;
  16707. newTexture.vScale = this.vScale;
  16708. newTexture.uAng = this.uAng;
  16709. newTexture.vAng = this.vAng;
  16710. newTexture.wAng = this.wAng;
  16711. return newTexture;
  16712. };
  16713. // Statics
  16714. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16715. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16716. if (onLoad === void 0) { onLoad = null; }
  16717. if (onError === void 0) { onError = null; }
  16718. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16719. };
  16720. // Constants
  16721. Texture.NEAREST_SAMPLINGMODE = 1;
  16722. Texture.BILINEAR_SAMPLINGMODE = 2;
  16723. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16724. Texture.EXPLICIT_MODE = 0;
  16725. Texture.SPHERICAL_MODE = 1;
  16726. Texture.PLANAR_MODE = 2;
  16727. Texture.CUBIC_MODE = 3;
  16728. Texture.PROJECTION_MODE = 4;
  16729. Texture.SKYBOX_MODE = 5;
  16730. Texture.CLAMP_ADDRESSMODE = 0;
  16731. Texture.WRAP_ADDRESSMODE = 1;
  16732. Texture.MIRROR_ADDRESSMODE = 2;
  16733. return Texture;
  16734. })(BABYLON.BaseTexture);
  16735. BABYLON.Texture = Texture;
  16736. })(BABYLON || (BABYLON = {}));
  16737. var BABYLON;
  16738. (function (BABYLON) {
  16739. var CubeTexture = (function (_super) {
  16740. __extends(CubeTexture, _super);
  16741. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16742. _super.call(this, scene);
  16743. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16744. this.name = rootUrl;
  16745. this.url = rootUrl;
  16746. this._noMipmap = noMipmap;
  16747. this.hasAlpha = false;
  16748. this._texture = this._getFromCache(rootUrl, noMipmap);
  16749. if (!extensions) {
  16750. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16751. }
  16752. this._extensions = extensions;
  16753. if (!this._texture) {
  16754. if (!scene.useDelayedTextureLoading) {
  16755. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16756. }
  16757. else {
  16758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16759. }
  16760. }
  16761. this.isCube = true;
  16762. this._textureMatrix = BABYLON.Matrix.Identity();
  16763. }
  16764. CubeTexture.prototype.clone = function () {
  16765. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16766. // Base texture
  16767. newTexture.level = this.level;
  16768. newTexture.wrapU = this.wrapU;
  16769. newTexture.wrapV = this.wrapV;
  16770. newTexture.coordinatesIndex = this.coordinatesIndex;
  16771. newTexture.coordinatesMode = this.coordinatesMode;
  16772. return newTexture;
  16773. };
  16774. // Methods
  16775. CubeTexture.prototype.delayLoad = function () {
  16776. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16777. return;
  16778. }
  16779. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16780. this._texture = this._getFromCache(this.url, this._noMipmap);
  16781. if (!this._texture) {
  16782. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16783. }
  16784. };
  16785. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16786. return this._textureMatrix;
  16787. };
  16788. return CubeTexture;
  16789. })(BABYLON.BaseTexture);
  16790. BABYLON.CubeTexture = CubeTexture;
  16791. })(BABYLON || (BABYLON = {}));
  16792. var BABYLON;
  16793. (function (BABYLON) {
  16794. var RenderTargetTexture = (function (_super) {
  16795. __extends(RenderTargetTexture, _super);
  16796. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16797. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16798. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16799. _super.call(this, null, scene, !generateMipMaps);
  16800. this.renderList = new Array();
  16801. this.renderParticles = true;
  16802. this.renderSprites = false;
  16803. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16804. this._currentRefreshId = -1;
  16805. this._refreshRate = 1;
  16806. this.name = name;
  16807. this.isRenderTarget = true;
  16808. this._size = size;
  16809. this._generateMipMaps = generateMipMaps;
  16810. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16811. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16812. // Rendering groups
  16813. this._renderingManager = new BABYLON.RenderingManager(scene);
  16814. }
  16815. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16816. this._currentRefreshId = -1;
  16817. };
  16818. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16819. get: function () {
  16820. return this._refreshRate;
  16821. },
  16822. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16823. set: function (value) {
  16824. this._refreshRate = value;
  16825. this.resetRefreshCounter();
  16826. },
  16827. enumerable: true,
  16828. configurable: true
  16829. });
  16830. RenderTargetTexture.prototype._shouldRender = function () {
  16831. if (this._currentRefreshId === -1) {
  16832. this._currentRefreshId = 1;
  16833. return true;
  16834. }
  16835. if (this.refreshRate === this._currentRefreshId) {
  16836. this._currentRefreshId = 1;
  16837. return true;
  16838. }
  16839. this._currentRefreshId++;
  16840. return false;
  16841. };
  16842. RenderTargetTexture.prototype.isReady = function () {
  16843. if (!this.getScene().renderTargetsEnabled) {
  16844. return false;
  16845. }
  16846. return _super.prototype.isReady.call(this);
  16847. };
  16848. RenderTargetTexture.prototype.getRenderSize = function () {
  16849. return this._size;
  16850. };
  16851. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16852. get: function () {
  16853. return true;
  16854. },
  16855. enumerable: true,
  16856. configurable: true
  16857. });
  16858. RenderTargetTexture.prototype.scale = function (ratio) {
  16859. var newSize = this._size * ratio;
  16860. this.resize(newSize, this._generateMipMaps);
  16861. };
  16862. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16863. this.releaseInternalTexture();
  16864. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16865. };
  16866. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16867. var scene = this.getScene();
  16868. var engine = scene.getEngine();
  16869. if (this._waitingRenderList) {
  16870. this.renderList = [];
  16871. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16872. var id = this._waitingRenderList[index];
  16873. this.renderList.push(scene.getMeshByID(id));
  16874. }
  16875. delete this._waitingRenderList;
  16876. }
  16877. if (this.renderList && this.renderList.length === 0) {
  16878. return;
  16879. }
  16880. // Bind
  16881. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16882. engine.bindFramebuffer(this._texture);
  16883. }
  16884. this._renderingManager.reset();
  16885. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16886. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16887. var mesh = currentRenderList[meshIndex];
  16888. if (mesh) {
  16889. if (!mesh.isReady()) {
  16890. // Reset _currentRefreshId
  16891. this.resetRefreshCounter();
  16892. continue;
  16893. }
  16894. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16895. mesh._activate(scene.getRenderId());
  16896. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16897. var subMesh = mesh.subMeshes[subIndex];
  16898. scene._activeIndices += subMesh.indexCount;
  16899. this._renderingManager.dispatch(subMesh);
  16900. }
  16901. }
  16902. }
  16903. }
  16904. if (this.onBeforeRender) {
  16905. this.onBeforeRender();
  16906. }
  16907. // Clear
  16908. if (this.onClear) {
  16909. this.onClear(engine);
  16910. }
  16911. else {
  16912. engine.clear(scene.clearColor, true, true);
  16913. }
  16914. if (!this._doNotChangeAspectRatio) {
  16915. scene.updateTransformMatrix(true);
  16916. }
  16917. // Render
  16918. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16919. if (useCameraPostProcess) {
  16920. scene.postProcessManager._finalizeFrame(false, this._texture);
  16921. }
  16922. if (!this._doNotChangeAspectRatio) {
  16923. scene.updateTransformMatrix(true);
  16924. }
  16925. if (this.onAfterRender) {
  16926. this.onAfterRender();
  16927. }
  16928. // Dump ?
  16929. if (dumpForDebug) {
  16930. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16931. }
  16932. // Unbind
  16933. engine.unBindFramebuffer(this._texture);
  16934. if (this.onAfterUnbind) {
  16935. this.onAfterUnbind();
  16936. }
  16937. };
  16938. RenderTargetTexture.prototype.clone = function () {
  16939. var textureSize = this.getSize();
  16940. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16941. // Base texture
  16942. newTexture.hasAlpha = this.hasAlpha;
  16943. newTexture.level = this.level;
  16944. // RenderTarget Texture
  16945. newTexture.coordinatesMode = this.coordinatesMode;
  16946. newTexture.renderList = this.renderList.slice(0);
  16947. return newTexture;
  16948. };
  16949. return RenderTargetTexture;
  16950. })(BABYLON.Texture);
  16951. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16952. })(BABYLON || (BABYLON = {}));
  16953. var BABYLON;
  16954. (function (BABYLON) {
  16955. var ProceduralTexture = (function (_super) {
  16956. __extends(ProceduralTexture, _super);
  16957. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16958. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16959. _super.call(this, null, scene, !generateMipMaps);
  16960. this._currentRefreshId = -1;
  16961. this._refreshRate = 1;
  16962. this._vertexDeclaration = [2];
  16963. this._vertexStrideSize = 2 * 4;
  16964. this._uniforms = new Array();
  16965. this._samplers = new Array();
  16966. this._textures = new Array();
  16967. this._floats = new Array();
  16968. this._floatsArrays = {};
  16969. this._colors3 = new Array();
  16970. this._colors4 = new Array();
  16971. this._vectors2 = new Array();
  16972. this._vectors3 = new Array();
  16973. this._matrices = new Array();
  16974. this._fallbackTextureUsed = false;
  16975. scene._proceduralTextures.push(this);
  16976. this.name = name;
  16977. this.isRenderTarget = true;
  16978. this._size = size;
  16979. this._generateMipMaps = generateMipMaps;
  16980. this.setFragment(fragment);
  16981. this._fallbackTexture = fallbackTexture;
  16982. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16983. // VBO
  16984. var vertices = [];
  16985. vertices.push(1, 1);
  16986. vertices.push(-1, 1);
  16987. vertices.push(-1, -1);
  16988. vertices.push(1, -1);
  16989. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16990. // Indices
  16991. var indices = [];
  16992. indices.push(0);
  16993. indices.push(1);
  16994. indices.push(2);
  16995. indices.push(0);
  16996. indices.push(2);
  16997. indices.push(3);
  16998. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16999. }
  17000. ProceduralTexture.prototype.reset = function () {
  17001. if (this._effect === undefined) {
  17002. return;
  17003. }
  17004. var engine = this.getScene().getEngine();
  17005. engine._releaseEffect(this._effect);
  17006. };
  17007. ProceduralTexture.prototype.isReady = function () {
  17008. var _this = this;
  17009. var engine = this.getScene().getEngine();
  17010. var shaders;
  17011. if (!this._fragment) {
  17012. return false;
  17013. }
  17014. if (this._fallbackTextureUsed) {
  17015. return true;
  17016. }
  17017. if (this._fragment.fragmentElement !== undefined) {
  17018. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17019. }
  17020. else {
  17021. shaders = { vertex: "procedural", fragment: this._fragment };
  17022. }
  17023. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17024. _this.releaseInternalTexture();
  17025. if (_this._fallbackTexture) {
  17026. _this._texture = _this._fallbackTexture._texture;
  17027. _this._texture.references++;
  17028. }
  17029. _this._fallbackTextureUsed = true;
  17030. });
  17031. return this._effect.isReady();
  17032. };
  17033. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17034. this._currentRefreshId = -1;
  17035. };
  17036. ProceduralTexture.prototype.setFragment = function (fragment) {
  17037. this._fragment = fragment;
  17038. };
  17039. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17040. get: function () {
  17041. return this._refreshRate;
  17042. },
  17043. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17044. set: function (value) {
  17045. this._refreshRate = value;
  17046. this.resetRefreshCounter();
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. ProceduralTexture.prototype._shouldRender = function () {
  17052. if (!this.isReady() || !this._texture) {
  17053. return false;
  17054. }
  17055. if (this._fallbackTextureUsed) {
  17056. return false;
  17057. }
  17058. if (this._currentRefreshId === -1) {
  17059. this._currentRefreshId = 1;
  17060. return true;
  17061. }
  17062. if (this.refreshRate === this._currentRefreshId) {
  17063. this._currentRefreshId = 1;
  17064. return true;
  17065. }
  17066. this._currentRefreshId++;
  17067. return false;
  17068. };
  17069. ProceduralTexture.prototype.getRenderSize = function () {
  17070. return this._size;
  17071. };
  17072. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17073. if (this._fallbackTextureUsed) {
  17074. return;
  17075. }
  17076. this.releaseInternalTexture();
  17077. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17078. };
  17079. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17080. if (this._uniforms.indexOf(uniformName) === -1) {
  17081. this._uniforms.push(uniformName);
  17082. }
  17083. };
  17084. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17085. if (this._samplers.indexOf(name) === -1) {
  17086. this._samplers.push(name);
  17087. }
  17088. this._textures[name] = texture;
  17089. return this;
  17090. };
  17091. ProceduralTexture.prototype.setFloat = function (name, value) {
  17092. this._checkUniform(name);
  17093. this._floats[name] = value;
  17094. return this;
  17095. };
  17096. ProceduralTexture.prototype.setFloats = function (name, value) {
  17097. this._checkUniform(name);
  17098. this._floatsArrays[name] = value;
  17099. return this;
  17100. };
  17101. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17102. this._checkUniform(name);
  17103. this._colors3[name] = value;
  17104. return this;
  17105. };
  17106. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17107. this._checkUniform(name);
  17108. this._colors4[name] = value;
  17109. return this;
  17110. };
  17111. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17112. this._checkUniform(name);
  17113. this._vectors2[name] = value;
  17114. return this;
  17115. };
  17116. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17117. this._checkUniform(name);
  17118. this._vectors3[name] = value;
  17119. return this;
  17120. };
  17121. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17122. this._checkUniform(name);
  17123. this._matrices[name] = value;
  17124. return this;
  17125. };
  17126. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17127. var scene = this.getScene();
  17128. var engine = scene.getEngine();
  17129. engine.bindFramebuffer(this._texture);
  17130. // Clear
  17131. engine.clear(scene.clearColor, true, true);
  17132. // Render
  17133. engine.enableEffect(this._effect);
  17134. engine.setState(false);
  17135. // Texture
  17136. for (var name in this._textures) {
  17137. this._effect.setTexture(name, this._textures[name]);
  17138. }
  17139. // Float
  17140. for (name in this._floats) {
  17141. this._effect.setFloat(name, this._floats[name]);
  17142. }
  17143. // Floats
  17144. for (name in this._floatsArrays) {
  17145. this._effect.setArray(name, this._floatsArrays[name]);
  17146. }
  17147. // Color3
  17148. for (name in this._colors3) {
  17149. this._effect.setColor3(name, this._colors3[name]);
  17150. }
  17151. // Color4
  17152. for (name in this._colors4) {
  17153. var color = this._colors4[name];
  17154. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17155. }
  17156. // Vector2
  17157. for (name in this._vectors2) {
  17158. this._effect.setVector2(name, this._vectors2[name]);
  17159. }
  17160. // Vector3
  17161. for (name in this._vectors3) {
  17162. this._effect.setVector3(name, this._vectors3[name]);
  17163. }
  17164. // Matrix
  17165. for (name in this._matrices) {
  17166. this._effect.setMatrix(name, this._matrices[name]);
  17167. }
  17168. // VBOs
  17169. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17170. // Draw order
  17171. engine.draw(true, 0, 6);
  17172. // Unbind
  17173. engine.unBindFramebuffer(this._texture);
  17174. };
  17175. ProceduralTexture.prototype.clone = function () {
  17176. var textureSize = this.getSize();
  17177. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17178. // Base texture
  17179. newTexture.hasAlpha = this.hasAlpha;
  17180. newTexture.level = this.level;
  17181. // RenderTarget Texture
  17182. newTexture.coordinatesMode = this.coordinatesMode;
  17183. return newTexture;
  17184. };
  17185. ProceduralTexture.prototype.dispose = function () {
  17186. var index = this.getScene()._proceduralTextures.indexOf(this);
  17187. if (index >= 0) {
  17188. this.getScene()._proceduralTextures.splice(index, 1);
  17189. }
  17190. _super.prototype.dispose.call(this);
  17191. };
  17192. return ProceduralTexture;
  17193. })(BABYLON.Texture);
  17194. BABYLON.ProceduralTexture = ProceduralTexture;
  17195. })(BABYLON || (BABYLON = {}));
  17196. var BABYLON;
  17197. (function (BABYLON) {
  17198. var MirrorTexture = (function (_super) {
  17199. __extends(MirrorTexture, _super);
  17200. function MirrorTexture(name, size, scene, generateMipMaps) {
  17201. var _this = this;
  17202. _super.call(this, name, size, scene, generateMipMaps, true);
  17203. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17204. this._transformMatrix = BABYLON.Matrix.Zero();
  17205. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17206. this.onBeforeRender = function () {
  17207. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17208. _this._savedViewMatrix = scene.getViewMatrix();
  17209. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17210. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17211. scene.clipPlane = _this.mirrorPlane;
  17212. scene.getEngine().cullBackFaces = false;
  17213. };
  17214. this.onAfterRender = function () {
  17215. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17216. scene.getEngine().cullBackFaces = true;
  17217. delete scene.clipPlane;
  17218. };
  17219. }
  17220. MirrorTexture.prototype.clone = function () {
  17221. var textureSize = this.getSize();
  17222. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17223. // Base texture
  17224. newTexture.hasAlpha = this.hasAlpha;
  17225. newTexture.level = this.level;
  17226. // Mirror Texture
  17227. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17228. newTexture.renderList = this.renderList.slice(0);
  17229. return newTexture;
  17230. };
  17231. return MirrorTexture;
  17232. })(BABYLON.RenderTargetTexture);
  17233. BABYLON.MirrorTexture = MirrorTexture;
  17234. })(BABYLON || (BABYLON = {}));
  17235. var BABYLON;
  17236. (function (BABYLON) {
  17237. var DynamicTexture = (function (_super) {
  17238. __extends(DynamicTexture, _super);
  17239. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17240. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17241. _super.call(this, null, scene, !generateMipMaps);
  17242. this.name = name;
  17243. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17244. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17245. this._generateMipMaps = generateMipMaps;
  17246. if (options.getContext) {
  17247. this._canvas = options;
  17248. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17249. }
  17250. else {
  17251. this._canvas = document.createElement("canvas");
  17252. if (options.width) {
  17253. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17254. }
  17255. else {
  17256. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17257. }
  17258. }
  17259. var textureSize = this.getSize();
  17260. this._canvas.width = textureSize.width;
  17261. this._canvas.height = textureSize.height;
  17262. this._context = this._canvas.getContext("2d");
  17263. }
  17264. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17265. get: function () {
  17266. return true;
  17267. },
  17268. enumerable: true,
  17269. configurable: true
  17270. });
  17271. DynamicTexture.prototype.scale = function (ratio) {
  17272. var textureSize = this.getSize();
  17273. textureSize.width *= ratio;
  17274. textureSize.height *= ratio;
  17275. this._canvas.width = textureSize.width;
  17276. this._canvas.height = textureSize.height;
  17277. this.releaseInternalTexture();
  17278. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17279. };
  17280. DynamicTexture.prototype.getContext = function () {
  17281. return this._context;
  17282. };
  17283. DynamicTexture.prototype.clear = function () {
  17284. var size = this.getSize();
  17285. this._context.fillRect(0, 0, size.width, size.height);
  17286. };
  17287. DynamicTexture.prototype.update = function (invertY) {
  17288. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17289. };
  17290. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17291. if (update === void 0) { update = true; }
  17292. var size = this.getSize();
  17293. if (clearColor) {
  17294. this._context.fillStyle = clearColor;
  17295. this._context.fillRect(0, 0, size.width, size.height);
  17296. }
  17297. this._context.font = font;
  17298. if (x === null) {
  17299. var textSize = this._context.measureText(text);
  17300. x = (size.width - textSize.width) / 2;
  17301. }
  17302. this._context.fillStyle = color;
  17303. this._context.fillText(text, x, y);
  17304. if (update) {
  17305. this.update(invertY);
  17306. }
  17307. };
  17308. DynamicTexture.prototype.clone = function () {
  17309. var textureSize = this.getSize();
  17310. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17311. // Base texture
  17312. newTexture.hasAlpha = this.hasAlpha;
  17313. newTexture.level = this.level;
  17314. // Dynamic Texture
  17315. newTexture.wrapU = this.wrapU;
  17316. newTexture.wrapV = this.wrapV;
  17317. return newTexture;
  17318. };
  17319. return DynamicTexture;
  17320. })(BABYLON.Texture);
  17321. BABYLON.DynamicTexture = DynamicTexture;
  17322. })(BABYLON || (BABYLON = {}));
  17323. var BABYLON;
  17324. (function (BABYLON) {
  17325. var VideoTexture = (function (_super) {
  17326. __extends(VideoTexture, _super);
  17327. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17328. var _this = this;
  17329. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17330. if (invertY === void 0) { invertY = false; }
  17331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17332. _super.call(this, null, scene, !generateMipMaps, invertY);
  17333. this._autoLaunch = true;
  17334. this.name = name;
  17335. this.video = document.createElement("video");
  17336. this.video.autoplay = false;
  17337. this.video.loop = true;
  17338. this.video.addEventListener("canplaythrough", function () {
  17339. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17340. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17341. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17342. }
  17343. else {
  17344. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17345. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17346. generateMipMaps = false;
  17347. }
  17348. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17349. _this._texture.isReady = true;
  17350. });
  17351. urls.forEach(function (url) {
  17352. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17353. var source = document.createElement("source");
  17354. source.src = url;
  17355. _this.video.appendChild(source);
  17356. });
  17357. this._lastUpdate = BABYLON.Tools.Now;
  17358. }
  17359. VideoTexture.prototype.update = function () {
  17360. if (this._autoLaunch) {
  17361. this._autoLaunch = false;
  17362. this.video.play();
  17363. }
  17364. var now = BABYLON.Tools.Now;
  17365. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17366. return false;
  17367. }
  17368. this._lastUpdate = now;
  17369. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17370. return true;
  17371. };
  17372. return VideoTexture;
  17373. })(BABYLON.Texture);
  17374. BABYLON.VideoTexture = VideoTexture;
  17375. })(BABYLON || (BABYLON = {}));
  17376. var BABYLON;
  17377. (function (BABYLON) {
  17378. var CustomProceduralTexture = (function (_super) {
  17379. __extends(CustomProceduralTexture, _super);
  17380. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17381. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17382. this._animate = true;
  17383. this._time = 0;
  17384. this._texturePath = texturePath;
  17385. //Try to load json
  17386. this.loadJson(texturePath);
  17387. this.refreshRate = 1;
  17388. }
  17389. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17390. var _this = this;
  17391. var that = this;
  17392. function noConfigFile() {
  17393. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17394. try {
  17395. that.setFragment(that._texturePath);
  17396. }
  17397. catch (ex) {
  17398. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17399. }
  17400. }
  17401. var configFileUrl = jsonUrl + "/config.json";
  17402. var xhr = new XMLHttpRequest();
  17403. xhr.open("GET", configFileUrl, true);
  17404. xhr.addEventListener("load", function () {
  17405. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17406. try {
  17407. _this._config = JSON.parse(xhr.response);
  17408. _this.updateShaderUniforms();
  17409. _this.updateTextures();
  17410. _this.setFragment(_this._texturePath + "/custom");
  17411. _this._animate = _this._config.animate;
  17412. _this.refreshRate = _this._config.refreshrate;
  17413. }
  17414. catch (ex) {
  17415. noConfigFile();
  17416. }
  17417. }
  17418. else {
  17419. noConfigFile();
  17420. }
  17421. }, false);
  17422. xhr.addEventListener("error", function () {
  17423. noConfigFile();
  17424. }, false);
  17425. try {
  17426. xhr.send();
  17427. }
  17428. catch (ex) {
  17429. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17430. }
  17431. };
  17432. CustomProceduralTexture.prototype.isReady = function () {
  17433. if (!_super.prototype.isReady.call(this)) {
  17434. return false;
  17435. }
  17436. for (var name in this._textures) {
  17437. var texture = this._textures[name];
  17438. if (!texture.isReady()) {
  17439. return false;
  17440. }
  17441. }
  17442. return true;
  17443. };
  17444. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17445. if (this._animate) {
  17446. this._time += this.getScene().getAnimationRatio() * 0.03;
  17447. this.updateShaderUniforms();
  17448. }
  17449. _super.prototype.render.call(this, useCameraPostProcess);
  17450. };
  17451. CustomProceduralTexture.prototype.updateTextures = function () {
  17452. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17453. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17454. }
  17455. };
  17456. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17457. if (this._config) {
  17458. for (var j = 0; j < this._config.uniforms.length; j++) {
  17459. var uniform = this._config.uniforms[j];
  17460. switch (uniform.type) {
  17461. case "float":
  17462. this.setFloat(uniform.name, uniform.value);
  17463. break;
  17464. case "color3":
  17465. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17466. break;
  17467. case "color4":
  17468. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17469. break;
  17470. case "vector2":
  17471. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17472. break;
  17473. case "vector3":
  17474. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17475. break;
  17476. }
  17477. }
  17478. }
  17479. this.setFloat("time", this._time);
  17480. };
  17481. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17482. get: function () {
  17483. return this._animate;
  17484. },
  17485. set: function (value) {
  17486. this._animate = value;
  17487. },
  17488. enumerable: true,
  17489. configurable: true
  17490. });
  17491. return CustomProceduralTexture;
  17492. })(BABYLON.ProceduralTexture);
  17493. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17494. })(BABYLON || (BABYLON = {}));
  17495. var BABYLON;
  17496. (function (BABYLON) {
  17497. var WoodProceduralTexture = (function (_super) {
  17498. __extends(WoodProceduralTexture, _super);
  17499. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17500. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17501. this._ampScale = 100.0;
  17502. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17503. this.updateShaderUniforms();
  17504. this.refreshRate = 0;
  17505. }
  17506. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17507. this.setFloat("ampScale", this._ampScale);
  17508. this.setColor3("woodColor", this._woodColor);
  17509. };
  17510. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17511. get: function () {
  17512. return this._ampScale;
  17513. },
  17514. set: function (value) {
  17515. this._ampScale = value;
  17516. this.updateShaderUniforms();
  17517. },
  17518. enumerable: true,
  17519. configurable: true
  17520. });
  17521. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17522. get: function () {
  17523. return this._woodColor;
  17524. },
  17525. set: function (value) {
  17526. this._woodColor = value;
  17527. this.updateShaderUniforms();
  17528. },
  17529. enumerable: true,
  17530. configurable: true
  17531. });
  17532. return WoodProceduralTexture;
  17533. })(BABYLON.ProceduralTexture);
  17534. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17535. var FireProceduralTexture = (function (_super) {
  17536. __extends(FireProceduralTexture, _super);
  17537. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17538. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17539. this._time = 0.0;
  17540. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17541. this._autoGenerateTime = true;
  17542. this._alphaThreshold = 0.5;
  17543. this._fireColors = FireProceduralTexture.RedFireColors;
  17544. this.updateShaderUniforms();
  17545. this.refreshRate = 1;
  17546. }
  17547. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17548. this.setFloat("time", this._time);
  17549. this.setVector2("speed", this._speed);
  17550. this.setColor3("c1", this._fireColors[0]);
  17551. this.setColor3("c2", this._fireColors[1]);
  17552. this.setColor3("c3", this._fireColors[2]);
  17553. this.setColor3("c4", this._fireColors[3]);
  17554. this.setColor3("c5", this._fireColors[4]);
  17555. this.setColor3("c6", this._fireColors[5]);
  17556. this.setFloat("alphaThreshold", this._alphaThreshold);
  17557. };
  17558. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17559. if (this._autoGenerateTime) {
  17560. this._time += this.getScene().getAnimationRatio() * 0.03;
  17561. this.updateShaderUniforms();
  17562. }
  17563. _super.prototype.render.call(this, useCameraPostProcess);
  17564. };
  17565. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17566. get: function () {
  17567. return [
  17568. new BABYLON.Color3(0.5, 0.0, 1.0),
  17569. new BABYLON.Color3(0.9, 0.0, 1.0),
  17570. new BABYLON.Color3(0.2, 0.0, 1.0),
  17571. new BABYLON.Color3(1.0, 0.9, 1.0),
  17572. new BABYLON.Color3(0.1, 0.1, 1.0),
  17573. new BABYLON.Color3(0.9, 0.9, 1.0)
  17574. ];
  17575. },
  17576. enumerable: true,
  17577. configurable: true
  17578. });
  17579. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17580. get: function () {
  17581. return [
  17582. new BABYLON.Color3(0.5, 1.0, 0.0),
  17583. new BABYLON.Color3(0.5, 1.0, 0.0),
  17584. new BABYLON.Color3(0.3, 0.4, 0.0),
  17585. new BABYLON.Color3(0.5, 1.0, 0.0),
  17586. new BABYLON.Color3(0.2, 0.0, 0.0),
  17587. new BABYLON.Color3(0.5, 1.0, 0.0)
  17588. ];
  17589. },
  17590. enumerable: true,
  17591. configurable: true
  17592. });
  17593. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17594. get: function () {
  17595. return [
  17596. new BABYLON.Color3(0.5, 0.0, 0.1),
  17597. new BABYLON.Color3(0.9, 0.0, 0.0),
  17598. new BABYLON.Color3(0.2, 0.0, 0.0),
  17599. new BABYLON.Color3(1.0, 0.9, 0.0),
  17600. new BABYLON.Color3(0.1, 0.1, 0.1),
  17601. new BABYLON.Color3(0.9, 0.9, 0.9)
  17602. ];
  17603. },
  17604. enumerable: true,
  17605. configurable: true
  17606. });
  17607. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17608. get: function () {
  17609. return [
  17610. new BABYLON.Color3(0.1, 0.0, 0.5),
  17611. new BABYLON.Color3(0.0, 0.0, 0.5),
  17612. new BABYLON.Color3(0.1, 0.0, 0.2),
  17613. new BABYLON.Color3(0.0, 0.0, 1.0),
  17614. new BABYLON.Color3(0.1, 0.2, 0.3),
  17615. new BABYLON.Color3(0.0, 0.2, 0.9)
  17616. ];
  17617. },
  17618. enumerable: true,
  17619. configurable: true
  17620. });
  17621. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17622. get: function () {
  17623. return this._fireColors;
  17624. },
  17625. set: function (value) {
  17626. this._fireColors = value;
  17627. this.updateShaderUniforms();
  17628. },
  17629. enumerable: true,
  17630. configurable: true
  17631. });
  17632. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17633. get: function () {
  17634. return this._time;
  17635. },
  17636. set: function (value) {
  17637. this._time = value;
  17638. this.updateShaderUniforms();
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17644. get: function () {
  17645. return this._speed;
  17646. },
  17647. set: function (value) {
  17648. this._speed = value;
  17649. this.updateShaderUniforms();
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17655. get: function () {
  17656. return this._alphaThreshold;
  17657. },
  17658. set: function (value) {
  17659. this._alphaThreshold = value;
  17660. this.updateShaderUniforms();
  17661. },
  17662. enumerable: true,
  17663. configurable: true
  17664. });
  17665. return FireProceduralTexture;
  17666. })(BABYLON.ProceduralTexture);
  17667. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17668. var CloudProceduralTexture = (function (_super) {
  17669. __extends(CloudProceduralTexture, _super);
  17670. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17671. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17672. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17673. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17674. this.updateShaderUniforms();
  17675. this.refreshRate = 0;
  17676. }
  17677. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17678. this.setColor4("skyColor", this._skyColor);
  17679. this.setColor4("cloudColor", this._cloudColor);
  17680. };
  17681. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17682. get: function () {
  17683. return this._skyColor;
  17684. },
  17685. set: function (value) {
  17686. this._skyColor = value;
  17687. this.updateShaderUniforms();
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17693. get: function () {
  17694. return this._cloudColor;
  17695. },
  17696. set: function (value) {
  17697. this._cloudColor = value;
  17698. this.updateShaderUniforms();
  17699. },
  17700. enumerable: true,
  17701. configurable: true
  17702. });
  17703. return CloudProceduralTexture;
  17704. })(BABYLON.ProceduralTexture);
  17705. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17706. var GrassProceduralTexture = (function (_super) {
  17707. __extends(GrassProceduralTexture, _super);
  17708. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17709. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17710. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17711. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17712. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17713. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17714. this._grassColors = [
  17715. new BABYLON.Color3(0.29, 0.38, 0.02),
  17716. new BABYLON.Color3(0.36, 0.49, 0.09),
  17717. new BABYLON.Color3(0.51, 0.6, 0.28)
  17718. ];
  17719. this.updateShaderUniforms();
  17720. this.refreshRate = 0;
  17721. }
  17722. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17723. this.setColor3("herb1Color", this._grassColors[0]);
  17724. this.setColor3("herb2Color", this._grassColors[1]);
  17725. this.setColor3("herb3Color", this._grassColors[2]);
  17726. this.setColor3("groundColor", this._groundColor);
  17727. };
  17728. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17729. get: function () {
  17730. return this._grassColors;
  17731. },
  17732. set: function (value) {
  17733. this._grassColors = value;
  17734. this.updateShaderUniforms();
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17740. get: function () {
  17741. return this._groundColor;
  17742. },
  17743. set: function (value) {
  17744. this.groundColor = value;
  17745. this.updateShaderUniforms();
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. return GrassProceduralTexture;
  17751. })(BABYLON.ProceduralTexture);
  17752. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17753. var RoadProceduralTexture = (function (_super) {
  17754. __extends(RoadProceduralTexture, _super);
  17755. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17756. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17757. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17758. this.updateShaderUniforms();
  17759. this.refreshRate = 0;
  17760. }
  17761. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17762. this.setColor3("roadColor", this._roadColor);
  17763. };
  17764. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17765. get: function () {
  17766. return this._roadColor;
  17767. },
  17768. set: function (value) {
  17769. this._roadColor = value;
  17770. this.updateShaderUniforms();
  17771. },
  17772. enumerable: true,
  17773. configurable: true
  17774. });
  17775. return RoadProceduralTexture;
  17776. })(BABYLON.ProceduralTexture);
  17777. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17778. var BrickProceduralTexture = (function (_super) {
  17779. __extends(BrickProceduralTexture, _super);
  17780. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17781. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17782. this._numberOfBricksHeight = 15;
  17783. this._numberOfBricksWidth = 5;
  17784. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17785. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17786. this.updateShaderUniforms();
  17787. this.refreshRate = 0;
  17788. }
  17789. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17790. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17791. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17792. this.setColor3("brickColor", this._brickColor);
  17793. this.setColor3("jointColor", this._jointColor);
  17794. };
  17795. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17796. get: function () {
  17797. return this._numberOfBricksHeight;
  17798. },
  17799. set: function (value) {
  17800. this._numberOfBricksHeight = value;
  17801. this.updateShaderUniforms();
  17802. },
  17803. enumerable: true,
  17804. configurable: true
  17805. });
  17806. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17807. get: function () {
  17808. return this._numberOfBricksWidth;
  17809. },
  17810. set: function (value) {
  17811. this._numberOfBricksHeight = value;
  17812. this.updateShaderUniforms();
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17818. get: function () {
  17819. return this._jointColor;
  17820. },
  17821. set: function (value) {
  17822. this._jointColor = value;
  17823. this.updateShaderUniforms();
  17824. },
  17825. enumerable: true,
  17826. configurable: true
  17827. });
  17828. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17829. get: function () {
  17830. return this._brickColor;
  17831. },
  17832. set: function (value) {
  17833. this._brickColor = value;
  17834. this.updateShaderUniforms();
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. return BrickProceduralTexture;
  17840. })(BABYLON.ProceduralTexture);
  17841. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17842. var MarbleProceduralTexture = (function (_super) {
  17843. __extends(MarbleProceduralTexture, _super);
  17844. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17845. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17846. this._numberOfTilesHeight = 3;
  17847. this._numberOfTilesWidth = 3;
  17848. this._amplitude = 9.0;
  17849. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17850. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17851. this.updateShaderUniforms();
  17852. this.refreshRate = 0;
  17853. }
  17854. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17855. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17856. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17857. this.setFloat("amplitude", this._amplitude);
  17858. this.setColor3("marbleColor", this._marbleColor);
  17859. this.setColor3("jointColor", this._jointColor);
  17860. };
  17861. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17862. get: function () {
  17863. return this._numberOfTilesHeight;
  17864. },
  17865. set: function (value) {
  17866. this._numberOfTilesHeight = value;
  17867. this.updateShaderUniforms();
  17868. },
  17869. enumerable: true,
  17870. configurable: true
  17871. });
  17872. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17873. get: function () {
  17874. return this._numberOfTilesWidth;
  17875. },
  17876. set: function (value) {
  17877. this._numberOfTilesWidth = value;
  17878. this.updateShaderUniforms();
  17879. },
  17880. enumerable: true,
  17881. configurable: true
  17882. });
  17883. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17884. get: function () {
  17885. return this._jointColor;
  17886. },
  17887. set: function (value) {
  17888. this._jointColor = value;
  17889. this.updateShaderUniforms();
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17895. get: function () {
  17896. return this._marbleColor;
  17897. },
  17898. set: function (value) {
  17899. this._marbleColor = value;
  17900. this.updateShaderUniforms();
  17901. },
  17902. enumerable: true,
  17903. configurable: true
  17904. });
  17905. return MarbleProceduralTexture;
  17906. })(BABYLON.ProceduralTexture);
  17907. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17908. })(BABYLON || (BABYLON = {}));
  17909. var BABYLON;
  17910. (function (BABYLON) {
  17911. var EffectFallbacks = (function () {
  17912. function EffectFallbacks() {
  17913. this._defines = {};
  17914. this._currentRank = 32;
  17915. this._maxRank = -1;
  17916. }
  17917. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17918. if (!this._defines[rank]) {
  17919. if (rank < this._currentRank) {
  17920. this._currentRank = rank;
  17921. }
  17922. if (rank > this._maxRank) {
  17923. this._maxRank = rank;
  17924. }
  17925. this._defines[rank] = new Array();
  17926. }
  17927. this._defines[rank].push(define);
  17928. };
  17929. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17930. get: function () {
  17931. return this._currentRank <= this._maxRank;
  17932. },
  17933. enumerable: true,
  17934. configurable: true
  17935. });
  17936. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17937. var currentFallbacks = this._defines[this._currentRank];
  17938. for (var index = 0; index < currentFallbacks.length; index++) {
  17939. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17940. }
  17941. this._currentRank++;
  17942. return currentDefines;
  17943. };
  17944. return EffectFallbacks;
  17945. })();
  17946. BABYLON.EffectFallbacks = EffectFallbacks;
  17947. var Effect = (function () {
  17948. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17949. var _this = this;
  17950. this._isReady = false;
  17951. this._compilationError = "";
  17952. this._valueCache = [];
  17953. this._engine = engine;
  17954. this.name = baseName;
  17955. this.defines = defines;
  17956. this._uniformsNames = uniformsNames.concat(samplers);
  17957. this._samplers = samplers;
  17958. this._attributesNames = attributesNames;
  17959. this.onError = onError;
  17960. this.onCompiled = onCompiled;
  17961. var vertexSource;
  17962. var fragmentSource;
  17963. if (baseName.vertexElement) {
  17964. vertexSource = document.getElementById(baseName.vertexElement);
  17965. if (!vertexSource) {
  17966. vertexSource = baseName.vertexElement;
  17967. }
  17968. }
  17969. else {
  17970. vertexSource = baseName.vertex || baseName;
  17971. }
  17972. if (baseName.fragmentElement) {
  17973. fragmentSource = document.getElementById(baseName.fragmentElement);
  17974. if (!fragmentSource) {
  17975. fragmentSource = baseName.fragmentElement;
  17976. }
  17977. }
  17978. else {
  17979. fragmentSource = baseName.fragment || baseName;
  17980. }
  17981. this._loadVertexShader(vertexSource, function (vertexCode) {
  17982. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17983. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17984. });
  17985. });
  17986. }
  17987. // Properties
  17988. Effect.prototype.isReady = function () {
  17989. return this._isReady;
  17990. };
  17991. Effect.prototype.getProgram = function () {
  17992. return this._program;
  17993. };
  17994. Effect.prototype.getAttributesNames = function () {
  17995. return this._attributesNames;
  17996. };
  17997. Effect.prototype.getAttributeLocation = function (index) {
  17998. return this._attributes[index];
  17999. };
  18000. Effect.prototype.getAttributeLocationByName = function (name) {
  18001. var index = this._attributesNames.indexOf(name);
  18002. return this._attributes[index];
  18003. };
  18004. Effect.prototype.getAttributesCount = function () {
  18005. return this._attributes.length;
  18006. };
  18007. Effect.prototype.getUniformIndex = function (uniformName) {
  18008. return this._uniformsNames.indexOf(uniformName);
  18009. };
  18010. Effect.prototype.getUniform = function (uniformName) {
  18011. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18012. };
  18013. Effect.prototype.getSamplers = function () {
  18014. return this._samplers;
  18015. };
  18016. Effect.prototype.getCompilationError = function () {
  18017. return this._compilationError;
  18018. };
  18019. // Methods
  18020. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18021. // DOM element ?
  18022. if (vertex instanceof HTMLElement) {
  18023. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18024. callback(vertexCode);
  18025. return;
  18026. }
  18027. // Is in local store ?
  18028. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18029. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18030. return;
  18031. }
  18032. var vertexShaderUrl;
  18033. if (vertex[0] === "." || vertex[0] === "/") {
  18034. vertexShaderUrl = vertex;
  18035. }
  18036. else {
  18037. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18038. }
  18039. // Vertex shader
  18040. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18041. };
  18042. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18043. // DOM element ?
  18044. if (fragment instanceof HTMLElement) {
  18045. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18046. callback(fragmentCode);
  18047. return;
  18048. }
  18049. // Is in local store ?
  18050. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18051. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18052. return;
  18053. }
  18054. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18055. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18056. return;
  18057. }
  18058. var fragmentShaderUrl;
  18059. if (fragment[0] === "." || fragment[0] === "/") {
  18060. fragmentShaderUrl = fragment;
  18061. }
  18062. else {
  18063. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18064. }
  18065. // Fragment shader
  18066. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18067. };
  18068. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18069. try {
  18070. var engine = this._engine;
  18071. if (!engine.getCaps().highPrecisionShaderSupported) {
  18072. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18073. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18074. }
  18075. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18076. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18077. this._attributes = engine.getAttributes(this._program, attributesNames);
  18078. for (var index = 0; index < this._samplers.length; index++) {
  18079. var sampler = this.getUniform(this._samplers[index]);
  18080. if (sampler == null) {
  18081. this._samplers.splice(index, 1);
  18082. index--;
  18083. }
  18084. }
  18085. engine.bindSamplers(this);
  18086. this._isReady = true;
  18087. if (this.onCompiled) {
  18088. this.onCompiled(this);
  18089. }
  18090. }
  18091. catch (e) {
  18092. // Is it a problem with precision?
  18093. if (e.message.indexOf("highp") !== -1) {
  18094. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18095. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18096. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18097. return;
  18098. }
  18099. // Let's go through fallbacks then
  18100. if (fallbacks && fallbacks.isMoreFallbacks) {
  18101. defines = fallbacks.reduce(defines);
  18102. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18103. }
  18104. else {
  18105. BABYLON.Tools.Error("Unable to compile effect: ");
  18106. if (this.name.vertexElement) {
  18107. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18108. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18109. }
  18110. else if (this.name.vertex) {
  18111. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18112. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18113. }
  18114. else {
  18115. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18116. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18117. }
  18118. BABYLON.Tools.Error("Defines: " + defines);
  18119. BABYLON.Tools.Error("Error: " + e.message);
  18120. this._compilationError = e.message;
  18121. if (this.onError) {
  18122. this.onError(this, this._compilationError);
  18123. }
  18124. }
  18125. }
  18126. };
  18127. Effect.prototype._bindTexture = function (channel, texture) {
  18128. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18129. };
  18130. Effect.prototype.setTexture = function (channel, texture) {
  18131. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18132. };
  18133. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18134. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18135. };
  18136. //public _cacheMatrix(uniformName, matrix) {
  18137. // if (!this._valueCache[uniformName]) {
  18138. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18139. // }
  18140. // for (var index = 0; index < 16; index++) {
  18141. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18142. // }
  18143. //};
  18144. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18145. if (!this._valueCache[uniformName]) {
  18146. this._valueCache[uniformName] = [x, y];
  18147. return;
  18148. }
  18149. this._valueCache[uniformName][0] = x;
  18150. this._valueCache[uniformName][1] = y;
  18151. };
  18152. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18153. if (!this._valueCache[uniformName]) {
  18154. this._valueCache[uniformName] = [x, y, z];
  18155. return;
  18156. }
  18157. this._valueCache[uniformName][0] = x;
  18158. this._valueCache[uniformName][1] = y;
  18159. this._valueCache[uniformName][2] = z;
  18160. };
  18161. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18162. if (!this._valueCache[uniformName]) {
  18163. this._valueCache[uniformName] = [x, y, z, w];
  18164. return;
  18165. }
  18166. this._valueCache[uniformName][0] = x;
  18167. this._valueCache[uniformName][1] = y;
  18168. this._valueCache[uniformName][2] = z;
  18169. this._valueCache[uniformName][3] = w;
  18170. };
  18171. Effect.prototype.setArray = function (uniformName, array) {
  18172. this._engine.setArray(this.getUniform(uniformName), array);
  18173. return this;
  18174. };
  18175. Effect.prototype.setArray2 = function (uniformName, array) {
  18176. this._engine.setArray2(this.getUniform(uniformName), array);
  18177. return this;
  18178. };
  18179. Effect.prototype.setArray3 = function (uniformName, array) {
  18180. this._engine.setArray3(this.getUniform(uniformName), array);
  18181. return this;
  18182. };
  18183. Effect.prototype.setArray4 = function (uniformName, array) {
  18184. this._engine.setArray4(this.getUniform(uniformName), array);
  18185. return this;
  18186. };
  18187. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18188. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18189. return this;
  18190. };
  18191. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18192. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18193. // return;
  18194. //this._cacheMatrix(uniformName, matrix);
  18195. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18196. return this;
  18197. };
  18198. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18199. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18200. return this;
  18201. };
  18202. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18203. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18204. return this;
  18205. };
  18206. Effect.prototype.setFloat = function (uniformName, value) {
  18207. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18208. return this;
  18209. this._valueCache[uniformName] = value;
  18210. this._engine.setFloat(this.getUniform(uniformName), value);
  18211. return this;
  18212. };
  18213. Effect.prototype.setBool = function (uniformName, bool) {
  18214. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18215. return this;
  18216. this._valueCache[uniformName] = bool;
  18217. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18218. return this;
  18219. };
  18220. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18221. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18222. return this;
  18223. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18224. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18225. return this;
  18226. };
  18227. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18228. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18229. return this;
  18230. this._cacheFloat2(uniformName, x, y);
  18231. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18232. return this;
  18233. };
  18234. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18235. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18236. return this;
  18237. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18238. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18239. return this;
  18240. };
  18241. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18242. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18243. return this;
  18244. this._cacheFloat3(uniformName, x, y, z);
  18245. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18246. return this;
  18247. };
  18248. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18249. 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)
  18250. return this;
  18251. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18252. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18253. return this;
  18254. };
  18255. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18256. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18257. return this;
  18258. this._cacheFloat4(uniformName, x, y, z, w);
  18259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18260. return this;
  18261. };
  18262. Effect.prototype.setColor3 = function (uniformName, color3) {
  18263. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18264. return this;
  18265. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18266. this._engine.setColor3(this.getUniform(uniformName), color3);
  18267. return this;
  18268. };
  18269. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18270. 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)
  18271. return this;
  18272. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18273. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18274. return this;
  18275. };
  18276. // Statics
  18277. Effect.ShadersStore = {};
  18278. return Effect;
  18279. })();
  18280. BABYLON.Effect = Effect;
  18281. })(BABYLON || (BABYLON = {}));
  18282. var BABYLON;
  18283. (function (BABYLON) {
  18284. var Material = (function () {
  18285. function Material(name, scene, doNotAdd) {
  18286. this.name = name;
  18287. this.checkReadyOnEveryCall = true;
  18288. this.checkReadyOnlyOnce = false;
  18289. this.state = "";
  18290. this.alpha = 1.0;
  18291. this.backFaceCulling = true;
  18292. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18293. this.disableDepthWrite = false;
  18294. this._wasPreviouslyReady = false;
  18295. this._fillMode = Material.TriangleFillMode;
  18296. this.pointSize = 1.0;
  18297. this.zOffset = 0;
  18298. this.id = name;
  18299. this._scene = scene;
  18300. if (!doNotAdd) {
  18301. scene.materials.push(this);
  18302. }
  18303. }
  18304. Object.defineProperty(Material, "TriangleFillMode", {
  18305. get: function () {
  18306. return Material._TriangleFillMode;
  18307. },
  18308. enumerable: true,
  18309. configurable: true
  18310. });
  18311. Object.defineProperty(Material, "WireFrameFillMode", {
  18312. get: function () {
  18313. return Material._WireFrameFillMode;
  18314. },
  18315. enumerable: true,
  18316. configurable: true
  18317. });
  18318. Object.defineProperty(Material, "PointFillMode", {
  18319. get: function () {
  18320. return Material._PointFillMode;
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. Object.defineProperty(Material.prototype, "wireframe", {
  18326. get: function () {
  18327. return this._fillMode === Material.WireFrameFillMode;
  18328. },
  18329. set: function (value) {
  18330. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18331. },
  18332. enumerable: true,
  18333. configurable: true
  18334. });
  18335. Object.defineProperty(Material.prototype, "pointsCloud", {
  18336. get: function () {
  18337. return this._fillMode === Material.PointFillMode;
  18338. },
  18339. set: function (value) {
  18340. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18341. },
  18342. enumerable: true,
  18343. configurable: true
  18344. });
  18345. Object.defineProperty(Material.prototype, "fillMode", {
  18346. get: function () {
  18347. return this._fillMode;
  18348. },
  18349. set: function (value) {
  18350. this._fillMode = value;
  18351. },
  18352. enumerable: true,
  18353. configurable: true
  18354. });
  18355. Material.prototype.isReady = function (mesh, useInstances) {
  18356. return true;
  18357. };
  18358. Material.prototype.getEffect = function () {
  18359. return this._effect;
  18360. };
  18361. Material.prototype.getScene = function () {
  18362. return this._scene;
  18363. };
  18364. Material.prototype.needAlphaBlending = function () {
  18365. return (this.alpha < 1.0);
  18366. };
  18367. Material.prototype.needAlphaTesting = function () {
  18368. return false;
  18369. };
  18370. Material.prototype.getAlphaTestTexture = function () {
  18371. return null;
  18372. };
  18373. Material.prototype.trackCreation = function (onCompiled, onError) {
  18374. };
  18375. Material.prototype._preBind = function () {
  18376. var engine = this._scene.getEngine();
  18377. engine.enableEffect(this._effect);
  18378. engine.setState(this.backFaceCulling, this.zOffset);
  18379. };
  18380. Material.prototype.bind = function (world, mesh) {
  18381. this._scene._cachedMaterial = this;
  18382. if (this.onBind) {
  18383. this.onBind(this, mesh);
  18384. }
  18385. if (this.disableDepthWrite) {
  18386. var engine = this._scene.getEngine();
  18387. this._cachedDepthWriteState = engine.getDepthWrite();
  18388. engine.setDepthWrite(false);
  18389. }
  18390. };
  18391. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18392. };
  18393. Material.prototype.unbind = function () {
  18394. if (this.disableDepthWrite) {
  18395. var engine = this._scene.getEngine();
  18396. engine.setDepthWrite(this._cachedDepthWriteState);
  18397. }
  18398. };
  18399. Material.prototype.clone = function (name) {
  18400. return null;
  18401. };
  18402. Material.prototype.dispose = function (forceDisposeEffect) {
  18403. // Remove from scene
  18404. var index = this._scene.materials.indexOf(this);
  18405. this._scene.materials.splice(index, 1);
  18406. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18407. if (forceDisposeEffect && this._effect) {
  18408. this._scene.getEngine()._releaseEffect(this._effect);
  18409. this._effect = null;
  18410. }
  18411. // Callback
  18412. if (this.onDispose) {
  18413. this.onDispose();
  18414. }
  18415. };
  18416. Material._TriangleFillMode = 0;
  18417. Material._WireFrameFillMode = 1;
  18418. Material._PointFillMode = 2;
  18419. return Material;
  18420. })();
  18421. BABYLON.Material = Material;
  18422. })(BABYLON || (BABYLON = {}));
  18423. var BABYLON;
  18424. (function (BABYLON) {
  18425. var maxSimultaneousLights = 4;
  18426. var FresnelParameters = (function () {
  18427. function FresnelParameters() {
  18428. this.isEnabled = true;
  18429. this.leftColor = BABYLON.Color3.White();
  18430. this.rightColor = BABYLON.Color3.Black();
  18431. this.bias = 0;
  18432. this.power = 1;
  18433. }
  18434. return FresnelParameters;
  18435. })();
  18436. BABYLON.FresnelParameters = FresnelParameters;
  18437. var StandardMaterialDefines = (function () {
  18438. function StandardMaterialDefines() {
  18439. this.DIFFUSE = false;
  18440. this.AMBIENT = false;
  18441. this.OPACITY = false;
  18442. this.OPACITYRGB = false;
  18443. this.REFLECTION = false;
  18444. this.EMISSIVE = false;
  18445. this.SPECULAR = false;
  18446. this.BUMP = false;
  18447. this.SPECULAROVERALPHA = false;
  18448. this.CLIPPLANE = false;
  18449. this.ALPHATEST = false;
  18450. this.ALPHAFROMDIFFUSE = false;
  18451. this.POINTSIZE = false;
  18452. this.FOG = false;
  18453. this.LIGHT0 = false;
  18454. this.LIGHT1 = false;
  18455. this.LIGHT2 = false;
  18456. this.LIGHT3 = false;
  18457. this.SPOTLIGHT0 = false;
  18458. this.SPOTLIGHT1 = false;
  18459. this.SPOTLIGHT2 = false;
  18460. this.SPOTLIGHT3 = false;
  18461. this.HEMILIGHT0 = false;
  18462. this.HEMILIGHT1 = false;
  18463. this.HEMILIGHT2 = false;
  18464. this.HEMILIGHT3 = false;
  18465. this.POINTDIRLIGHT0 = false;
  18466. this.POINTDIRLIGHT1 = false;
  18467. this.POINTDIRLIGHT2 = false;
  18468. this.POINTDIRLIGHT3 = false;
  18469. this.SPECULARTERM = false;
  18470. this.SHADOW0 = false;
  18471. this.SHADOW1 = false;
  18472. this.SHADOW2 = false;
  18473. this.SHADOW3 = false;
  18474. this.SHADOWS = false;
  18475. this.SHADOWVSM0 = false;
  18476. this.SHADOWVSM1 = false;
  18477. this.SHADOWVSM2 = false;
  18478. this.SHADOWVSM3 = false;
  18479. this.SHADOWPCF0 = false;
  18480. this.SHADOWPCF1 = false;
  18481. this.SHADOWPCF2 = false;
  18482. this.SHADOWPCF3 = false;
  18483. this.DIFFUSEFRESNEL = false;
  18484. this.OPACITYFRESNEL = false;
  18485. this.REFLECTIONFRESNEL = false;
  18486. this.EMISSIVEFRESNEL = false;
  18487. this.FRESNEL = false;
  18488. this.NORMAL = false;
  18489. this.UV1 = false;
  18490. this.UV2 = false;
  18491. this.VERTEXCOLOR = false;
  18492. this.VERTEXALPHA = false;
  18493. this.BONES = false;
  18494. this.BONES4 = false;
  18495. this.BonesPerMesh = 0;
  18496. this.INSTANCES = false;
  18497. this.GLOSSINESS = false;
  18498. this._keys = Object.keys(this);
  18499. }
  18500. StandardMaterialDefines.prototype.isEqual = function (other) {
  18501. for (var index = 0; index < this._keys.length; index++) {
  18502. var prop = this._keys[index];
  18503. if (this[prop] !== other[prop]) {
  18504. return false;
  18505. }
  18506. }
  18507. return true;
  18508. };
  18509. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18510. for (var index = 0; index < this._keys.length; index++) {
  18511. var prop = this._keys[index];
  18512. other[prop] = this[prop];
  18513. }
  18514. };
  18515. StandardMaterialDefines.prototype.reset = function () {
  18516. for (var index = 0; index < this._keys.length; index++) {
  18517. var prop = this._keys[index];
  18518. if (prop === "BonesPerMesh") {
  18519. this[prop] = 0;
  18520. continue;
  18521. }
  18522. this[prop] = false;
  18523. }
  18524. };
  18525. StandardMaterialDefines.prototype.toString = function () {
  18526. var result = "";
  18527. for (var index = 0; index < this._keys.length; index++) {
  18528. var prop = this._keys[index];
  18529. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18530. result += "#define BonesPerMesh " + this[prop] + "\n";
  18531. continue;
  18532. }
  18533. if (this[prop]) {
  18534. result += "#define " + prop + "\n";
  18535. }
  18536. }
  18537. return result;
  18538. };
  18539. return StandardMaterialDefines;
  18540. })();
  18541. var StandardMaterial = (function (_super) {
  18542. __extends(StandardMaterial, _super);
  18543. function StandardMaterial(name, scene) {
  18544. var _this = this;
  18545. _super.call(this, name, scene);
  18546. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18547. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18548. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18549. this.specularPower = 64;
  18550. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18551. this.useAlphaFromDiffuseTexture = false;
  18552. this.useSpecularOverAlpha = true;
  18553. this.fogEnabled = true;
  18554. this.useGlossinessFromSpecularMapAlpha = false;
  18555. this._renderTargets = new BABYLON.SmartArray(16);
  18556. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18557. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18558. this._scaledDiffuse = new BABYLON.Color3();
  18559. this._scaledSpecular = new BABYLON.Color3();
  18560. this._defines = new StandardMaterialDefines();
  18561. this._cachedDefines = new StandardMaterialDefines();
  18562. this._cachedDefines.BonesPerMesh = -1;
  18563. this.getRenderTargetTextures = function () {
  18564. _this._renderTargets.reset();
  18565. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18566. _this._renderTargets.push(_this.reflectionTexture);
  18567. }
  18568. return _this._renderTargets;
  18569. };
  18570. }
  18571. StandardMaterial.prototype.needAlphaBlending = function () {
  18572. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18573. };
  18574. StandardMaterial.prototype.needAlphaTesting = function () {
  18575. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18576. };
  18577. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18578. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18579. };
  18580. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18581. return this.diffuseTexture;
  18582. };
  18583. // Methods
  18584. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18585. if (this.checkReadyOnlyOnce) {
  18586. if (this._wasPreviouslyReady) {
  18587. return true;
  18588. }
  18589. }
  18590. var scene = this.getScene();
  18591. if (!this.checkReadyOnEveryCall) {
  18592. if (this._renderId === scene.getRenderId()) {
  18593. return true;
  18594. }
  18595. }
  18596. var engine = scene.getEngine();
  18597. var needNormals = false;
  18598. var needUVs = false;
  18599. this._defines.reset();
  18600. // Textures
  18601. if (scene.texturesEnabled) {
  18602. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18603. if (!this.diffuseTexture.isReady()) {
  18604. return false;
  18605. }
  18606. else {
  18607. needUVs = true;
  18608. this._defines.DIFFUSE = true;
  18609. }
  18610. }
  18611. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18612. if (!this.ambientTexture.isReady()) {
  18613. return false;
  18614. }
  18615. else {
  18616. needUVs = true;
  18617. this._defines.AMBIENT = true;
  18618. }
  18619. }
  18620. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18621. if (!this.opacityTexture.isReady()) {
  18622. return false;
  18623. }
  18624. else {
  18625. needUVs = true;
  18626. this._defines.OPACITY = true;
  18627. if (this.opacityTexture.getAlphaFromRGB) {
  18628. this._defines.OPACITYRGB = true;
  18629. }
  18630. }
  18631. }
  18632. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18633. if (!this.reflectionTexture.isReady()) {
  18634. return false;
  18635. }
  18636. else {
  18637. needNormals = true;
  18638. needUVs = true;
  18639. this._defines.REFLECTION = true;
  18640. }
  18641. }
  18642. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18643. if (!this.emissiveTexture.isReady()) {
  18644. return false;
  18645. }
  18646. else {
  18647. needUVs = true;
  18648. this._defines.EMISSIVE = true;
  18649. }
  18650. }
  18651. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18652. if (!this.specularTexture.isReady()) {
  18653. return false;
  18654. }
  18655. else {
  18656. needUVs = true;
  18657. this._defines.SPECULAR = true;
  18658. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18659. }
  18660. }
  18661. }
  18662. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18663. if (!this.bumpTexture.isReady()) {
  18664. return false;
  18665. }
  18666. else {
  18667. needUVs = true;
  18668. this._defines.BUMP = true;
  18669. }
  18670. }
  18671. // Effect
  18672. if (scene.clipPlane) {
  18673. this._defines.CLIPPLANE = true;
  18674. }
  18675. if (engine.getAlphaTesting()) {
  18676. this._defines.ALPHATEST = true;
  18677. }
  18678. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18679. this._defines.ALPHAFROMDIFFUSE = true;
  18680. }
  18681. // Point size
  18682. if (this.pointsCloud || scene.forcePointsCloud) {
  18683. this._defines.POINTSIZE = true;
  18684. }
  18685. // Fog
  18686. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18687. this._defines.FOG = true;
  18688. }
  18689. var lightIndex = 0;
  18690. if (scene.lightsEnabled) {
  18691. for (var index = 0; index < scene.lights.length; index++) {
  18692. var light = scene.lights[index];
  18693. if (!light.isEnabled()) {
  18694. continue;
  18695. }
  18696. // Excluded check
  18697. if (light._excludedMeshesIds.length > 0) {
  18698. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18699. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18700. if (excludedMesh) {
  18701. light.excludedMeshes.push(excludedMesh);
  18702. }
  18703. }
  18704. light._excludedMeshesIds = [];
  18705. }
  18706. // Included check
  18707. if (light._includedOnlyMeshesIds.length > 0) {
  18708. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18709. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18710. if (includedOnlyMesh) {
  18711. light.includedOnlyMeshes.push(includedOnlyMesh);
  18712. }
  18713. }
  18714. light._includedOnlyMeshesIds = [];
  18715. }
  18716. if (!light.canAffectMesh(mesh)) {
  18717. continue;
  18718. }
  18719. needNormals = true;
  18720. this._defines["LIGHT" + lightIndex] = true;
  18721. var type;
  18722. if (light instanceof BABYLON.SpotLight) {
  18723. type = "SPOTLIGHT" + lightIndex;
  18724. }
  18725. else if (light instanceof BABYLON.HemisphericLight) {
  18726. type = "HEMILIGHT" + lightIndex;
  18727. }
  18728. else {
  18729. type = "POINTDIRLIGHT" + lightIndex;
  18730. }
  18731. this._defines[type] = true;
  18732. // Specular
  18733. if (!light.specular.equalsFloats(0, 0, 0)) {
  18734. this._defines.SPECULARTERM = true;
  18735. }
  18736. // Shadows
  18737. if (scene.shadowsEnabled) {
  18738. var shadowGenerator = light.getShadowGenerator();
  18739. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18740. this._defines["SHADOW" + lightIndex] = true;
  18741. this._defines.SHADOWS = true;
  18742. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18743. this._defines["SHADOWVSM" + lightIndex] = true;
  18744. }
  18745. if (shadowGenerator.usePoissonSampling) {
  18746. this._defines["SHADOWPCF" + lightIndex] = true;
  18747. }
  18748. }
  18749. }
  18750. lightIndex++;
  18751. if (lightIndex === maxSimultaneousLights)
  18752. break;
  18753. }
  18754. }
  18755. if (StandardMaterial.FresnelEnabled) {
  18756. // Fresnel
  18757. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18758. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18759. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18760. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18761. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18762. this._defines.DIFFUSEFRESNEL = true;
  18763. }
  18764. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18765. this._defines.OPACITYFRESNEL = true;
  18766. }
  18767. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18768. this._defines.REFLECTIONFRESNEL = true;
  18769. }
  18770. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18771. this._defines.EMISSIVEFRESNEL = true;
  18772. }
  18773. needNormals = true;
  18774. this._defines.FRESNEL = true;
  18775. }
  18776. }
  18777. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18778. this._defines.SPECULAROVERALPHA = true;
  18779. }
  18780. // Attribs
  18781. if (mesh) {
  18782. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18783. this._defines.NORMAL = true;
  18784. }
  18785. if (needUVs) {
  18786. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18787. this._defines.UV1 = true;
  18788. }
  18789. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18790. this._defines.UV2 = true;
  18791. }
  18792. }
  18793. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18794. this._defines.VERTEXCOLOR = true;
  18795. if (mesh.hasVertexAlpha) {
  18796. this._defines.VERTEXALPHA = true;
  18797. }
  18798. }
  18799. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18800. this._defines.BONES = true;
  18801. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18802. this._defines.BONES4 = true;
  18803. }
  18804. // Instances
  18805. if (useInstances) {
  18806. this._defines.INSTANCES = true;
  18807. }
  18808. }
  18809. // Get correct effect
  18810. if (!this._defines.isEqual(this._cachedDefines)) {
  18811. this._defines.cloneTo(this._cachedDefines);
  18812. scene.resetCachedMaterial();
  18813. // Fallbacks
  18814. var fallbacks = new BABYLON.EffectFallbacks();
  18815. if (this._defines.REFLECTION) {
  18816. fallbacks.addFallback(0, "REFLECTION");
  18817. }
  18818. if (this._defines.SPECULAR) {
  18819. fallbacks.addFallback(0, "SPECULAR");
  18820. }
  18821. if (this._defines.BUMP) {
  18822. fallbacks.addFallback(0, "BUMP");
  18823. }
  18824. if (this._defines.SPECULAROVERALPHA) {
  18825. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18826. }
  18827. if (this._defines.FOG) {
  18828. fallbacks.addFallback(1, "FOG");
  18829. }
  18830. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18831. if (!this._defines["LIGHT" + lightIndex]) {
  18832. continue;
  18833. }
  18834. if (lightIndex > 0) {
  18835. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18836. }
  18837. if (this._defines["SHADOW" + lightIndex]) {
  18838. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18839. }
  18840. if (this._defines["SHADOWPCF" + lightIndex]) {
  18841. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18842. }
  18843. if (this._defines["SHADOWVSM" + lightIndex]) {
  18844. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18845. }
  18846. }
  18847. if (this._defines.SPECULARTERM) {
  18848. fallbacks.addFallback(0, "SPECULARTERM");
  18849. }
  18850. if (this._defines.DIFFUSEFRESNEL) {
  18851. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18852. }
  18853. if (this._defines.OPACITYFRESNEL) {
  18854. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18855. }
  18856. if (this._defines.REFLECTIONFRESNEL) {
  18857. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18858. }
  18859. if (this._defines.EMISSIVEFRESNEL) {
  18860. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18861. }
  18862. if (this._defines.FRESNEL) {
  18863. fallbacks.addFallback(4, "FRESNEL");
  18864. }
  18865. if (this._defines.BONES4) {
  18866. fallbacks.addFallback(0, "BONES4");
  18867. }
  18868. //Attributes
  18869. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18870. if (this._defines.NORMAL) {
  18871. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18872. }
  18873. if (this._defines.UV1) {
  18874. attribs.push(BABYLON.VertexBuffer.UVKind);
  18875. }
  18876. if (this._defines.UV2) {
  18877. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18878. }
  18879. if (this._defines.VERTEXCOLOR) {
  18880. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18881. }
  18882. if (this._defines.BONES) {
  18883. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18884. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18885. }
  18886. if (this._defines.INSTANCES) {
  18887. attribs.push("world0");
  18888. attribs.push("world1");
  18889. attribs.push("world2");
  18890. attribs.push("world3");
  18891. }
  18892. // Legacy browser patch
  18893. var shaderName = "default";
  18894. if (!scene.getEngine().getCaps().standardDerivatives) {
  18895. shaderName = "legacydefault";
  18896. }
  18897. var join = this._defines.toString();
  18898. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18899. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18900. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18901. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18902. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18903. "vFogInfos", "vFogColor", "pointSize",
  18904. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18905. "mBones",
  18906. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18907. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18908. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18909. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18910. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18911. ], join, fallbacks, this.onCompiled, this.onError);
  18912. }
  18913. if (!this._effect.isReady()) {
  18914. return false;
  18915. }
  18916. this._renderId = scene.getRenderId();
  18917. this._wasPreviouslyReady = true;
  18918. return true;
  18919. };
  18920. StandardMaterial.prototype.unbind = function () {
  18921. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18922. this._effect.setTexture("reflection2DSampler", null);
  18923. }
  18924. _super.prototype.unbind.call(this);
  18925. };
  18926. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18927. this._effect.setMatrix("world", world);
  18928. };
  18929. StandardMaterial.prototype.bind = function (world, mesh) {
  18930. var scene = this.getScene();
  18931. // Matrices
  18932. this.bindOnlyWorldMatrix(world);
  18933. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18934. // Bones
  18935. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18936. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18937. }
  18938. if (scene.getCachedMaterial() !== this) {
  18939. if (StandardMaterial.FresnelEnabled) {
  18940. // Fresnel
  18941. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18942. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18943. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18944. }
  18945. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18946. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18947. }
  18948. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18949. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18950. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18951. }
  18952. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18953. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18954. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18955. }
  18956. }
  18957. // Textures
  18958. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18959. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18960. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18961. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18962. }
  18963. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18964. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18965. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18966. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18967. }
  18968. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18969. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18970. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18971. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18972. }
  18973. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18974. if (this.reflectionTexture.isCube) {
  18975. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18976. }
  18977. else {
  18978. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18979. }
  18980. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18981. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18982. }
  18983. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18984. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18985. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18986. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18987. }
  18988. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18989. this._effect.setTexture("specularSampler", this.specularTexture);
  18990. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18991. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18992. }
  18993. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18994. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18995. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18996. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18997. }
  18998. // Clip plane
  18999. if (scene.clipPlane) {
  19000. var clipPlane = scene.clipPlane;
  19001. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19002. }
  19003. // Point size
  19004. if (this.pointsCloud) {
  19005. this._effect.setFloat("pointSize", this.pointSize);
  19006. }
  19007. // Colors
  19008. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19009. // Scaling down color according to emissive
  19010. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19011. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19012. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19013. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19014. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19015. if (this._defines.SPECULARTERM) {
  19016. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19017. }
  19018. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19019. }
  19020. // Scaling down color according to emissive
  19021. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19022. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19023. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19024. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19025. if (scene.lightsEnabled) {
  19026. var lightIndex = 0;
  19027. for (var index = 0; index < scene.lights.length; index++) {
  19028. var light = scene.lights[index];
  19029. if (!light.isEnabled()) {
  19030. continue;
  19031. }
  19032. if (!light.canAffectMesh(mesh)) {
  19033. continue;
  19034. }
  19035. if (light instanceof BABYLON.PointLight) {
  19036. // Point Light
  19037. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19038. }
  19039. else if (light instanceof BABYLON.DirectionalLight) {
  19040. // Directional Light
  19041. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19042. }
  19043. else if (light instanceof BABYLON.SpotLight) {
  19044. // Spot Light
  19045. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19046. }
  19047. else if (light instanceof BABYLON.HemisphericLight) {
  19048. // Hemispheric Light
  19049. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19050. }
  19051. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19052. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19053. if (this._defines.SPECULARTERM) {
  19054. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19055. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19056. }
  19057. // Shadows
  19058. if (scene.shadowsEnabled) {
  19059. var shadowGenerator = light.getShadowGenerator();
  19060. if (mesh.receiveShadows && shadowGenerator) {
  19061. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19062. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19063. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19064. }
  19065. }
  19066. lightIndex++;
  19067. if (lightIndex === maxSimultaneousLights)
  19068. break;
  19069. }
  19070. }
  19071. // View
  19072. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19073. this._effect.setMatrix("view", scene.getViewMatrix());
  19074. }
  19075. // Fog
  19076. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19077. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19078. this._effect.setColor3("vFogColor", scene.fogColor);
  19079. }
  19080. _super.prototype.bind.call(this, world, mesh);
  19081. };
  19082. StandardMaterial.prototype.getAnimatables = function () {
  19083. var results = [];
  19084. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19085. results.push(this.diffuseTexture);
  19086. }
  19087. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19088. results.push(this.ambientTexture);
  19089. }
  19090. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19091. results.push(this.opacityTexture);
  19092. }
  19093. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19094. results.push(this.reflectionTexture);
  19095. }
  19096. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19097. results.push(this.emissiveTexture);
  19098. }
  19099. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19100. results.push(this.specularTexture);
  19101. }
  19102. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19103. results.push(this.bumpTexture);
  19104. }
  19105. return results;
  19106. };
  19107. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19108. if (this.diffuseTexture) {
  19109. this.diffuseTexture.dispose();
  19110. }
  19111. if (this.ambientTexture) {
  19112. this.ambientTexture.dispose();
  19113. }
  19114. if (this.opacityTexture) {
  19115. this.opacityTexture.dispose();
  19116. }
  19117. if (this.reflectionTexture) {
  19118. this.reflectionTexture.dispose();
  19119. }
  19120. if (this.emissiveTexture) {
  19121. this.emissiveTexture.dispose();
  19122. }
  19123. if (this.specularTexture) {
  19124. this.specularTexture.dispose();
  19125. }
  19126. if (this.bumpTexture) {
  19127. this.bumpTexture.dispose();
  19128. }
  19129. _super.prototype.dispose.call(this, forceDisposeEffect);
  19130. };
  19131. StandardMaterial.prototype.clone = function (name) {
  19132. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19133. // Base material
  19134. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19135. newStandardMaterial.alpha = this.alpha;
  19136. newStandardMaterial.fillMode = this.fillMode;
  19137. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19138. // Standard material
  19139. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19140. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19141. }
  19142. if (this.ambientTexture && this.ambientTexture.clone) {
  19143. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19144. }
  19145. if (this.opacityTexture && this.opacityTexture.clone) {
  19146. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19147. }
  19148. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19149. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19150. }
  19151. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19152. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19153. }
  19154. if (this.specularTexture && this.specularTexture.clone) {
  19155. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19156. }
  19157. if (this.bumpTexture && this.bumpTexture.clone) {
  19158. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19159. }
  19160. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19161. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19162. newStandardMaterial.specularColor = this.specularColor.clone();
  19163. newStandardMaterial.specularPower = this.specularPower;
  19164. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19165. return newStandardMaterial;
  19166. };
  19167. // Statics
  19168. // Flags used to enable or disable a type of texture for all Standard Materials
  19169. StandardMaterial.DiffuseTextureEnabled = true;
  19170. StandardMaterial.AmbientTextureEnabled = true;
  19171. StandardMaterial.OpacityTextureEnabled = true;
  19172. StandardMaterial.ReflectionTextureEnabled = true;
  19173. StandardMaterial.EmissiveTextureEnabled = true;
  19174. StandardMaterial.SpecularTextureEnabled = true;
  19175. StandardMaterial.BumpTextureEnabled = true;
  19176. StandardMaterial.FresnelEnabled = true;
  19177. return StandardMaterial;
  19178. })(BABYLON.Material);
  19179. BABYLON.StandardMaterial = StandardMaterial;
  19180. })(BABYLON || (BABYLON = {}));
  19181. var BABYLON;
  19182. (function (BABYLON) {
  19183. var MultiMaterial = (function (_super) {
  19184. __extends(MultiMaterial, _super);
  19185. function MultiMaterial(name, scene) {
  19186. _super.call(this, name, scene, true);
  19187. this.subMaterials = new Array();
  19188. scene.multiMaterials.push(this);
  19189. }
  19190. // Properties
  19191. MultiMaterial.prototype.getSubMaterial = function (index) {
  19192. if (index < 0 || index >= this.subMaterials.length) {
  19193. return this.getScene().defaultMaterial;
  19194. }
  19195. return this.subMaterials[index];
  19196. };
  19197. // Methods
  19198. MultiMaterial.prototype.isReady = function (mesh) {
  19199. for (var index = 0; index < this.subMaterials.length; index++) {
  19200. var subMaterial = this.subMaterials[index];
  19201. if (subMaterial) {
  19202. if (!this.subMaterials[index].isReady(mesh)) {
  19203. return false;
  19204. }
  19205. }
  19206. }
  19207. return true;
  19208. };
  19209. MultiMaterial.prototype.clone = function (name) {
  19210. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19211. for (var index = 0; index < this.subMaterials.length; index++) {
  19212. var subMaterial = this.subMaterials[index];
  19213. newMultiMaterial.subMaterials.push(subMaterial);
  19214. }
  19215. return newMultiMaterial;
  19216. };
  19217. return MultiMaterial;
  19218. })(BABYLON.Material);
  19219. BABYLON.MultiMaterial = MultiMaterial;
  19220. })(BABYLON || (BABYLON = {}));
  19221. var BABYLON;
  19222. (function (BABYLON) {
  19223. var SceneLoader = (function () {
  19224. function SceneLoader() {
  19225. }
  19226. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19227. get: function () {
  19228. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19229. },
  19230. set: function (value) {
  19231. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19232. },
  19233. enumerable: true,
  19234. configurable: true
  19235. });
  19236. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19237. get: function () {
  19238. return SceneLoader._ShowLoadingScreen;
  19239. },
  19240. set: function (value) {
  19241. SceneLoader._ShowLoadingScreen = value;
  19242. },
  19243. enumerable: true,
  19244. configurable: true
  19245. });
  19246. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19247. var dotPosition = sceneFilename.lastIndexOf(".");
  19248. var queryStringPosition = sceneFilename.indexOf("?");
  19249. if (queryStringPosition === -1) {
  19250. queryStringPosition = sceneFilename.length;
  19251. }
  19252. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19253. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19254. var plugin = this._registeredPlugins[index];
  19255. if (plugin.extensions.indexOf(extension) !== -1) {
  19256. return plugin;
  19257. }
  19258. }
  19259. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19260. };
  19261. // Public functions
  19262. SceneLoader.RegisterPlugin = function (plugin) {
  19263. plugin.extensions = plugin.extensions.toLowerCase();
  19264. SceneLoader._registeredPlugins.push(plugin);
  19265. };
  19266. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19267. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19268. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19269. return;
  19270. }
  19271. var loadingToken = {};
  19272. scene._addPendingData(loadingToken);
  19273. var manifestChecked = function (success) {
  19274. scene.database = database;
  19275. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19276. var importMeshFromData = function (data) {
  19277. var meshes = [];
  19278. var particleSystems = [];
  19279. var skeletons = [];
  19280. try {
  19281. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19282. if (onerror) {
  19283. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19284. }
  19285. scene._removePendingData(loadingToken);
  19286. return;
  19287. }
  19288. }
  19289. catch (e) {
  19290. if (onerror) {
  19291. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19292. }
  19293. scene._removePendingData(loadingToken);
  19294. return;
  19295. }
  19296. if (onsuccess) {
  19297. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19298. onsuccess(meshes, particleSystems, skeletons);
  19299. scene._removePendingData(loadingToken);
  19300. }
  19301. };
  19302. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19303. // Direct load
  19304. importMeshFromData(sceneFilename.substr(5));
  19305. return;
  19306. }
  19307. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19308. importMeshFromData(data);
  19309. }, progressCallBack, database);
  19310. };
  19311. if (scene.getEngine().enableOfflineSupport) {
  19312. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19313. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19314. }
  19315. else {
  19316. manifestChecked(true);
  19317. }
  19318. };
  19319. /**
  19320. * Load a scene
  19321. * @param rootUrl a string that defines the root url for scene and resources
  19322. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19323. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19324. */
  19325. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19326. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19327. };
  19328. /**
  19329. * Append a scene
  19330. * @param rootUrl a string that defines the root url for scene and resources
  19331. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19332. * @param scene is the instance of BABYLON.Scene to append to
  19333. */
  19334. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19335. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19336. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19337. return;
  19338. }
  19339. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19340. var database;
  19341. var loadingToken = {};
  19342. scene._addPendingData(loadingToken);
  19343. if (SceneLoader.ShowLoadingScreen) {
  19344. scene.getEngine().displayLoadingUI();
  19345. }
  19346. var loadSceneFromData = function (data) {
  19347. scene.database = database;
  19348. if (!plugin.load(scene, data, rootUrl)) {
  19349. if (onerror) {
  19350. onerror(scene);
  19351. }
  19352. scene._removePendingData(loadingToken);
  19353. scene.getEngine().hideLoadingUI();
  19354. return;
  19355. }
  19356. if (onsuccess) {
  19357. onsuccess(scene);
  19358. }
  19359. scene._removePendingData(loadingToken);
  19360. if (SceneLoader.ShowLoadingScreen) {
  19361. scene.executeWhenReady(function () {
  19362. scene.getEngine().hideLoadingUI();
  19363. });
  19364. }
  19365. };
  19366. var manifestChecked = function (success) {
  19367. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19368. };
  19369. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19370. // Direct load
  19371. loadSceneFromData(sceneFilename.substr(5));
  19372. return;
  19373. }
  19374. if (rootUrl.indexOf("file:") === -1) {
  19375. if (scene.getEngine().enableOfflineSupport) {
  19376. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19377. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19378. }
  19379. else {
  19380. manifestChecked(true);
  19381. }
  19382. }
  19383. else {
  19384. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19385. }
  19386. };
  19387. // Flags
  19388. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19389. SceneLoader._ShowLoadingScreen = true;
  19390. // Members
  19391. SceneLoader._registeredPlugins = new Array();
  19392. return SceneLoader;
  19393. })();
  19394. BABYLON.SceneLoader = SceneLoader;
  19395. ;
  19396. })(BABYLON || (BABYLON = {}));
  19397. var BABYLON;
  19398. (function (BABYLON) {
  19399. var Internals;
  19400. (function (Internals) {
  19401. var checkColors4 = function (colors, count) {
  19402. // Check if color3 was used
  19403. if (colors.length === count * 3) {
  19404. var colors4 = [];
  19405. for (var index = 0; index < colors.length; index += 3) {
  19406. var newIndex = (index / 3) * 4;
  19407. colors4[newIndex] = colors[index];
  19408. colors4[newIndex + 1] = colors[index + 1];
  19409. colors4[newIndex + 2] = colors[index + 2];
  19410. colors4[newIndex + 3] = 1.0;
  19411. }
  19412. return colors4;
  19413. }
  19414. return colors;
  19415. };
  19416. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19417. var texture = null;
  19418. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19419. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19420. texture.name = parsedTexture.name;
  19421. texture.hasAlpha = parsedTexture.hasAlpha;
  19422. texture.level = parsedTexture.level;
  19423. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19424. }
  19425. return texture;
  19426. };
  19427. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19428. if (parsedTexture.isCube) {
  19429. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19430. }
  19431. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19432. return null;
  19433. }
  19434. var texture;
  19435. if (parsedTexture.mirrorPlane) {
  19436. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19437. texture._waitingRenderList = parsedTexture.renderList;
  19438. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19439. }
  19440. else if (parsedTexture.isRenderTarget) {
  19441. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19442. texture._waitingRenderList = parsedTexture.renderList;
  19443. }
  19444. else {
  19445. if (parsedTexture.base64String) {
  19446. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19447. }
  19448. else {
  19449. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19450. }
  19451. }
  19452. texture.name = parsedTexture.name;
  19453. texture.hasAlpha = parsedTexture.hasAlpha;
  19454. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19455. texture.level = parsedTexture.level;
  19456. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19457. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19458. texture.uOffset = parsedTexture.uOffset;
  19459. texture.vOffset = parsedTexture.vOffset;
  19460. texture.uScale = parsedTexture.uScale;
  19461. texture.vScale = parsedTexture.vScale;
  19462. texture.uAng = parsedTexture.uAng;
  19463. texture.vAng = parsedTexture.vAng;
  19464. texture.wAng = parsedTexture.wAng;
  19465. texture.wrapU = parsedTexture.wrapU;
  19466. texture.wrapV = parsedTexture.wrapV;
  19467. // Animations
  19468. if (parsedTexture.animations) {
  19469. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19470. var parsedAnimation = parsedTexture.animations[animationIndex];
  19471. texture.animations.push(parseAnimation(parsedAnimation));
  19472. }
  19473. }
  19474. return texture;
  19475. };
  19476. var parseSkeleton = function (parsedSkeleton, scene) {
  19477. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19478. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19479. var parsedBone = parsedSkeleton.bones[index];
  19480. var parentBone = null;
  19481. if (parsedBone.parentBoneIndex > -1) {
  19482. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19483. }
  19484. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19485. if (parsedBone.animation) {
  19486. bone.animations.push(parseAnimation(parsedBone.animation));
  19487. }
  19488. }
  19489. return skeleton;
  19490. };
  19491. var parseFresnelParameters = function (parsedFresnelParameters) {
  19492. var fresnelParameters = new BABYLON.FresnelParameters();
  19493. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19494. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19495. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19496. fresnelParameters.bias = parsedFresnelParameters.bias;
  19497. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19498. return fresnelParameters;
  19499. };
  19500. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19501. var material;
  19502. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19503. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19504. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19505. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19506. material.specularPower = parsedMaterial.specularPower;
  19507. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19508. material.alpha = parsedMaterial.alpha;
  19509. material.id = parsedMaterial.id;
  19510. if (parsedMaterial.disableDepthWrite) {
  19511. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19512. }
  19513. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19514. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19515. material.wireframe = parsedMaterial.wireframe;
  19516. if (parsedMaterial.diffuseTexture) {
  19517. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19518. }
  19519. if (parsedMaterial.diffuseFresnelParameters) {
  19520. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19521. }
  19522. if (parsedMaterial.ambientTexture) {
  19523. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19524. }
  19525. if (parsedMaterial.opacityTexture) {
  19526. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19527. }
  19528. if (parsedMaterial.opacityFresnelParameters) {
  19529. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19530. }
  19531. if (parsedMaterial.reflectionTexture) {
  19532. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19533. }
  19534. if (parsedMaterial.reflectionFresnelParameters) {
  19535. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19536. }
  19537. if (parsedMaterial.emissiveTexture) {
  19538. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19539. }
  19540. if (parsedMaterial.emissiveFresnelParameters) {
  19541. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19542. }
  19543. if (parsedMaterial.specularTexture) {
  19544. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19545. }
  19546. if (parsedMaterial.bumpTexture) {
  19547. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19548. }
  19549. if (parsedMaterial.checkReadyOnlyOnce) {
  19550. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19551. }
  19552. return material;
  19553. };
  19554. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19555. for (var index = 0; index < parsedData.materials.length; index++) {
  19556. var parsedMaterial = parsedData.materials[index];
  19557. if (parsedMaterial.id === id) {
  19558. return parseMaterial(parsedMaterial, scene, rootUrl);
  19559. }
  19560. }
  19561. return null;
  19562. };
  19563. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19564. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19565. multiMaterial.id = parsedMultiMaterial.id;
  19566. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19567. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19568. var subMatId = parsedMultiMaterial.materials[matIndex];
  19569. if (subMatId) {
  19570. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19571. }
  19572. else {
  19573. multiMaterial.subMaterials.push(null);
  19574. }
  19575. }
  19576. return multiMaterial;
  19577. };
  19578. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19579. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19580. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19581. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19582. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19583. var parsedFlare = parsedLensFlareSystem.flares[index];
  19584. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19585. }
  19586. return lensFlareSystem;
  19587. };
  19588. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19589. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19590. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19591. if (parsedParticleSystem.textureName) {
  19592. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19593. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19594. }
  19595. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19596. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19597. particleSystem.minSize = parsedParticleSystem.minSize;
  19598. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19599. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19600. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19601. particleSystem.emitter = emitter;
  19602. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19603. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19604. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19605. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19606. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19607. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19608. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19609. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19610. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19611. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19612. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19613. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19614. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19615. particleSystem.start();
  19616. return particleSystem;
  19617. };
  19618. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19619. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19620. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19621. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19622. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19623. shadowGenerator.getShadowMap().renderList.push(mesh);
  19624. }
  19625. if (parsedShadowGenerator.usePoissonSampling) {
  19626. shadowGenerator.usePoissonSampling = true;
  19627. }
  19628. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19629. shadowGenerator.useVarianceShadowMap = true;
  19630. }
  19631. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19632. shadowGenerator.useBlurVarianceShadowMap = true;
  19633. if (parsedShadowGenerator.blurScale) {
  19634. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19635. }
  19636. if (parsedShadowGenerator.blurBoxOffset) {
  19637. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19638. }
  19639. }
  19640. if (parsedShadowGenerator.bias !== undefined) {
  19641. shadowGenerator.bias = parsedShadowGenerator.bias;
  19642. }
  19643. return shadowGenerator;
  19644. };
  19645. var parseAnimation = function (parsedAnimation) {
  19646. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19647. var dataType = parsedAnimation.dataType;
  19648. var keys = [];
  19649. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19650. var key = parsedAnimation.keys[index];
  19651. var data;
  19652. switch (dataType) {
  19653. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19654. data = key.values[0];
  19655. break;
  19656. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19657. data = BABYLON.Quaternion.FromArray(key.values);
  19658. break;
  19659. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19660. data = BABYLON.Matrix.FromArray(key.values);
  19661. break;
  19662. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19663. default:
  19664. data = BABYLON.Vector3.FromArray(key.values);
  19665. break;
  19666. }
  19667. keys.push({
  19668. frame: key.frame,
  19669. value: data
  19670. });
  19671. }
  19672. animation.setKeys(keys);
  19673. return animation;
  19674. };
  19675. var parseLight = function (parsedLight, scene) {
  19676. var light;
  19677. switch (parsedLight.type) {
  19678. case 0:
  19679. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19680. break;
  19681. case 1:
  19682. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19683. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19684. break;
  19685. case 2:
  19686. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19687. break;
  19688. case 3:
  19689. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19690. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19691. break;
  19692. }
  19693. light.id = parsedLight.id;
  19694. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19695. if (parsedLight.intensity !== undefined) {
  19696. light.intensity = parsedLight.intensity;
  19697. }
  19698. if (parsedLight.range) {
  19699. light.range = parsedLight.range;
  19700. }
  19701. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19702. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19703. if (parsedLight.excludedMeshesIds) {
  19704. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19705. }
  19706. // Parent
  19707. if (parsedLight.parentId) {
  19708. light._waitingParentId = parsedLight.parentId;
  19709. }
  19710. if (parsedLight.includedOnlyMeshesIds) {
  19711. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19712. }
  19713. // Animations
  19714. if (parsedLight.animations) {
  19715. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19716. var parsedAnimation = parsedLight.animations[animationIndex];
  19717. light.animations.push(parseAnimation(parsedAnimation));
  19718. }
  19719. }
  19720. if (parsedLight.autoAnimate) {
  19721. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19722. }
  19723. };
  19724. var parseCamera = function (parsedCamera, scene) {
  19725. var camera;
  19726. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19727. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19728. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19729. var alpha = parsedCamera.alpha;
  19730. var beta = parsedCamera.beta;
  19731. var radius = parsedCamera.radius;
  19732. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19733. var interaxial_distance = parsedCamera.interaxial_distance;
  19734. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19735. }
  19736. else {
  19737. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19738. }
  19739. }
  19740. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19741. interaxial_distance = parsedCamera.interaxial_distance;
  19742. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19743. }
  19744. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19745. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19746. }
  19747. else if (parsedCamera.type === "FollowCamera") {
  19748. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19749. camera.heightOffset = parsedCamera.heightOffset;
  19750. camera.radius = parsedCamera.radius;
  19751. camera.rotationOffset = parsedCamera.rotationOffset;
  19752. if (lockedTargetMesh)
  19753. camera.target = lockedTargetMesh;
  19754. }
  19755. else if (parsedCamera.type === "GamepadCamera") {
  19756. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19757. }
  19758. else if (parsedCamera.type === "TouchCamera") {
  19759. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19760. }
  19761. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19762. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19763. }
  19764. else if (parsedCamera.type === "WebVRFreeCamera") {
  19765. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19766. }
  19767. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19768. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19769. }
  19770. else {
  19771. // Free Camera is the default value
  19772. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19773. }
  19774. // apply 3d rig, when found
  19775. if (parsedCamera.cameraRigMode) {
  19776. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19777. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19778. }
  19779. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19780. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19781. camera.lockedTarget = lockedTargetMesh;
  19782. }
  19783. camera.id = parsedCamera.id;
  19784. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19785. // Parent
  19786. if (parsedCamera.parentId) {
  19787. camera._waitingParentId = parsedCamera.parentId;
  19788. }
  19789. // Target
  19790. if (parsedCamera.target) {
  19791. if (camera.setTarget) {
  19792. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19793. }
  19794. else {
  19795. //For ArcRotate
  19796. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19797. }
  19798. }
  19799. else {
  19800. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19801. }
  19802. camera.fov = parsedCamera.fov;
  19803. camera.minZ = parsedCamera.minZ;
  19804. camera.maxZ = parsedCamera.maxZ;
  19805. camera.speed = parsedCamera.speed;
  19806. camera.inertia = parsedCamera.inertia;
  19807. camera.checkCollisions = parsedCamera.checkCollisions;
  19808. camera.applyGravity = parsedCamera.applyGravity;
  19809. if (parsedCamera.ellipsoid) {
  19810. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19811. }
  19812. // Animations
  19813. if (parsedCamera.animations) {
  19814. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19815. var parsedAnimation = parsedCamera.animations[animationIndex];
  19816. camera.animations.push(parseAnimation(parsedAnimation));
  19817. }
  19818. }
  19819. if (parsedCamera.autoAnimate) {
  19820. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19821. }
  19822. // Layer Mask
  19823. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19824. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19825. }
  19826. else {
  19827. camera.layerMask = 0x0FFFFFFF;
  19828. }
  19829. return camera;
  19830. };
  19831. var parseGeometry = function (parsedGeometry, scene) {
  19832. var id = parsedGeometry.id;
  19833. return scene.getGeometryByID(id);
  19834. };
  19835. var parseBox = function (parsedBox, scene) {
  19836. if (parseGeometry(parsedBox, scene)) {
  19837. return null; // null since geometry could be something else than a box...
  19838. }
  19839. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19840. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19841. scene.pushGeometry(box, true);
  19842. return box;
  19843. };
  19844. var parseSphere = function (parsedSphere, scene) {
  19845. if (parseGeometry(parsedSphere, scene)) {
  19846. return null; // null since geometry could be something else than a sphere...
  19847. }
  19848. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19849. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19850. scene.pushGeometry(sphere, true);
  19851. return sphere;
  19852. };
  19853. var parseCylinder = function (parsedCylinder, scene) {
  19854. if (parseGeometry(parsedCylinder, scene)) {
  19855. return null; // null since geometry could be something else than a cylinder...
  19856. }
  19857. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19858. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19859. scene.pushGeometry(cylinder, true);
  19860. return cylinder;
  19861. };
  19862. var parseTorus = function (parsedTorus, scene) {
  19863. if (parseGeometry(parsedTorus, scene)) {
  19864. return null; // null since geometry could be something else than a torus...
  19865. }
  19866. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19867. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19868. scene.pushGeometry(torus, true);
  19869. return torus;
  19870. };
  19871. var parseGround = function (parsedGround, scene) {
  19872. if (parseGeometry(parsedGround, scene)) {
  19873. return null; // null since geometry could be something else than a ground...
  19874. }
  19875. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19876. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19877. scene.pushGeometry(ground, true);
  19878. return ground;
  19879. };
  19880. var parsePlane = function (parsedPlane, scene) {
  19881. if (parseGeometry(parsedPlane, scene)) {
  19882. return null; // null since geometry could be something else than a plane...
  19883. }
  19884. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19885. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19886. scene.pushGeometry(plane, true);
  19887. return plane;
  19888. };
  19889. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19890. if (parseGeometry(parsedTorusKnot, scene)) {
  19891. return null; // null since geometry could be something else than a torusKnot...
  19892. }
  19893. 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);
  19894. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19895. scene.pushGeometry(torusKnot, true);
  19896. return torusKnot;
  19897. };
  19898. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19899. if (parseGeometry(parsedVertexData, scene)) {
  19900. return null; // null since geometry could be a primitive
  19901. }
  19902. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19903. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19904. if (parsedVertexData.delayLoadingFile) {
  19905. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19906. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19907. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19908. geometry._delayInfo = [];
  19909. if (parsedVertexData.hasUVs) {
  19910. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19911. }
  19912. if (parsedVertexData.hasUVs2) {
  19913. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19914. }
  19915. if (parsedVertexData.hasUVs3) {
  19916. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19917. }
  19918. if (parsedVertexData.hasUVs4) {
  19919. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19920. }
  19921. if (parsedVertexData.hasUVs5) {
  19922. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19923. }
  19924. if (parsedVertexData.hasUVs6) {
  19925. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19926. }
  19927. if (parsedVertexData.hasColors) {
  19928. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19929. }
  19930. if (parsedVertexData.hasMatricesIndices) {
  19931. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19932. }
  19933. if (parsedVertexData.hasMatricesWeights) {
  19934. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19935. }
  19936. geometry._delayLoadingFunction = importVertexData;
  19937. }
  19938. else {
  19939. importVertexData(parsedVertexData, geometry);
  19940. }
  19941. scene.pushGeometry(geometry, true);
  19942. return geometry;
  19943. };
  19944. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19945. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19946. mesh.id = parsedMesh.id;
  19947. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19948. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19949. if (parsedMesh.rotationQuaternion) {
  19950. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19951. }
  19952. else if (parsedMesh.rotation) {
  19953. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19954. }
  19955. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19956. if (parsedMesh.localMatrix) {
  19957. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19958. }
  19959. else if (parsedMesh.pivotMatrix) {
  19960. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19961. }
  19962. mesh.setEnabled(parsedMesh.isEnabled);
  19963. mesh.isVisible = parsedMesh.isVisible;
  19964. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19965. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19966. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19967. if (parsedMesh.applyFog !== undefined) {
  19968. mesh.applyFog = parsedMesh.applyFog;
  19969. }
  19970. if (parsedMesh.pickable !== undefined) {
  19971. mesh.isPickable = parsedMesh.pickable;
  19972. }
  19973. if (parsedMesh.alphaIndex !== undefined) {
  19974. mesh.alphaIndex = parsedMesh.alphaIndex;
  19975. }
  19976. mesh.receiveShadows = parsedMesh.receiveShadows;
  19977. mesh.billboardMode = parsedMesh.billboardMode;
  19978. if (parsedMesh.visibility !== undefined) {
  19979. mesh.visibility = parsedMesh.visibility;
  19980. }
  19981. mesh.checkCollisions = parsedMesh.checkCollisions;
  19982. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19983. // freezeWorldMatrix
  19984. if (parsedMesh.freezeWorldMatrix) {
  19985. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19986. }
  19987. // Parent
  19988. if (parsedMesh.parentId) {
  19989. mesh._waitingParentId = parsedMesh.parentId;
  19990. }
  19991. // Actions
  19992. if (parsedMesh.actions !== undefined) {
  19993. mesh._waitingActions = parsedMesh.actions;
  19994. }
  19995. // Geometry
  19996. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19997. if (parsedMesh.delayLoadingFile) {
  19998. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19999. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20000. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20001. if (parsedMesh._binaryInfo) {
  20002. mesh._binaryInfo = parsedMesh._binaryInfo;
  20003. }
  20004. mesh._delayInfo = [];
  20005. if (parsedMesh.hasUVs) {
  20006. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20007. }
  20008. if (parsedMesh.hasUVs2) {
  20009. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20010. }
  20011. if (parsedMesh.hasUVs3) {
  20012. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20013. }
  20014. if (parsedMesh.hasUVs4) {
  20015. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20016. }
  20017. if (parsedMesh.hasUVs5) {
  20018. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20019. }
  20020. if (parsedMesh.hasUVs6) {
  20021. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20022. }
  20023. if (parsedMesh.hasColors) {
  20024. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20025. }
  20026. if (parsedMesh.hasMatricesIndices) {
  20027. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20028. }
  20029. if (parsedMesh.hasMatricesWeights) {
  20030. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20031. }
  20032. mesh._delayLoadingFunction = importGeometry;
  20033. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20034. mesh._checkDelayState();
  20035. }
  20036. }
  20037. else {
  20038. importGeometry(parsedMesh, mesh);
  20039. }
  20040. // Material
  20041. if (parsedMesh.materialId) {
  20042. mesh.setMaterialByID(parsedMesh.materialId);
  20043. }
  20044. else {
  20045. mesh.material = null;
  20046. }
  20047. // Skeleton
  20048. if (parsedMesh.skeletonId > -1) {
  20049. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20050. }
  20051. // Physics
  20052. if (parsedMesh.physicsImpostor) {
  20053. if (!scene.isPhysicsEnabled()) {
  20054. scene.enablePhysics();
  20055. }
  20056. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20057. }
  20058. // Animations
  20059. if (parsedMesh.animations) {
  20060. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20061. var parsedAnimation = parsedMesh.animations[animationIndex];
  20062. mesh.animations.push(parseAnimation(parsedAnimation));
  20063. }
  20064. }
  20065. if (parsedMesh.autoAnimate) {
  20066. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20067. }
  20068. // Layer Mask
  20069. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20070. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20071. }
  20072. else {
  20073. mesh.layerMask = 0x0FFFFFFF;
  20074. }
  20075. // Instances
  20076. if (parsedMesh.instances) {
  20077. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20078. var parsedInstance = parsedMesh.instances[index];
  20079. var instance = mesh.createInstance(parsedInstance.name);
  20080. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20081. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20082. if (parsedInstance.rotationQuaternion) {
  20083. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20084. }
  20085. else if (parsedInstance.rotation) {
  20086. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20087. }
  20088. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20089. instance.checkCollisions = mesh.checkCollisions;
  20090. if (parsedMesh.animations) {
  20091. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20092. parsedAnimation = parsedMesh.animations[animationIndex];
  20093. instance.animations.push(parseAnimation(parsedAnimation));
  20094. }
  20095. }
  20096. }
  20097. }
  20098. return mesh;
  20099. };
  20100. var parseActions = function (parsedActions, object, scene) {
  20101. var actionManager = new BABYLON.ActionManager(scene);
  20102. if (object === null)
  20103. scene.actionManager = actionManager;
  20104. else
  20105. object.actionManager = actionManager;
  20106. // instanciate a new object
  20107. var instanciate = function (name, params) {
  20108. var newInstance = Object.create(BABYLON[name].prototype);
  20109. newInstance.constructor.apply(newInstance, params);
  20110. return newInstance;
  20111. };
  20112. var parseParameter = function (name, value, target, propertyPath) {
  20113. if (propertyPath === null) {
  20114. // String, boolean or float
  20115. var floatValue = parseFloat(value);
  20116. if (value === "true" || value === "false")
  20117. return value === "true";
  20118. else
  20119. return isNaN(floatValue) ? value : floatValue;
  20120. }
  20121. var effectiveTarget = propertyPath.split(".");
  20122. var values = value.split(",");
  20123. // Get effective Target
  20124. for (var i = 0; i < effectiveTarget.length; i++) {
  20125. target = target[effectiveTarget[i]];
  20126. }
  20127. // Return appropriate value with its type
  20128. if (typeof (target) === "boolean")
  20129. return values[0] === "true";
  20130. if (typeof (target) === "string")
  20131. return values[0];
  20132. // Parameters with multiple values such as Vector3 etc.
  20133. var split = new Array();
  20134. for (var i = 0; i < values.length; i++)
  20135. split.push(parseFloat(values[i]));
  20136. if (target instanceof BABYLON.Vector3)
  20137. return BABYLON.Vector3.FromArray(split);
  20138. if (target instanceof BABYLON.Vector4)
  20139. return BABYLON.Vector4.FromArray(split);
  20140. if (target instanceof BABYLON.Color3)
  20141. return BABYLON.Color3.FromArray(split);
  20142. if (target instanceof BABYLON.Color4)
  20143. return BABYLON.Color4.FromArray(split);
  20144. return parseFloat(values[0]);
  20145. };
  20146. // traverse graph per trigger
  20147. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20148. if (combineArray === void 0) { combineArray = null; }
  20149. if (parsedAction.detached)
  20150. return;
  20151. var parameters = new Array();
  20152. var target = null;
  20153. var propertyPath = null;
  20154. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20155. // Parameters
  20156. if (parsedAction.type === 2)
  20157. parameters.push(actionManager);
  20158. else
  20159. parameters.push(trigger);
  20160. if (combine) {
  20161. var actions = new Array();
  20162. for (var j = 0; j < parsedAction.combine.length; j++) {
  20163. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20164. }
  20165. parameters.push(actions);
  20166. }
  20167. else {
  20168. for (var i = 0; i < parsedAction.properties.length; i++) {
  20169. var value = parsedAction.properties[i].value;
  20170. var name = parsedAction.properties[i].name;
  20171. var targetType = parsedAction.properties[i].targetType;
  20172. if (name === "target")
  20173. if (targetType !== null && targetType === "SceneProperties")
  20174. value = target = scene;
  20175. else
  20176. value = target = scene.getNodeByName(value);
  20177. else if (name === "parent")
  20178. value = scene.getNodeByName(value);
  20179. else if (name === "sound")
  20180. value = scene.getSoundByName(value);
  20181. else if (name !== "propertyPath") {
  20182. if (parsedAction.type === 2 && name === "operator")
  20183. value = BABYLON.ValueCondition[value];
  20184. else
  20185. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20186. }
  20187. else {
  20188. propertyPath = value;
  20189. }
  20190. parameters.push(value);
  20191. }
  20192. }
  20193. if (combineArray === null) {
  20194. parameters.push(condition);
  20195. }
  20196. else {
  20197. parameters.push(null);
  20198. }
  20199. // If interpolate value action
  20200. if (parsedAction.name === "InterpolateValueAction") {
  20201. var param = parameters[parameters.length - 2];
  20202. parameters[parameters.length - 1] = param;
  20203. parameters[parameters.length - 2] = condition;
  20204. }
  20205. // Action or condition(s) and not CombineAction
  20206. var newAction = instanciate(parsedAction.name, parameters);
  20207. if (combineArray === null) {
  20208. if (newAction instanceof BABYLON.Condition) {
  20209. condition = newAction;
  20210. newAction = action;
  20211. }
  20212. else {
  20213. condition = null;
  20214. if (action)
  20215. action.then(newAction);
  20216. else
  20217. actionManager.registerAction(newAction);
  20218. }
  20219. }
  20220. else {
  20221. combineArray.push(newAction);
  20222. }
  20223. for (var i = 0; i < parsedAction.children.length; i++)
  20224. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20225. };
  20226. // triggers
  20227. for (var i = 0; i < parsedActions.children.length; i++) {
  20228. var triggerParams;
  20229. var trigger = parsedActions.children[i];
  20230. if (trigger.properties.length > 0) {
  20231. var param = trigger.properties[0].value;
  20232. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20233. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20234. }
  20235. else
  20236. triggerParams = BABYLON.ActionManager[trigger.name];
  20237. for (var j = 0; j < trigger.children.length; j++) {
  20238. if (!trigger.detached)
  20239. traverse(trigger.children[j], triggerParams, null, null);
  20240. }
  20241. }
  20242. };
  20243. var parseSound = function (parsedSound, scene, rootUrl) {
  20244. var soundName = parsedSound.name;
  20245. var soundUrl = rootUrl + soundName;
  20246. var options = {
  20247. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20248. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20249. rolloffFactor: parsedSound.rolloffFactor,
  20250. refDistance: parsedSound.refDistance,
  20251. distanceModel: parsedSound.distanceModel,
  20252. playbackRate: parsedSound.playbackRate
  20253. };
  20254. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20255. scene._addPendingData(newSound);
  20256. if (parsedSound.position) {
  20257. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20258. newSound.setPosition(soundPosition);
  20259. }
  20260. if (parsedSound.isDirectional) {
  20261. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20262. if (parsedSound.localDirectionToMesh) {
  20263. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20264. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20265. }
  20266. }
  20267. if (parsedSound.connectedMeshId) {
  20268. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20269. if (connectedMesh) {
  20270. newSound.attachToMesh(connectedMesh);
  20271. }
  20272. }
  20273. };
  20274. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20275. names = (names instanceof Array) ? names : [names];
  20276. for (var i in names) {
  20277. if (mesh.name === names[i]) {
  20278. hierarchyIds.push(mesh.id);
  20279. return true;
  20280. }
  20281. }
  20282. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20283. hierarchyIds.push(mesh.id);
  20284. return true;
  20285. }
  20286. return false;
  20287. };
  20288. var importVertexData = function (parsedVertexData, geometry) {
  20289. var vertexData = new BABYLON.VertexData();
  20290. // positions
  20291. var positions = parsedVertexData.positions;
  20292. if (positions) {
  20293. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20294. }
  20295. // normals
  20296. var normals = parsedVertexData.normals;
  20297. if (normals) {
  20298. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20299. }
  20300. // uvs
  20301. var uvs = parsedVertexData.uvs;
  20302. if (uvs) {
  20303. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20304. }
  20305. // uv2s
  20306. var uv2s = parsedVertexData.uv2s;
  20307. if (uv2s) {
  20308. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20309. }
  20310. // uv3s
  20311. var uv3s = parsedVertexData.uv3s;
  20312. if (uv3s) {
  20313. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20314. }
  20315. // uv4s
  20316. var uv4s = parsedVertexData.uv4s;
  20317. if (uv4s) {
  20318. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20319. }
  20320. // uv5s
  20321. var uv5s = parsedVertexData.uv5s;
  20322. if (uv5s) {
  20323. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20324. }
  20325. // uv6s
  20326. var uv6s = parsedVertexData.uv6s;
  20327. if (uv6s) {
  20328. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20329. }
  20330. // colors
  20331. var colors = parsedVertexData.colors;
  20332. if (colors) {
  20333. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20334. }
  20335. // matricesIndices
  20336. var matricesIndices = parsedVertexData.matricesIndices;
  20337. if (matricesIndices) {
  20338. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20339. }
  20340. // matricesWeights
  20341. var matricesWeights = parsedVertexData.matricesWeights;
  20342. if (matricesWeights) {
  20343. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20344. }
  20345. // indices
  20346. var indices = parsedVertexData.indices;
  20347. if (indices) {
  20348. vertexData.indices = indices;
  20349. }
  20350. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20351. };
  20352. var importGeometry = function (parsedGeometry, mesh) {
  20353. var scene = mesh.getScene();
  20354. // Geometry
  20355. var geometryId = parsedGeometry.geometryId;
  20356. if (geometryId) {
  20357. var geometry = scene.getGeometryByID(geometryId);
  20358. if (geometry) {
  20359. geometry.applyToMesh(mesh);
  20360. }
  20361. }
  20362. else if (parsedGeometry instanceof ArrayBuffer) {
  20363. var binaryInfo = mesh._binaryInfo;
  20364. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20365. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20366. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20367. }
  20368. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20369. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20370. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20371. }
  20372. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20373. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20374. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20375. }
  20376. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20377. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20378. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20379. }
  20380. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20381. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20382. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20383. }
  20384. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20385. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20386. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20387. }
  20388. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20389. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20390. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20391. }
  20392. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20393. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20394. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20395. }
  20396. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20397. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20398. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20399. }
  20400. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20401. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20402. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20403. }
  20404. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20405. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20406. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20407. }
  20408. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20409. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20410. mesh.setIndices(indicesData);
  20411. }
  20412. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20413. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20414. mesh.subMeshes = [];
  20415. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20416. var materialIndex = subMeshesData[(i * 5) + 0];
  20417. var verticesStart = subMeshesData[(i * 5) + 1];
  20418. var verticesCount = subMeshesData[(i * 5) + 2];
  20419. var indexStart = subMeshesData[(i * 5) + 3];
  20420. var indexCount = subMeshesData[(i * 5) + 4];
  20421. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20422. }
  20423. }
  20424. }
  20425. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20426. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20427. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20428. if (parsedGeometry.uvs) {
  20429. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20430. }
  20431. if (parsedGeometry.uvs2) {
  20432. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20433. }
  20434. if (parsedGeometry.uvs3) {
  20435. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20436. }
  20437. if (parsedGeometry.uvs4) {
  20438. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20439. }
  20440. if (parsedGeometry.uvs5) {
  20441. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20442. }
  20443. if (parsedGeometry.uvs6) {
  20444. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20445. }
  20446. if (parsedGeometry.colors) {
  20447. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20448. }
  20449. if (parsedGeometry.matricesIndices) {
  20450. if (!parsedGeometry.matricesIndices._isExpanded) {
  20451. var floatIndices = [];
  20452. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20453. var matricesIndex = parsedGeometry.matricesIndices[i];
  20454. floatIndices.push(matricesIndex & 0x000000FF);
  20455. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20456. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20457. floatIndices.push(matricesIndex >> 24);
  20458. }
  20459. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20460. }
  20461. else {
  20462. delete parsedGeometry.matricesIndices._isExpanded;
  20463. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20464. }
  20465. }
  20466. if (parsedGeometry.matricesWeights) {
  20467. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20468. }
  20469. mesh.setIndices(parsedGeometry.indices);
  20470. }
  20471. // SubMeshes
  20472. if (parsedGeometry.subMeshes) {
  20473. mesh.subMeshes = [];
  20474. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20475. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20476. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20477. }
  20478. }
  20479. // Flat shading
  20480. if (mesh._shouldGenerateFlatShading) {
  20481. mesh.convertToFlatShadedMesh();
  20482. delete mesh._shouldGenerateFlatShading;
  20483. }
  20484. // Update
  20485. mesh.computeWorldMatrix(true);
  20486. // Octree
  20487. if (scene._selectionOctree) {
  20488. scene._selectionOctree.addMesh(mesh);
  20489. }
  20490. };
  20491. BABYLON.SceneLoader.RegisterPlugin({
  20492. extensions: ".babylon",
  20493. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20494. var parsedData = JSON.parse(data);
  20495. var loadedSkeletonsIds = [];
  20496. var loadedMaterialsIds = [];
  20497. var hierarchyIds = [];
  20498. for (var index = 0; index < parsedData.meshes.length; index++) {
  20499. var parsedMesh = parsedData.meshes[index];
  20500. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20501. if (meshesNames instanceof Array) {
  20502. // Remove found mesh name from list.
  20503. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20504. }
  20505. //Geometry?
  20506. if (parsedMesh.geometryId) {
  20507. //does the file contain geometries?
  20508. if (parsedData.geometries) {
  20509. //find the correct geometry and add it to the scene
  20510. var found = false;
  20511. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20512. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20513. return;
  20514. }
  20515. else {
  20516. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20517. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20518. switch (geometryType) {
  20519. case "boxes":
  20520. parseBox(parsedGeometryData, scene);
  20521. break;
  20522. case "spheres":
  20523. parseSphere(parsedGeometryData, scene);
  20524. break;
  20525. case "cylinders":
  20526. parseCylinder(parsedGeometryData, scene);
  20527. break;
  20528. case "toruses":
  20529. parseTorus(parsedGeometryData, scene);
  20530. break;
  20531. case "grounds":
  20532. parseGround(parsedGeometryData, scene);
  20533. break;
  20534. case "planes":
  20535. parsePlane(parsedGeometryData, scene);
  20536. break;
  20537. case "torusKnots":
  20538. parseTorusKnot(parsedGeometryData, scene);
  20539. break;
  20540. case "vertexData":
  20541. parseVertexData(parsedGeometryData, scene, rootUrl);
  20542. break;
  20543. }
  20544. found = true;
  20545. }
  20546. });
  20547. }
  20548. });
  20549. if (!found) {
  20550. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20551. }
  20552. }
  20553. }
  20554. // Material ?
  20555. if (parsedMesh.materialId) {
  20556. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20557. if (!materialFound && parsedData.multiMaterials) {
  20558. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20559. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20560. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20561. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20562. var subMatId = parsedMultiMaterial.materials[matIndex];
  20563. loadedMaterialsIds.push(subMatId);
  20564. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20565. }
  20566. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20567. parseMultiMaterial(parsedMultiMaterial, scene);
  20568. materialFound = true;
  20569. break;
  20570. }
  20571. }
  20572. }
  20573. if (!materialFound) {
  20574. loadedMaterialsIds.push(parsedMesh.materialId);
  20575. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20576. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20577. }
  20578. }
  20579. }
  20580. // Skeleton ?
  20581. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20582. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20583. if (!skeletonAlreadyLoaded) {
  20584. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20585. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20586. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20587. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20588. loadedSkeletonsIds.push(parsedSkeleton.id);
  20589. }
  20590. }
  20591. }
  20592. }
  20593. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20594. meshes.push(mesh);
  20595. }
  20596. }
  20597. // Connecting parents
  20598. for (index = 0; index < scene.meshes.length; index++) {
  20599. var currentMesh = scene.meshes[index];
  20600. if (currentMesh._waitingParentId) {
  20601. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20602. currentMesh._waitingParentId = undefined;
  20603. }
  20604. }
  20605. // freeze world matrix application
  20606. for (index = 0; index < scene.meshes.length; index++) {
  20607. var currentMesh = scene.meshes[index];
  20608. if (currentMesh._waitingFreezeWorldMatrix) {
  20609. currentMesh.freezeWorldMatrix();
  20610. currentMesh._waitingFreezeWorldMatrix = undefined;
  20611. }
  20612. }
  20613. // Particles
  20614. if (parsedData.particleSystems) {
  20615. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20616. var parsedParticleSystem = parsedData.particleSystems[index];
  20617. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20618. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20619. }
  20620. }
  20621. }
  20622. return true;
  20623. },
  20624. load: function (scene, data, rootUrl) {
  20625. var parsedData = JSON.parse(data);
  20626. // Scene
  20627. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20628. scene.autoClear = parsedData.autoClear;
  20629. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20630. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20631. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20632. // Fog
  20633. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20634. scene.fogMode = parsedData.fogMode;
  20635. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20636. scene.fogStart = parsedData.fogStart;
  20637. scene.fogEnd = parsedData.fogEnd;
  20638. scene.fogDensity = parsedData.fogDensity;
  20639. }
  20640. // Lights
  20641. for (var index = 0; index < parsedData.lights.length; index++) {
  20642. var parsedLight = parsedData.lights[index];
  20643. parseLight(parsedLight, scene);
  20644. }
  20645. // Materials
  20646. if (parsedData.materials) {
  20647. for (index = 0; index < parsedData.materials.length; index++) {
  20648. var parsedMaterial = parsedData.materials[index];
  20649. parseMaterial(parsedMaterial, scene, rootUrl);
  20650. }
  20651. }
  20652. if (parsedData.multiMaterials) {
  20653. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20654. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20655. parseMultiMaterial(parsedMultiMaterial, scene);
  20656. }
  20657. }
  20658. // Skeletons
  20659. if (parsedData.skeletons) {
  20660. for (index = 0; index < parsedData.skeletons.length; index++) {
  20661. var parsedSkeleton = parsedData.skeletons[index];
  20662. parseSkeleton(parsedSkeleton, scene);
  20663. }
  20664. }
  20665. // Geometries
  20666. var geometries = parsedData.geometries;
  20667. if (geometries) {
  20668. // Boxes
  20669. var boxes = geometries.boxes;
  20670. if (boxes) {
  20671. for (index = 0; index < boxes.length; index++) {
  20672. var parsedBox = boxes[index];
  20673. parseBox(parsedBox, scene);
  20674. }
  20675. }
  20676. // Spheres
  20677. var spheres = geometries.spheres;
  20678. if (spheres) {
  20679. for (index = 0; index < spheres.length; index++) {
  20680. var parsedSphere = spheres[index];
  20681. parseSphere(parsedSphere, scene);
  20682. }
  20683. }
  20684. // Cylinders
  20685. var cylinders = geometries.cylinders;
  20686. if (cylinders) {
  20687. for (index = 0; index < cylinders.length; index++) {
  20688. var parsedCylinder = cylinders[index];
  20689. parseCylinder(parsedCylinder, scene);
  20690. }
  20691. }
  20692. // Toruses
  20693. var toruses = geometries.toruses;
  20694. if (toruses) {
  20695. for (index = 0; index < toruses.length; index++) {
  20696. var parsedTorus = toruses[index];
  20697. parseTorus(parsedTorus, scene);
  20698. }
  20699. }
  20700. // Grounds
  20701. var grounds = geometries.grounds;
  20702. if (grounds) {
  20703. for (index = 0; index < grounds.length; index++) {
  20704. var parsedGround = grounds[index];
  20705. parseGround(parsedGround, scene);
  20706. }
  20707. }
  20708. // Planes
  20709. var planes = geometries.planes;
  20710. if (planes) {
  20711. for (index = 0; index < planes.length; index++) {
  20712. var parsedPlane = planes[index];
  20713. parsePlane(parsedPlane, scene);
  20714. }
  20715. }
  20716. // TorusKnots
  20717. var torusKnots = geometries.torusKnots;
  20718. if (torusKnots) {
  20719. for (index = 0; index < torusKnots.length; index++) {
  20720. var parsedTorusKnot = torusKnots[index];
  20721. parseTorusKnot(parsedTorusKnot, scene);
  20722. }
  20723. }
  20724. // VertexData
  20725. var vertexData = geometries.vertexData;
  20726. if (vertexData) {
  20727. for (index = 0; index < vertexData.length; index++) {
  20728. var parsedVertexData = vertexData[index];
  20729. parseVertexData(parsedVertexData, scene, rootUrl);
  20730. }
  20731. }
  20732. }
  20733. // Meshes
  20734. for (index = 0; index < parsedData.meshes.length; index++) {
  20735. var parsedMesh = parsedData.meshes[index];
  20736. parseMesh(parsedMesh, scene, rootUrl);
  20737. }
  20738. // Cameras
  20739. for (index = 0; index < parsedData.cameras.length; index++) {
  20740. var parsedCamera = parsedData.cameras[index];
  20741. parseCamera(parsedCamera, scene);
  20742. }
  20743. if (parsedData.activeCameraID) {
  20744. scene.setActiveCameraByID(parsedData.activeCameraID);
  20745. }
  20746. // Browsing all the graph to connect the dots
  20747. for (index = 0; index < scene.cameras.length; index++) {
  20748. var camera = scene.cameras[index];
  20749. if (camera._waitingParentId) {
  20750. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20751. camera._waitingParentId = undefined;
  20752. }
  20753. }
  20754. for (index = 0; index < scene.lights.length; index++) {
  20755. var light = scene.lights[index];
  20756. if (light._waitingParentId) {
  20757. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20758. light._waitingParentId = undefined;
  20759. }
  20760. }
  20761. // Sounds
  20762. if (parsedData.sounds) {
  20763. for (index = 0; index < parsedData.sounds.length; index++) {
  20764. var parsedSound = parsedData.sounds[index];
  20765. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20766. parseSound(parsedSound, scene, rootUrl);
  20767. }
  20768. else {
  20769. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20770. }
  20771. }
  20772. }
  20773. // Connect parents & children and parse actions
  20774. for (index = 0; index < scene.meshes.length; index++) {
  20775. var mesh = scene.meshes[index];
  20776. if (mesh._waitingParentId) {
  20777. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20778. mesh._waitingParentId = undefined;
  20779. }
  20780. if (mesh._waitingActions) {
  20781. parseActions(mesh._waitingActions, mesh, scene);
  20782. mesh._waitingActions = undefined;
  20783. }
  20784. }
  20785. // freeze world matrix application
  20786. for (index = 0; index < scene.meshes.length; index++) {
  20787. var currentMesh = scene.meshes[index];
  20788. if (currentMesh._waitingFreezeWorldMatrix) {
  20789. currentMesh.freezeWorldMatrix();
  20790. currentMesh._waitingFreezeWorldMatrix = undefined;
  20791. }
  20792. }
  20793. // Particles Systems
  20794. if (parsedData.particleSystems) {
  20795. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20796. var parsedParticleSystem = parsedData.particleSystems[index];
  20797. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20798. }
  20799. }
  20800. // Lens flares
  20801. if (parsedData.lensFlareSystems) {
  20802. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20803. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20804. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20805. }
  20806. }
  20807. // Shadows
  20808. if (parsedData.shadowGenerators) {
  20809. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20810. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20811. parseShadowGenerator(parsedShadowGenerator, scene);
  20812. }
  20813. }
  20814. // Actions (scene)
  20815. if (parsedData.actions) {
  20816. parseActions(parsedData.actions, null, scene);
  20817. }
  20818. // Finish
  20819. return true;
  20820. }
  20821. });
  20822. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20823. })(BABYLON || (BABYLON = {}));
  20824. var BABYLON;
  20825. (function (BABYLON) {
  20826. var SpriteManager = (function () {
  20827. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20829. this.name = name;
  20830. this.cellSize = cellSize;
  20831. this.sprites = new Array();
  20832. this.renderingGroupId = 0;
  20833. this.fogEnabled = true;
  20834. this._vertexDeclaration = [4, 4, 4, 4];
  20835. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20836. this._capacity = capacity;
  20837. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20838. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20839. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20840. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20841. this._scene = scene;
  20842. this._scene.spriteManagers.push(this);
  20843. // VBO
  20844. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20845. var indices = [];
  20846. var index = 0;
  20847. for (var count = 0; count < capacity; count++) {
  20848. indices.push(index);
  20849. indices.push(index + 1);
  20850. indices.push(index + 2);
  20851. indices.push(index);
  20852. indices.push(index + 2);
  20853. indices.push(index + 3);
  20854. index += 4;
  20855. }
  20856. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20857. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20858. // Effects
  20859. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20860. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20861. }
  20862. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20863. var arrayOffset = index * 16;
  20864. if (offsetX === 0)
  20865. offsetX = this._epsilon;
  20866. else if (offsetX === 1)
  20867. offsetX = 1 - this._epsilon;
  20868. if (offsetY === 0)
  20869. offsetY = this._epsilon;
  20870. else if (offsetY === 1)
  20871. offsetY = 1 - this._epsilon;
  20872. this._vertices[arrayOffset] = sprite.position.x;
  20873. this._vertices[arrayOffset + 1] = sprite.position.y;
  20874. this._vertices[arrayOffset + 2] = sprite.position.z;
  20875. this._vertices[arrayOffset + 3] = sprite.angle;
  20876. this._vertices[arrayOffset + 4] = sprite.width;
  20877. this._vertices[arrayOffset + 5] = sprite.height;
  20878. this._vertices[arrayOffset + 6] = offsetX;
  20879. this._vertices[arrayOffset + 7] = offsetY;
  20880. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20881. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20882. var offset = (sprite.cellIndex / rowSize) >> 0;
  20883. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20884. this._vertices[arrayOffset + 11] = offset;
  20885. // Color
  20886. this._vertices[arrayOffset + 12] = sprite.color.r;
  20887. this._vertices[arrayOffset + 13] = sprite.color.g;
  20888. this._vertices[arrayOffset + 14] = sprite.color.b;
  20889. this._vertices[arrayOffset + 15] = sprite.color.a;
  20890. };
  20891. SpriteManager.prototype.render = function () {
  20892. // Check
  20893. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20894. return;
  20895. var engine = this._scene.getEngine();
  20896. var baseSize = this._spriteTexture.getBaseSize();
  20897. // Sprites
  20898. var deltaTime = engine.getDeltaTime();
  20899. var max = Math.min(this._capacity, this.sprites.length);
  20900. var rowSize = baseSize.width / this.cellSize;
  20901. var offset = 0;
  20902. for (var index = 0; index < max; index++) {
  20903. var sprite = this.sprites[index];
  20904. if (!sprite) {
  20905. continue;
  20906. }
  20907. sprite._animate(deltaTime);
  20908. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20909. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20910. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20911. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20912. }
  20913. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20914. // Render
  20915. var effect = this._effectBase;
  20916. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20917. effect = this._effectFog;
  20918. }
  20919. engine.enableEffect(effect);
  20920. var viewMatrix = this._scene.getViewMatrix();
  20921. effect.setTexture("diffuseSampler", this._spriteTexture);
  20922. effect.setMatrix("view", viewMatrix);
  20923. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20924. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20925. // Fog
  20926. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20927. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20928. effect.setColor3("vFogColor", this._scene.fogColor);
  20929. }
  20930. // VBOs
  20931. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20932. // Draw order
  20933. engine.setDepthFunctionToLessOrEqual();
  20934. effect.setBool("alphaTest", true);
  20935. engine.setColorWrite(false);
  20936. engine.draw(true, 0, max * 6);
  20937. engine.setColorWrite(true);
  20938. effect.setBool("alphaTest", false);
  20939. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20940. engine.draw(true, 0, max * 6);
  20941. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20942. };
  20943. SpriteManager.prototype.dispose = function () {
  20944. if (this._vertexBuffer) {
  20945. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20946. this._vertexBuffer = null;
  20947. }
  20948. if (this._indexBuffer) {
  20949. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20950. this._indexBuffer = null;
  20951. }
  20952. if (this._spriteTexture) {
  20953. this._spriteTexture.dispose();
  20954. this._spriteTexture = null;
  20955. }
  20956. // Remove from scene
  20957. var index = this._scene.spriteManagers.indexOf(this);
  20958. this._scene.spriteManagers.splice(index, 1);
  20959. // Callback
  20960. if (this.onDispose) {
  20961. this.onDispose();
  20962. }
  20963. };
  20964. return SpriteManager;
  20965. })();
  20966. BABYLON.SpriteManager = SpriteManager;
  20967. })(BABYLON || (BABYLON = {}));
  20968. var BABYLON;
  20969. (function (BABYLON) {
  20970. var Sprite = (function () {
  20971. function Sprite(name, manager) {
  20972. this.name = name;
  20973. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20974. this.width = 1.0;
  20975. this.height = 1.0;
  20976. this.angle = 0;
  20977. this.cellIndex = 0;
  20978. this.invertU = 0;
  20979. this.invertV = 0;
  20980. this.animations = new Array();
  20981. this._animationStarted = false;
  20982. this._loopAnimation = false;
  20983. this._fromIndex = 0;
  20984. this._toIndex = 0;
  20985. this._delay = 0;
  20986. this._direction = 1;
  20987. this._frameCount = 0;
  20988. this._time = 0;
  20989. this._manager = manager;
  20990. this._manager.sprites.push(this);
  20991. this.position = BABYLON.Vector3.Zero();
  20992. }
  20993. Object.defineProperty(Sprite.prototype, "size", {
  20994. get: function () {
  20995. return this.width;
  20996. },
  20997. set: function (value) {
  20998. this.width = value;
  20999. this.height = value;
  21000. },
  21001. enumerable: true,
  21002. configurable: true
  21003. });
  21004. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21005. this._fromIndex = from;
  21006. this._toIndex = to;
  21007. this._loopAnimation = loop;
  21008. this._delay = delay;
  21009. this._animationStarted = true;
  21010. this._direction = from < to ? 1 : -1;
  21011. this.cellIndex = from;
  21012. this._time = 0;
  21013. };
  21014. Sprite.prototype.stopAnimation = function () {
  21015. this._animationStarted = false;
  21016. };
  21017. Sprite.prototype._animate = function (deltaTime) {
  21018. if (!this._animationStarted)
  21019. return;
  21020. this._time += deltaTime;
  21021. if (this._time > this._delay) {
  21022. this._time = this._time % this._delay;
  21023. this.cellIndex += this._direction;
  21024. if (this.cellIndex == this._toIndex) {
  21025. if (this._loopAnimation) {
  21026. this.cellIndex = this._fromIndex;
  21027. }
  21028. else {
  21029. this._animationStarted = false;
  21030. if (this.disposeWhenFinishedAnimating) {
  21031. this.dispose();
  21032. }
  21033. }
  21034. }
  21035. }
  21036. };
  21037. Sprite.prototype.dispose = function () {
  21038. for (var i = 0; i < this._manager.sprites.length; i++) {
  21039. if (this._manager.sprites[i] == this) {
  21040. this._manager.sprites.splice(i, 1);
  21041. }
  21042. }
  21043. };
  21044. return Sprite;
  21045. })();
  21046. BABYLON.Sprite = Sprite;
  21047. })(BABYLON || (BABYLON = {}));
  21048. var BABYLON;
  21049. (function (BABYLON) {
  21050. var Layer = (function () {
  21051. function Layer(name, imgUrl, scene, isBackground, color) {
  21052. this.name = name;
  21053. this._vertexDeclaration = [2];
  21054. this._vertexStrideSize = 2 * 4;
  21055. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21056. this.isBackground = isBackground === undefined ? true : isBackground;
  21057. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21058. this._scene = scene;
  21059. this._scene.layers.push(this);
  21060. // VBO
  21061. var vertices = [];
  21062. vertices.push(1, 1);
  21063. vertices.push(-1, 1);
  21064. vertices.push(-1, -1);
  21065. vertices.push(1, -1);
  21066. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21067. // Indices
  21068. var indices = [];
  21069. indices.push(0);
  21070. indices.push(1);
  21071. indices.push(2);
  21072. indices.push(0);
  21073. indices.push(2);
  21074. indices.push(3);
  21075. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21076. // Effects
  21077. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21078. }
  21079. Layer.prototype.render = function () {
  21080. // Check
  21081. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21082. return;
  21083. var engine = this._scene.getEngine();
  21084. // Render
  21085. engine.enableEffect(this._effect);
  21086. engine.setState(false);
  21087. // Texture
  21088. this._effect.setTexture("textureSampler", this.texture);
  21089. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21090. // Color
  21091. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21092. // VBOs
  21093. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21094. // Draw order
  21095. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21096. engine.draw(true, 0, 6);
  21097. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21098. };
  21099. Layer.prototype.dispose = function () {
  21100. if (this._vertexBuffer) {
  21101. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21102. this._vertexBuffer = null;
  21103. }
  21104. if (this._indexBuffer) {
  21105. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21106. this._indexBuffer = null;
  21107. }
  21108. if (this.texture) {
  21109. this.texture.dispose();
  21110. this.texture = null;
  21111. }
  21112. // Remove from scene
  21113. var index = this._scene.layers.indexOf(this);
  21114. this._scene.layers.splice(index, 1);
  21115. // Callback
  21116. if (this.onDispose) {
  21117. this.onDispose();
  21118. }
  21119. };
  21120. return Layer;
  21121. })();
  21122. BABYLON.Layer = Layer;
  21123. })(BABYLON || (BABYLON = {}));
  21124. var BABYLON;
  21125. (function (BABYLON) {
  21126. var Particle = (function () {
  21127. function Particle() {
  21128. this.position = BABYLON.Vector3.Zero();
  21129. this.direction = BABYLON.Vector3.Zero();
  21130. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21131. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21132. this.lifeTime = 1.0;
  21133. this.age = 0;
  21134. this.size = 0;
  21135. this.angle = 0;
  21136. this.angularSpeed = 0;
  21137. }
  21138. Particle.prototype.copyTo = function (other) {
  21139. other.position.copyFrom(this.position);
  21140. other.direction.copyFrom(this.direction);
  21141. other.color.copyFrom(this.color);
  21142. other.colorStep.copyFrom(this.colorStep);
  21143. other.lifeTime = this.lifeTime;
  21144. other.age = this.age;
  21145. other.size = this.size;
  21146. other.angle = this.angle;
  21147. other.angularSpeed = this.angularSpeed;
  21148. };
  21149. return Particle;
  21150. })();
  21151. BABYLON.Particle = Particle;
  21152. })(BABYLON || (BABYLON = {}));
  21153. var BABYLON;
  21154. (function (BABYLON) {
  21155. var randomNumber = function (min, max) {
  21156. if (min === max) {
  21157. return (min);
  21158. }
  21159. var random = Math.random();
  21160. return ((random * (max - min)) + min);
  21161. };
  21162. var ParticleSystem = (function () {
  21163. function ParticleSystem(name, capacity, scene, customEffect) {
  21164. var _this = this;
  21165. this.name = name;
  21166. this.renderingGroupId = 0;
  21167. this.emitter = null;
  21168. this.emitRate = 10;
  21169. this.manualEmitCount = -1;
  21170. this.updateSpeed = 0.01;
  21171. this.targetStopDuration = 0;
  21172. this.disposeOnStop = false;
  21173. this.minEmitPower = 1;
  21174. this.maxEmitPower = 1;
  21175. this.minLifeTime = 1;
  21176. this.maxLifeTime = 1;
  21177. this.minSize = 1;
  21178. this.maxSize = 1;
  21179. this.minAngularSpeed = 0;
  21180. this.maxAngularSpeed = 0;
  21181. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21182. this.forceDepthWrite = false;
  21183. this.gravity = BABYLON.Vector3.Zero();
  21184. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21185. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21186. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21187. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21188. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21189. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21190. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21191. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21192. this.particles = new Array();
  21193. this._vertexDeclaration = [3, 4, 4];
  21194. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21195. this._stockParticles = new Array();
  21196. this._newPartsExcess = 0;
  21197. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21198. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21199. this._scaledDirection = BABYLON.Vector3.Zero();
  21200. this._scaledGravity = BABYLON.Vector3.Zero();
  21201. this._currentRenderId = -1;
  21202. this._started = false;
  21203. this._stopped = false;
  21204. this._actualFrame = 0;
  21205. this.id = name;
  21206. this._capacity = capacity;
  21207. this._scene = scene;
  21208. this._customEffect = customEffect;
  21209. scene.particleSystems.push(this);
  21210. // VBO
  21211. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21212. var indices = [];
  21213. var index = 0;
  21214. for (var count = 0; count < capacity; count++) {
  21215. indices.push(index);
  21216. indices.push(index + 1);
  21217. indices.push(index + 2);
  21218. indices.push(index);
  21219. indices.push(index + 2);
  21220. indices.push(index + 3);
  21221. index += 4;
  21222. }
  21223. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21224. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21225. // Default behaviors
  21226. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21227. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21228. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21229. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21230. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21231. };
  21232. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21233. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21234. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21235. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21236. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21237. };
  21238. this.updateFunction = function (particles) {
  21239. for (var index = 0; index < particles.length; index++) {
  21240. var particle = particles[index];
  21241. particle.age += _this._scaledUpdateSpeed;
  21242. if (particle.age >= particle.lifeTime) {
  21243. _this.recycleParticle(particle);
  21244. index--;
  21245. continue;
  21246. }
  21247. else {
  21248. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21249. particle.color.addInPlace(_this._scaledColorStep);
  21250. if (particle.color.a < 0)
  21251. particle.color.a = 0;
  21252. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21253. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21254. particle.position.addInPlace(_this._scaledDirection);
  21255. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21256. particle.direction.addInPlace(_this._scaledGravity);
  21257. }
  21258. }
  21259. };
  21260. }
  21261. ParticleSystem.prototype.recycleParticle = function (particle) {
  21262. var lastParticle = this.particles.pop();
  21263. if (lastParticle !== particle) {
  21264. lastParticle.copyTo(particle);
  21265. this._stockParticles.push(lastParticle);
  21266. }
  21267. };
  21268. ParticleSystem.prototype.getCapacity = function () {
  21269. return this._capacity;
  21270. };
  21271. ParticleSystem.prototype.isAlive = function () {
  21272. return this._alive;
  21273. };
  21274. ParticleSystem.prototype.isStarted = function () {
  21275. return this._started;
  21276. };
  21277. ParticleSystem.prototype.start = function () {
  21278. this._started = true;
  21279. this._stopped = false;
  21280. this._actualFrame = 0;
  21281. };
  21282. ParticleSystem.prototype.stop = function () {
  21283. this._stopped = true;
  21284. };
  21285. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21286. var offset = index * 11;
  21287. this._vertices[offset] = particle.position.x;
  21288. this._vertices[offset + 1] = particle.position.y;
  21289. this._vertices[offset + 2] = particle.position.z;
  21290. this._vertices[offset + 3] = particle.color.r;
  21291. this._vertices[offset + 4] = particle.color.g;
  21292. this._vertices[offset + 5] = particle.color.b;
  21293. this._vertices[offset + 6] = particle.color.a;
  21294. this._vertices[offset + 7] = particle.angle;
  21295. this._vertices[offset + 8] = particle.size;
  21296. this._vertices[offset + 9] = offsetX;
  21297. this._vertices[offset + 10] = offsetY;
  21298. };
  21299. ParticleSystem.prototype._update = function (newParticles) {
  21300. // Update current
  21301. this._alive = this.particles.length > 0;
  21302. this.updateFunction(this.particles);
  21303. // Add new ones
  21304. var worldMatrix;
  21305. if (this.emitter.position) {
  21306. worldMatrix = this.emitter.getWorldMatrix();
  21307. }
  21308. else {
  21309. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21310. }
  21311. for (var index = 0; index < newParticles; index++) {
  21312. if (this.particles.length === this._capacity) {
  21313. break;
  21314. }
  21315. if (this._stockParticles.length !== 0) {
  21316. var particle = this._stockParticles.pop();
  21317. particle.age = 0;
  21318. }
  21319. else {
  21320. particle = new BABYLON.Particle();
  21321. }
  21322. this.particles.push(particle);
  21323. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21324. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21325. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21326. particle.size = randomNumber(this.minSize, this.maxSize);
  21327. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21328. this.startPositionFunction(worldMatrix, particle.position);
  21329. var step = randomNumber(0, 1.0);
  21330. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21331. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21332. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21333. }
  21334. };
  21335. ParticleSystem.prototype._getEffect = function () {
  21336. if (this._customEffect) {
  21337. return this._customEffect;
  21338. }
  21339. ;
  21340. var defines = [];
  21341. if (this._scene.clipPlane) {
  21342. defines.push("#define CLIPPLANE");
  21343. }
  21344. // Effect
  21345. var join = defines.join("\n");
  21346. if (this._cachedDefines !== join) {
  21347. this._cachedDefines = join;
  21348. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21349. }
  21350. return this._effect;
  21351. };
  21352. ParticleSystem.prototype.animate = function () {
  21353. if (!this._started)
  21354. return;
  21355. var effect = this._getEffect();
  21356. // Check
  21357. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21358. return;
  21359. if (this._currentRenderId === this._scene.getRenderId()) {
  21360. return;
  21361. }
  21362. this._currentRenderId = this._scene.getRenderId();
  21363. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21364. // determine the number of particles we need to create
  21365. var emitCout;
  21366. if (this.manualEmitCount > -1) {
  21367. emitCout = this.manualEmitCount;
  21368. this.manualEmitCount = 0;
  21369. }
  21370. else {
  21371. emitCout = this.emitRate;
  21372. }
  21373. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21374. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21375. if (this._newPartsExcess > 1.0) {
  21376. newParticles += this._newPartsExcess >> 0;
  21377. this._newPartsExcess -= this._newPartsExcess >> 0;
  21378. }
  21379. this._alive = false;
  21380. if (!this._stopped) {
  21381. this._actualFrame += this._scaledUpdateSpeed;
  21382. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21383. this.stop();
  21384. }
  21385. else {
  21386. newParticles = 0;
  21387. }
  21388. this._update(newParticles);
  21389. // Stopped?
  21390. if (this._stopped) {
  21391. if (!this._alive) {
  21392. this._started = false;
  21393. if (this.disposeOnStop) {
  21394. this._scene._toBeDisposed.push(this);
  21395. }
  21396. }
  21397. }
  21398. // Update VBO
  21399. var offset = 0;
  21400. for (var index = 0; index < this.particles.length; index++) {
  21401. var particle = this.particles[index];
  21402. this._appendParticleVertex(offset++, particle, 0, 0);
  21403. this._appendParticleVertex(offset++, particle, 1, 0);
  21404. this._appendParticleVertex(offset++, particle, 1, 1);
  21405. this._appendParticleVertex(offset++, particle, 0, 1);
  21406. }
  21407. var engine = this._scene.getEngine();
  21408. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21409. };
  21410. ParticleSystem.prototype.render = function () {
  21411. var effect = this._getEffect();
  21412. // Check
  21413. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21414. return 0;
  21415. var engine = this._scene.getEngine();
  21416. // Render
  21417. engine.enableEffect(effect);
  21418. engine.setState(false);
  21419. var viewMatrix = this._scene.getViewMatrix();
  21420. effect.setTexture("diffuseSampler", this.particleTexture);
  21421. effect.setMatrix("view", viewMatrix);
  21422. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21423. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21424. if (this._scene.clipPlane) {
  21425. var clipPlane = this._scene.clipPlane;
  21426. var invView = viewMatrix.clone();
  21427. invView.invert();
  21428. effect.setMatrix("invView", invView);
  21429. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21430. }
  21431. // VBOs
  21432. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21433. // Draw order
  21434. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21435. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21436. }
  21437. else {
  21438. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21439. }
  21440. if (this.forceDepthWrite) {
  21441. engine.setDepthWrite(true);
  21442. }
  21443. engine.draw(true, 0, this.particles.length * 6);
  21444. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21445. return this.particles.length;
  21446. };
  21447. ParticleSystem.prototype.dispose = function () {
  21448. if (this._vertexBuffer) {
  21449. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21450. this._vertexBuffer = null;
  21451. }
  21452. if (this._indexBuffer) {
  21453. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21454. this._indexBuffer = null;
  21455. }
  21456. if (this.particleTexture) {
  21457. this.particleTexture.dispose();
  21458. this.particleTexture = null;
  21459. }
  21460. // Remove from scene
  21461. var index = this._scene.particleSystems.indexOf(this);
  21462. this._scene.particleSystems.splice(index, 1);
  21463. // Callback
  21464. if (this.onDispose) {
  21465. this.onDispose();
  21466. }
  21467. };
  21468. // Clone
  21469. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21470. var result = new ParticleSystem(name, this._capacity, this._scene);
  21471. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21472. if (newEmitter === undefined) {
  21473. newEmitter = this.emitter;
  21474. }
  21475. result.emitter = newEmitter;
  21476. if (this.particleTexture) {
  21477. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21478. }
  21479. result.start();
  21480. return result;
  21481. };
  21482. // Statics
  21483. ParticleSystem.BLENDMODE_ONEONE = 0;
  21484. ParticleSystem.BLENDMODE_STANDARD = 1;
  21485. return ParticleSystem;
  21486. })();
  21487. BABYLON.ParticleSystem = ParticleSystem;
  21488. })(BABYLON || (BABYLON = {}));
  21489. var BABYLON;
  21490. (function (BABYLON) {
  21491. var Animation = (function () {
  21492. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21493. this.name = name;
  21494. this.targetProperty = targetProperty;
  21495. this.framePerSecond = framePerSecond;
  21496. this.dataType = dataType;
  21497. this.loopMode = loopMode;
  21498. this._offsetsCache = {};
  21499. this._highLimitsCache = {};
  21500. this._stopped = false;
  21501. this.targetPropertyPath = targetProperty.split(".");
  21502. this.dataType = dataType;
  21503. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21504. }
  21505. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21506. var dataType = undefined;
  21507. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21508. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21509. }
  21510. else if (from instanceof BABYLON.Quaternion) {
  21511. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21512. }
  21513. else if (from instanceof BABYLON.Vector3) {
  21514. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21515. }
  21516. else if (from instanceof BABYLON.Vector2) {
  21517. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21518. }
  21519. else if (from instanceof BABYLON.Color3) {
  21520. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21521. }
  21522. if (dataType == undefined) {
  21523. return null;
  21524. }
  21525. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21526. var keys = [];
  21527. keys.push({ frame: 0, value: from });
  21528. keys.push({ frame: totalFrame, value: to });
  21529. animation.setKeys(keys);
  21530. if (easingFunction !== undefined) {
  21531. animation.setEasingFunction(easingFunction);
  21532. }
  21533. mesh.animations.push(animation);
  21534. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21535. };
  21536. // Methods
  21537. Animation.prototype.reset = function () {
  21538. this._offsetsCache = {};
  21539. this._highLimitsCache = {};
  21540. this.currentFrame = 0;
  21541. };
  21542. Animation.prototype.isStopped = function () {
  21543. return this._stopped;
  21544. };
  21545. Animation.prototype.getKeys = function () {
  21546. return this._keys;
  21547. };
  21548. Animation.prototype.getEasingFunction = function () {
  21549. return this._easingFunction;
  21550. };
  21551. Animation.prototype.setEasingFunction = function (easingFunction) {
  21552. this._easingFunction = easingFunction;
  21553. };
  21554. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21555. return startValue + (endValue - startValue) * gradient;
  21556. };
  21557. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21558. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21559. };
  21560. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21561. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21562. };
  21563. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21564. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21565. };
  21566. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21567. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21568. };
  21569. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21570. var startScale = new BABYLON.Vector3(0, 0, 0);
  21571. var startRotation = new BABYLON.Quaternion();
  21572. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21573. startValue.decompose(startScale, startRotation, startTranslation);
  21574. var endScale = new BABYLON.Vector3(0, 0, 0);
  21575. var endRotation = new BABYLON.Quaternion();
  21576. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21577. endValue.decompose(endScale, endRotation, endTranslation);
  21578. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21579. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21580. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21581. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21582. return result;
  21583. };
  21584. Animation.prototype.clone = function () {
  21585. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21586. clone.setKeys(this._keys);
  21587. return clone;
  21588. };
  21589. Animation.prototype.setKeys = function (values) {
  21590. this._keys = values.slice(0);
  21591. this._offsetsCache = {};
  21592. this._highLimitsCache = {};
  21593. };
  21594. Animation.prototype._getKeyValue = function (value) {
  21595. if (typeof value === "function") {
  21596. return value();
  21597. }
  21598. return value;
  21599. };
  21600. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21601. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21602. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21603. }
  21604. this.currentFrame = currentFrame;
  21605. // Try to get a hash to find the right key
  21606. 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));
  21607. if (this._keys[startKey].frame >= currentFrame) {
  21608. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21609. startKey--;
  21610. }
  21611. }
  21612. for (var key = startKey; key < this._keys.length; key++) {
  21613. if (this._keys[key + 1].frame >= currentFrame) {
  21614. var startValue = this._getKeyValue(this._keys[key].value);
  21615. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21616. // gradient : percent of currentFrame between the frame inf and the frame sup
  21617. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21618. // check for easingFunction and correction of gradient
  21619. if (this._easingFunction != null) {
  21620. gradient = this._easingFunction.ease(gradient);
  21621. }
  21622. switch (this.dataType) {
  21623. // Float
  21624. case Animation.ANIMATIONTYPE_FLOAT:
  21625. switch (loopMode) {
  21626. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21627. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21628. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21629. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21630. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21631. }
  21632. break;
  21633. // Quaternion
  21634. case Animation.ANIMATIONTYPE_QUATERNION:
  21635. var quaternion = null;
  21636. switch (loopMode) {
  21637. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21638. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21639. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21640. break;
  21641. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21642. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21643. break;
  21644. }
  21645. return quaternion;
  21646. // Vector3
  21647. case Animation.ANIMATIONTYPE_VECTOR3:
  21648. switch (loopMode) {
  21649. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21650. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21651. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21652. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21653. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21654. }
  21655. // Vector2
  21656. case Animation.ANIMATIONTYPE_VECTOR2:
  21657. switch (loopMode) {
  21658. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21659. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21660. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21661. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21662. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21663. }
  21664. // Color3
  21665. case Animation.ANIMATIONTYPE_COLOR3:
  21666. switch (loopMode) {
  21667. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21668. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21669. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21670. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21671. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21672. }
  21673. // Matrix
  21674. case Animation.ANIMATIONTYPE_MATRIX:
  21675. switch (loopMode) {
  21676. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21677. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21678. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21679. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21680. return startValue;
  21681. }
  21682. default:
  21683. break;
  21684. }
  21685. break;
  21686. }
  21687. }
  21688. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21689. };
  21690. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21691. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21692. this._stopped = true;
  21693. return false;
  21694. }
  21695. var returnValue = true;
  21696. // Adding a start key at frame 0 if missing
  21697. if (this._keys[0].frame !== 0) {
  21698. var newKey = { frame: 0, value: this._keys[0].value };
  21699. this._keys.splice(0, 0, newKey);
  21700. }
  21701. // Check limits
  21702. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21703. from = this._keys[0].frame;
  21704. }
  21705. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21706. to = this._keys[this._keys.length - 1].frame;
  21707. }
  21708. // Compute ratio
  21709. var range = to - from;
  21710. var offsetValue;
  21711. // ratio represents the frame delta between from and to
  21712. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21713. var highLimitValue = 0;
  21714. if (ratio > range && !loop) {
  21715. returnValue = false;
  21716. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21717. }
  21718. else {
  21719. // Get max value if required
  21720. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21721. var keyOffset = to.toString() + from.toString();
  21722. if (!this._offsetsCache[keyOffset]) {
  21723. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21724. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21725. switch (this.dataType) {
  21726. // Float
  21727. case Animation.ANIMATIONTYPE_FLOAT:
  21728. this._offsetsCache[keyOffset] = toValue - fromValue;
  21729. break;
  21730. // Quaternion
  21731. case Animation.ANIMATIONTYPE_QUATERNION:
  21732. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21733. break;
  21734. // Vector3
  21735. case Animation.ANIMATIONTYPE_VECTOR3:
  21736. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21737. // Vector2
  21738. case Animation.ANIMATIONTYPE_VECTOR2:
  21739. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21740. // Color3
  21741. case Animation.ANIMATIONTYPE_COLOR3:
  21742. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21743. default:
  21744. break;
  21745. }
  21746. this._highLimitsCache[keyOffset] = toValue;
  21747. }
  21748. highLimitValue = this._highLimitsCache[keyOffset];
  21749. offsetValue = this._offsetsCache[keyOffset];
  21750. }
  21751. }
  21752. if (offsetValue === undefined) {
  21753. switch (this.dataType) {
  21754. // Float
  21755. case Animation.ANIMATIONTYPE_FLOAT:
  21756. offsetValue = 0;
  21757. break;
  21758. // Quaternion
  21759. case Animation.ANIMATIONTYPE_QUATERNION:
  21760. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21761. break;
  21762. // Vector3
  21763. case Animation.ANIMATIONTYPE_VECTOR3:
  21764. offsetValue = BABYLON.Vector3.Zero();
  21765. break;
  21766. // Vector2
  21767. case Animation.ANIMATIONTYPE_VECTOR2:
  21768. offsetValue = BABYLON.Vector2.Zero();
  21769. break;
  21770. // Color3
  21771. case Animation.ANIMATIONTYPE_COLOR3:
  21772. offsetValue = BABYLON.Color3.Black();
  21773. }
  21774. }
  21775. // Compute value
  21776. var repeatCount = (ratio / range) >> 0;
  21777. var currentFrame = returnValue ? from + ratio % range : to;
  21778. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21779. // Set value
  21780. if (this.targetPropertyPath.length > 1) {
  21781. var property = this._target[this.targetPropertyPath[0]];
  21782. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21783. property = property[this.targetPropertyPath[index]];
  21784. }
  21785. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21786. }
  21787. else {
  21788. this._target[this.targetPropertyPath[0]] = currentValue;
  21789. }
  21790. if (this._target.markAsDirty) {
  21791. this._target.markAsDirty(this.targetProperty);
  21792. }
  21793. if (!returnValue) {
  21794. this._stopped = true;
  21795. }
  21796. return returnValue;
  21797. };
  21798. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21799. get: function () {
  21800. return Animation._ANIMATIONTYPE_FLOAT;
  21801. },
  21802. enumerable: true,
  21803. configurable: true
  21804. });
  21805. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21806. get: function () {
  21807. return Animation._ANIMATIONTYPE_VECTOR3;
  21808. },
  21809. enumerable: true,
  21810. configurable: true
  21811. });
  21812. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21813. get: function () {
  21814. return Animation._ANIMATIONTYPE_VECTOR2;
  21815. },
  21816. enumerable: true,
  21817. configurable: true
  21818. });
  21819. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21820. get: function () {
  21821. return Animation._ANIMATIONTYPE_QUATERNION;
  21822. },
  21823. enumerable: true,
  21824. configurable: true
  21825. });
  21826. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21827. get: function () {
  21828. return Animation._ANIMATIONTYPE_MATRIX;
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21834. get: function () {
  21835. return Animation._ANIMATIONTYPE_COLOR3;
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21841. get: function () {
  21842. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21843. },
  21844. enumerable: true,
  21845. configurable: true
  21846. });
  21847. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21848. get: function () {
  21849. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21850. },
  21851. enumerable: true,
  21852. configurable: true
  21853. });
  21854. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21855. get: function () {
  21856. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21857. },
  21858. enumerable: true,
  21859. configurable: true
  21860. });
  21861. // Statics
  21862. Animation._ANIMATIONTYPE_FLOAT = 0;
  21863. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21864. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21865. Animation._ANIMATIONTYPE_MATRIX = 3;
  21866. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21867. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21868. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21869. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21870. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21871. return Animation;
  21872. })();
  21873. BABYLON.Animation = Animation;
  21874. })(BABYLON || (BABYLON = {}));
  21875. var BABYLON;
  21876. (function (BABYLON) {
  21877. var Animatable = (function () {
  21878. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21879. if (fromFrame === void 0) { fromFrame = 0; }
  21880. if (toFrame === void 0) { toFrame = 100; }
  21881. if (loopAnimation === void 0) { loopAnimation = false; }
  21882. if (speedRatio === void 0) { speedRatio = 1.0; }
  21883. this.target = target;
  21884. this.fromFrame = fromFrame;
  21885. this.toFrame = toFrame;
  21886. this.loopAnimation = loopAnimation;
  21887. this.speedRatio = speedRatio;
  21888. this.onAnimationEnd = onAnimationEnd;
  21889. this._animations = new Array();
  21890. this._paused = false;
  21891. this.animationStarted = false;
  21892. if (animations) {
  21893. this.appendAnimations(target, animations);
  21894. }
  21895. this._scene = scene;
  21896. scene._activeAnimatables.push(this);
  21897. }
  21898. // Methods
  21899. Animatable.prototype.appendAnimations = function (target, animations) {
  21900. for (var index = 0; index < animations.length; index++) {
  21901. var animation = animations[index];
  21902. animation._target = target;
  21903. this._animations.push(animation);
  21904. }
  21905. };
  21906. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21907. var animations = this._animations;
  21908. for (var index = 0; index < animations.length; index++) {
  21909. if (animations[index].targetProperty === property) {
  21910. return animations[index];
  21911. }
  21912. }
  21913. return null;
  21914. };
  21915. Animatable.prototype.reset = function () {
  21916. var animations = this._animations;
  21917. for (var index = 0; index < animations.length; index++) {
  21918. animations[index].reset();
  21919. }
  21920. this._localDelayOffset = null;
  21921. this._pausedDelay = null;
  21922. };
  21923. Animatable.prototype.pause = function () {
  21924. if (this._paused) {
  21925. return;
  21926. }
  21927. this._paused = true;
  21928. };
  21929. Animatable.prototype.restart = function () {
  21930. this._paused = false;
  21931. };
  21932. Animatable.prototype.stop = function () {
  21933. var index = this._scene._activeAnimatables.indexOf(this);
  21934. if (index > -1) {
  21935. this._scene._activeAnimatables.splice(index, 1);
  21936. }
  21937. if (this.onAnimationEnd) {
  21938. this.onAnimationEnd();
  21939. }
  21940. };
  21941. Animatable.prototype._animate = function (delay) {
  21942. if (this._paused) {
  21943. if (!this._pausedDelay) {
  21944. this._pausedDelay = delay;
  21945. }
  21946. return true;
  21947. }
  21948. if (!this._localDelayOffset) {
  21949. this._localDelayOffset = delay;
  21950. }
  21951. else if (this._pausedDelay) {
  21952. this._localDelayOffset += delay - this._pausedDelay;
  21953. this._pausedDelay = null;
  21954. }
  21955. // Animating
  21956. var running = false;
  21957. var animations = this._animations;
  21958. for (var index = 0; index < animations.length; index++) {
  21959. var animation = animations[index];
  21960. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21961. running = running || isRunning;
  21962. }
  21963. if (!running) {
  21964. // Remove from active animatables
  21965. index = this._scene._activeAnimatables.indexOf(this);
  21966. this._scene._activeAnimatables.splice(index, 1);
  21967. }
  21968. if (!running && this.onAnimationEnd) {
  21969. this.onAnimationEnd();
  21970. }
  21971. return running;
  21972. };
  21973. return Animatable;
  21974. })();
  21975. BABYLON.Animatable = Animatable;
  21976. })(BABYLON || (BABYLON = {}));
  21977. var BABYLON;
  21978. (function (BABYLON) {
  21979. var EasingFunction = (function () {
  21980. function EasingFunction() {
  21981. // Properties
  21982. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21983. }
  21984. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21985. get: function () {
  21986. return EasingFunction._EASINGMODE_EASEIN;
  21987. },
  21988. enumerable: true,
  21989. configurable: true
  21990. });
  21991. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21992. get: function () {
  21993. return EasingFunction._EASINGMODE_EASEOUT;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21999. get: function () {
  22000. return EasingFunction._EASINGMODE_EASEINOUT;
  22001. },
  22002. enumerable: true,
  22003. configurable: true
  22004. });
  22005. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22006. var n = Math.min(Math.max(easingMode, 0), 2);
  22007. this._easingMode = n;
  22008. };
  22009. EasingFunction.prototype.getEasingMode = function () {
  22010. return this._easingMode;
  22011. };
  22012. EasingFunction.prototype.easeInCore = function (gradient) {
  22013. throw new Error('You must implement this method');
  22014. };
  22015. EasingFunction.prototype.ease = function (gradient) {
  22016. switch (this._easingMode) {
  22017. case EasingFunction.EASINGMODE_EASEIN:
  22018. return this.easeInCore(gradient);
  22019. case EasingFunction.EASINGMODE_EASEOUT:
  22020. return (1 - this.easeInCore(1 - gradient));
  22021. }
  22022. if (gradient >= 0.5) {
  22023. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22024. }
  22025. return (this.easeInCore(gradient * 2) * 0.5);
  22026. };
  22027. //Statics
  22028. EasingFunction._EASINGMODE_EASEIN = 0;
  22029. EasingFunction._EASINGMODE_EASEOUT = 1;
  22030. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22031. return EasingFunction;
  22032. })();
  22033. BABYLON.EasingFunction = EasingFunction;
  22034. var CircleEase = (function (_super) {
  22035. __extends(CircleEase, _super);
  22036. function CircleEase() {
  22037. _super.apply(this, arguments);
  22038. }
  22039. CircleEase.prototype.easeInCore = function (gradient) {
  22040. gradient = Math.max(0, Math.min(1, gradient));
  22041. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22042. };
  22043. return CircleEase;
  22044. })(EasingFunction);
  22045. BABYLON.CircleEase = CircleEase;
  22046. var BackEase = (function (_super) {
  22047. __extends(BackEase, _super);
  22048. function BackEase(amplitude) {
  22049. if (amplitude === void 0) { amplitude = 1; }
  22050. _super.call(this);
  22051. this.amplitude = amplitude;
  22052. }
  22053. BackEase.prototype.easeInCore = function (gradient) {
  22054. var num = Math.max(0, this.amplitude);
  22055. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22056. };
  22057. return BackEase;
  22058. })(EasingFunction);
  22059. BABYLON.BackEase = BackEase;
  22060. var BounceEase = (function (_super) {
  22061. __extends(BounceEase, _super);
  22062. function BounceEase(bounces, bounciness) {
  22063. if (bounces === void 0) { bounces = 3; }
  22064. if (bounciness === void 0) { bounciness = 2; }
  22065. _super.call(this);
  22066. this.bounces = bounces;
  22067. this.bounciness = bounciness;
  22068. }
  22069. BounceEase.prototype.easeInCore = function (gradient) {
  22070. var y = Math.max(0.0, this.bounces);
  22071. var bounciness = this.bounciness;
  22072. if (bounciness <= 1.0) {
  22073. bounciness = 1.001;
  22074. }
  22075. var num9 = Math.pow(bounciness, y);
  22076. var num5 = 1.0 - bounciness;
  22077. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22078. var num15 = gradient * num4;
  22079. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22080. var num3 = Math.floor(num65);
  22081. var num13 = num3 + 1.0;
  22082. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22083. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22084. var num7 = (num8 + num12) * 0.5;
  22085. var num6 = gradient - num7;
  22086. var num2 = num7 - num8;
  22087. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22088. };
  22089. return BounceEase;
  22090. })(EasingFunction);
  22091. BABYLON.BounceEase = BounceEase;
  22092. var CubicEase = (function (_super) {
  22093. __extends(CubicEase, _super);
  22094. function CubicEase() {
  22095. _super.apply(this, arguments);
  22096. }
  22097. CubicEase.prototype.easeInCore = function (gradient) {
  22098. return (gradient * gradient * gradient);
  22099. };
  22100. return CubicEase;
  22101. })(EasingFunction);
  22102. BABYLON.CubicEase = CubicEase;
  22103. var ElasticEase = (function (_super) {
  22104. __extends(ElasticEase, _super);
  22105. function ElasticEase(oscillations, springiness) {
  22106. if (oscillations === void 0) { oscillations = 3; }
  22107. if (springiness === void 0) { springiness = 3; }
  22108. _super.call(this);
  22109. this.oscillations = oscillations;
  22110. this.springiness = springiness;
  22111. }
  22112. ElasticEase.prototype.easeInCore = function (gradient) {
  22113. var num2;
  22114. var num3 = Math.max(0.0, this.oscillations);
  22115. var num = Math.max(0.0, this.springiness);
  22116. if (num == 0) {
  22117. num2 = gradient;
  22118. }
  22119. else {
  22120. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22121. }
  22122. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22123. };
  22124. return ElasticEase;
  22125. })(EasingFunction);
  22126. BABYLON.ElasticEase = ElasticEase;
  22127. var ExponentialEase = (function (_super) {
  22128. __extends(ExponentialEase, _super);
  22129. function ExponentialEase(exponent) {
  22130. if (exponent === void 0) { exponent = 2; }
  22131. _super.call(this);
  22132. this.exponent = exponent;
  22133. }
  22134. ExponentialEase.prototype.easeInCore = function (gradient) {
  22135. if (this.exponent <= 0) {
  22136. return gradient;
  22137. }
  22138. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22139. };
  22140. return ExponentialEase;
  22141. })(EasingFunction);
  22142. BABYLON.ExponentialEase = ExponentialEase;
  22143. var PowerEase = (function (_super) {
  22144. __extends(PowerEase, _super);
  22145. function PowerEase(power) {
  22146. if (power === void 0) { power = 2; }
  22147. _super.call(this);
  22148. this.power = power;
  22149. }
  22150. PowerEase.prototype.easeInCore = function (gradient) {
  22151. var y = Math.max(0.0, this.power);
  22152. return Math.pow(gradient, y);
  22153. };
  22154. return PowerEase;
  22155. })(EasingFunction);
  22156. BABYLON.PowerEase = PowerEase;
  22157. var QuadraticEase = (function (_super) {
  22158. __extends(QuadraticEase, _super);
  22159. function QuadraticEase() {
  22160. _super.apply(this, arguments);
  22161. }
  22162. QuadraticEase.prototype.easeInCore = function (gradient) {
  22163. return (gradient * gradient);
  22164. };
  22165. return QuadraticEase;
  22166. })(EasingFunction);
  22167. BABYLON.QuadraticEase = QuadraticEase;
  22168. var QuarticEase = (function (_super) {
  22169. __extends(QuarticEase, _super);
  22170. function QuarticEase() {
  22171. _super.apply(this, arguments);
  22172. }
  22173. QuarticEase.prototype.easeInCore = function (gradient) {
  22174. return (gradient * gradient * gradient * gradient);
  22175. };
  22176. return QuarticEase;
  22177. })(EasingFunction);
  22178. BABYLON.QuarticEase = QuarticEase;
  22179. var QuinticEase = (function (_super) {
  22180. __extends(QuinticEase, _super);
  22181. function QuinticEase() {
  22182. _super.apply(this, arguments);
  22183. }
  22184. QuinticEase.prototype.easeInCore = function (gradient) {
  22185. return (gradient * gradient * gradient * gradient * gradient);
  22186. };
  22187. return QuinticEase;
  22188. })(EasingFunction);
  22189. BABYLON.QuinticEase = QuinticEase;
  22190. var SineEase = (function (_super) {
  22191. __extends(SineEase, _super);
  22192. function SineEase() {
  22193. _super.apply(this, arguments);
  22194. }
  22195. SineEase.prototype.easeInCore = function (gradient) {
  22196. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22197. };
  22198. return SineEase;
  22199. })(EasingFunction);
  22200. BABYLON.SineEase = SineEase;
  22201. var BezierCurveEase = (function (_super) {
  22202. __extends(BezierCurveEase, _super);
  22203. function BezierCurveEase(x1, y1, x2, y2) {
  22204. if (x1 === void 0) { x1 = 0; }
  22205. if (y1 === void 0) { y1 = 0; }
  22206. if (x2 === void 0) { x2 = 1; }
  22207. if (y2 === void 0) { y2 = 1; }
  22208. _super.call(this);
  22209. this.x1 = x1;
  22210. this.y1 = y1;
  22211. this.x2 = x2;
  22212. this.y2 = y2;
  22213. }
  22214. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22215. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22216. };
  22217. return BezierCurveEase;
  22218. })(EasingFunction);
  22219. BABYLON.BezierCurveEase = BezierCurveEase;
  22220. })(BABYLON || (BABYLON = {}));
  22221. var BABYLON;
  22222. (function (BABYLON) {
  22223. var Octree = (function () {
  22224. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22225. if (maxDepth === void 0) { maxDepth = 2; }
  22226. this.maxDepth = maxDepth;
  22227. this.dynamicContent = new Array();
  22228. this._maxBlockCapacity = maxBlockCapacity || 64;
  22229. this._selectionContent = new BABYLON.SmartArray(1024);
  22230. this._creationFunc = creationFunc;
  22231. }
  22232. // Methods
  22233. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22234. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22235. };
  22236. Octree.prototype.addMesh = function (entry) {
  22237. for (var index = 0; index < this.blocks.length; index++) {
  22238. var block = this.blocks[index];
  22239. block.addEntry(entry);
  22240. }
  22241. };
  22242. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22243. this._selectionContent.reset();
  22244. for (var index = 0; index < this.blocks.length; index++) {
  22245. var block = this.blocks[index];
  22246. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22247. }
  22248. if (allowDuplicate) {
  22249. this._selectionContent.concat(this.dynamicContent);
  22250. }
  22251. else {
  22252. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22253. }
  22254. return this._selectionContent;
  22255. };
  22256. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22257. this._selectionContent.reset();
  22258. for (var index = 0; index < this.blocks.length; index++) {
  22259. var block = this.blocks[index];
  22260. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22261. }
  22262. if (allowDuplicate) {
  22263. this._selectionContent.concat(this.dynamicContent);
  22264. }
  22265. else {
  22266. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22267. }
  22268. return this._selectionContent;
  22269. };
  22270. Octree.prototype.intersectsRay = function (ray) {
  22271. this._selectionContent.reset();
  22272. for (var index = 0; index < this.blocks.length; index++) {
  22273. var block = this.blocks[index];
  22274. block.intersectsRay(ray, this._selectionContent);
  22275. }
  22276. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22277. return this._selectionContent;
  22278. };
  22279. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22280. target.blocks = new Array();
  22281. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22282. // Segmenting space
  22283. for (var x = 0; x < 2; x++) {
  22284. for (var y = 0; y < 2; y++) {
  22285. for (var z = 0; z < 2; z++) {
  22286. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22287. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22288. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22289. block.addEntries(entries);
  22290. target.blocks.push(block);
  22291. }
  22292. }
  22293. }
  22294. };
  22295. Octree.CreationFuncForMeshes = function (entry, block) {
  22296. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22297. block.entries.push(entry);
  22298. }
  22299. };
  22300. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22301. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22302. block.entries.push(entry);
  22303. }
  22304. };
  22305. return Octree;
  22306. })();
  22307. BABYLON.Octree = Octree;
  22308. })(BABYLON || (BABYLON = {}));
  22309. var BABYLON;
  22310. (function (BABYLON) {
  22311. var OctreeBlock = (function () {
  22312. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22313. this.entries = new Array();
  22314. this._boundingVectors = new Array();
  22315. this._capacity = capacity;
  22316. this._depth = depth;
  22317. this._maxDepth = maxDepth;
  22318. this._creationFunc = creationFunc;
  22319. this._minPoint = minPoint;
  22320. this._maxPoint = maxPoint;
  22321. this._boundingVectors.push(minPoint.clone());
  22322. this._boundingVectors.push(maxPoint.clone());
  22323. this._boundingVectors.push(minPoint.clone());
  22324. this._boundingVectors[2].x = maxPoint.x;
  22325. this._boundingVectors.push(minPoint.clone());
  22326. this._boundingVectors[3].y = maxPoint.y;
  22327. this._boundingVectors.push(minPoint.clone());
  22328. this._boundingVectors[4].z = maxPoint.z;
  22329. this._boundingVectors.push(maxPoint.clone());
  22330. this._boundingVectors[5].z = minPoint.z;
  22331. this._boundingVectors.push(maxPoint.clone());
  22332. this._boundingVectors[6].x = minPoint.x;
  22333. this._boundingVectors.push(maxPoint.clone());
  22334. this._boundingVectors[7].y = minPoint.y;
  22335. }
  22336. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22337. // Property
  22338. get: function () {
  22339. return this._capacity;
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22345. get: function () {
  22346. return this._minPoint;
  22347. },
  22348. enumerable: true,
  22349. configurable: true
  22350. });
  22351. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22352. get: function () {
  22353. return this._maxPoint;
  22354. },
  22355. enumerable: true,
  22356. configurable: true
  22357. });
  22358. // Methods
  22359. OctreeBlock.prototype.addEntry = function (entry) {
  22360. if (this.blocks) {
  22361. for (var index = 0; index < this.blocks.length; index++) {
  22362. var block = this.blocks[index];
  22363. block.addEntry(entry);
  22364. }
  22365. return;
  22366. }
  22367. this._creationFunc(entry, this);
  22368. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22369. this.createInnerBlocks();
  22370. }
  22371. };
  22372. OctreeBlock.prototype.addEntries = function (entries) {
  22373. for (var index = 0; index < entries.length; index++) {
  22374. var mesh = entries[index];
  22375. this.addEntry(mesh);
  22376. }
  22377. };
  22378. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22379. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22380. if (this.blocks) {
  22381. for (var index = 0; index < this.blocks.length; index++) {
  22382. var block = this.blocks[index];
  22383. block.select(frustumPlanes, selection, allowDuplicate);
  22384. }
  22385. return;
  22386. }
  22387. if (allowDuplicate) {
  22388. selection.concat(this.entries);
  22389. }
  22390. else {
  22391. selection.concatWithNoDuplicate(this.entries);
  22392. }
  22393. }
  22394. };
  22395. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22396. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22397. if (this.blocks) {
  22398. for (var index = 0; index < this.blocks.length; index++) {
  22399. var block = this.blocks[index];
  22400. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22401. }
  22402. return;
  22403. }
  22404. if (allowDuplicate) {
  22405. selection.concat(this.entries);
  22406. }
  22407. else {
  22408. selection.concatWithNoDuplicate(this.entries);
  22409. }
  22410. }
  22411. };
  22412. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22413. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22414. if (this.blocks) {
  22415. for (var index = 0; index < this.blocks.length; index++) {
  22416. var block = this.blocks[index];
  22417. block.intersectsRay(ray, selection);
  22418. }
  22419. return;
  22420. }
  22421. selection.concatWithNoDuplicate(this.entries);
  22422. }
  22423. };
  22424. OctreeBlock.prototype.createInnerBlocks = function () {
  22425. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22426. };
  22427. return OctreeBlock;
  22428. })();
  22429. BABYLON.OctreeBlock = OctreeBlock;
  22430. })(BABYLON || (BABYLON = {}));
  22431. var BABYLON;
  22432. (function (BABYLON) {
  22433. var Bone = (function (_super) {
  22434. __extends(Bone, _super);
  22435. function Bone(name, skeleton, parentBone, matrix) {
  22436. _super.call(this, name, skeleton.getScene());
  22437. this.name = name;
  22438. this.children = new Array();
  22439. this.animations = new Array();
  22440. this._worldTransform = new BABYLON.Matrix();
  22441. this._absoluteTransform = new BABYLON.Matrix();
  22442. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22443. this._skeleton = skeleton;
  22444. this._matrix = matrix;
  22445. this._baseMatrix = matrix;
  22446. skeleton.bones.push(this);
  22447. if (parentBone) {
  22448. this._parent = parentBone;
  22449. parentBone.children.push(this);
  22450. }
  22451. else {
  22452. this._parent = null;
  22453. }
  22454. this._updateDifferenceMatrix();
  22455. }
  22456. // Members
  22457. Bone.prototype.getParent = function () {
  22458. return this._parent;
  22459. };
  22460. Bone.prototype.getLocalMatrix = function () {
  22461. return this._matrix;
  22462. };
  22463. Bone.prototype.getBaseMatrix = function () {
  22464. return this._baseMatrix;
  22465. };
  22466. Bone.prototype.getWorldMatrix = function () {
  22467. return this._worldTransform;
  22468. };
  22469. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22470. return this._invertedAbsoluteTransform;
  22471. };
  22472. Bone.prototype.getAbsoluteMatrix = function () {
  22473. var matrix = this._matrix.clone();
  22474. var parent = this._parent;
  22475. while (parent) {
  22476. matrix = matrix.multiply(parent.getLocalMatrix());
  22477. parent = parent.getParent();
  22478. }
  22479. return matrix;
  22480. };
  22481. // Methods
  22482. Bone.prototype.updateMatrix = function (matrix) {
  22483. this._matrix = matrix;
  22484. this._skeleton._markAsDirty();
  22485. this._updateDifferenceMatrix();
  22486. };
  22487. Bone.prototype._updateDifferenceMatrix = function () {
  22488. if (this._parent) {
  22489. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22490. }
  22491. else {
  22492. this._absoluteTransform.copyFrom(this._matrix);
  22493. }
  22494. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22495. for (var index = 0; index < this.children.length; index++) {
  22496. this.children[index]._updateDifferenceMatrix();
  22497. }
  22498. };
  22499. Bone.prototype.markAsDirty = function () {
  22500. this._currentRenderId++;
  22501. this._skeleton._markAsDirty();
  22502. };
  22503. return Bone;
  22504. })(BABYLON.Node);
  22505. BABYLON.Bone = Bone;
  22506. })(BABYLON || (BABYLON = {}));
  22507. var BABYLON;
  22508. (function (BABYLON) {
  22509. var Skeleton = (function () {
  22510. function Skeleton(name, id, scene) {
  22511. this.name = name;
  22512. this.id = id;
  22513. this.bones = new Array();
  22514. this._isDirty = true;
  22515. this._identity = BABYLON.Matrix.Identity();
  22516. this.bones = [];
  22517. this._scene = scene;
  22518. scene.skeletons.push(this);
  22519. this.prepare();
  22520. //make sure it will recalculate the matrix next time prepare is called.
  22521. this._isDirty = true;
  22522. }
  22523. // Members
  22524. Skeleton.prototype.getTransformMatrices = function () {
  22525. return this._transformMatrices;
  22526. };
  22527. Skeleton.prototype.getScene = function () {
  22528. return this._scene;
  22529. };
  22530. // Methods
  22531. Skeleton.prototype._markAsDirty = function () {
  22532. this._isDirty = true;
  22533. };
  22534. Skeleton.prototype.prepare = function () {
  22535. if (!this._isDirty) {
  22536. return;
  22537. }
  22538. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22539. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22540. }
  22541. for (var index = 0; index < this.bones.length; index++) {
  22542. var bone = this.bones[index];
  22543. var parentBone = bone.getParent();
  22544. if (parentBone) {
  22545. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22546. }
  22547. else {
  22548. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22549. }
  22550. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22551. }
  22552. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22553. this._isDirty = false;
  22554. this._scene._activeBones += this.bones.length;
  22555. };
  22556. Skeleton.prototype.getAnimatables = function () {
  22557. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22558. this._animatables = [];
  22559. for (var index = 0; index < this.bones.length; index++) {
  22560. this._animatables.push(this.bones[index]);
  22561. }
  22562. }
  22563. return this._animatables;
  22564. };
  22565. Skeleton.prototype.clone = function (name, id) {
  22566. var result = new Skeleton(name, id || name, this._scene);
  22567. for (var index = 0; index < this.bones.length; index++) {
  22568. var source = this.bones[index];
  22569. var parentBone = null;
  22570. if (source.getParent()) {
  22571. var parentIndex = this.bones.indexOf(source.getParent());
  22572. parentBone = result.bones[parentIndex];
  22573. }
  22574. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22575. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22576. }
  22577. return result;
  22578. };
  22579. return Skeleton;
  22580. })();
  22581. BABYLON.Skeleton = Skeleton;
  22582. })(BABYLON || (BABYLON = {}));
  22583. var BABYLON;
  22584. (function (BABYLON) {
  22585. var PostProcess = (function () {
  22586. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22588. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22589. this.name = name;
  22590. this.width = -1;
  22591. this.height = -1;
  22592. this._reusable = false;
  22593. this._textures = new BABYLON.SmartArray(2);
  22594. this._currentRenderTextureInd = 0;
  22595. if (camera != null) {
  22596. this._camera = camera;
  22597. this._scene = camera.getScene();
  22598. camera.attachPostProcess(this);
  22599. this._engine = this._scene.getEngine();
  22600. }
  22601. else {
  22602. this._engine = engine;
  22603. }
  22604. this._renderRatio = ratio;
  22605. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22606. this._reusable = reusable || false;
  22607. this._textureType = textureType;
  22608. samplers = samplers || [];
  22609. samplers.push("textureSampler");
  22610. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22611. }
  22612. PostProcess.prototype.isReusable = function () {
  22613. return this._reusable;
  22614. };
  22615. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22616. camera = camera || this._camera;
  22617. var scene = camera.getScene();
  22618. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22619. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22620. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22621. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22622. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22623. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22624. if (this._textures.length > 0) {
  22625. for (var i = 0; i < this._textures.length; i++) {
  22626. this._engine._releaseTexture(this._textures.data[i]);
  22627. }
  22628. this._textures.reset();
  22629. }
  22630. this.width = desiredWidth;
  22631. this.height = desiredHeight;
  22632. 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 }));
  22633. if (this._reusable) {
  22634. 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 }));
  22635. }
  22636. if (this.onSizeChanged) {
  22637. this.onSizeChanged();
  22638. }
  22639. }
  22640. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22641. if (this.onActivate) {
  22642. this.onActivate(camera);
  22643. }
  22644. // Clear
  22645. if (this.clearColor) {
  22646. this._engine.clear(this.clearColor, true, true);
  22647. }
  22648. else {
  22649. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22650. }
  22651. if (this._reusable) {
  22652. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22653. }
  22654. };
  22655. PostProcess.prototype.apply = function () {
  22656. // Check
  22657. if (!this._effect.isReady())
  22658. return null;
  22659. // States
  22660. this._engine.enableEffect(this._effect);
  22661. this._engine.setState(false);
  22662. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22663. this._engine.setDepthBuffer(false);
  22664. this._engine.setDepthWrite(false);
  22665. // Texture
  22666. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22667. // Parameters
  22668. if (this.onApply) {
  22669. this.onApply(this._effect);
  22670. }
  22671. return this._effect;
  22672. };
  22673. PostProcess.prototype.dispose = function (camera) {
  22674. camera = camera || this._camera;
  22675. if (this._textures.length > 0) {
  22676. for (var i = 0; i < this._textures.length; i++) {
  22677. this._engine._releaseTexture(this._textures.data[i]);
  22678. }
  22679. this._textures.reset();
  22680. }
  22681. if (!camera) {
  22682. return;
  22683. }
  22684. camera.detachPostProcess(this);
  22685. var index = camera._postProcesses.indexOf(this);
  22686. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22687. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22688. }
  22689. };
  22690. return PostProcess;
  22691. })();
  22692. BABYLON.PostProcess = PostProcess;
  22693. })(BABYLON || (BABYLON = {}));
  22694. var BABYLON;
  22695. (function (BABYLON) {
  22696. var PostProcessManager = (function () {
  22697. function PostProcessManager(scene) {
  22698. this._vertexDeclaration = [2];
  22699. this._vertexStrideSize = 2 * 4;
  22700. this._scene = scene;
  22701. }
  22702. PostProcessManager.prototype._prepareBuffers = function () {
  22703. if (this._vertexBuffer) {
  22704. return;
  22705. }
  22706. // VBO
  22707. var vertices = [];
  22708. vertices.push(1, 1);
  22709. vertices.push(-1, 1);
  22710. vertices.push(-1, -1);
  22711. vertices.push(1, -1);
  22712. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22713. // Indices
  22714. var indices = [];
  22715. indices.push(0);
  22716. indices.push(1);
  22717. indices.push(2);
  22718. indices.push(0);
  22719. indices.push(2);
  22720. indices.push(3);
  22721. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22722. };
  22723. // Methods
  22724. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22725. var postProcesses = this._scene.activeCamera._postProcesses;
  22726. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22727. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22728. return false;
  22729. }
  22730. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22731. return true;
  22732. };
  22733. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22734. var engine = this._scene.getEngine();
  22735. for (var index = 0; index < postProcesses.length; index++) {
  22736. if (index < postProcesses.length - 1) {
  22737. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22738. }
  22739. else {
  22740. if (targetTexture) {
  22741. engine.bindFramebuffer(targetTexture);
  22742. }
  22743. else {
  22744. engine.restoreDefaultFramebuffer();
  22745. }
  22746. }
  22747. var pp = postProcesses[index];
  22748. var effect = pp.apply();
  22749. if (effect) {
  22750. if (pp.onBeforeRender) {
  22751. pp.onBeforeRender(effect);
  22752. }
  22753. // VBOs
  22754. this._prepareBuffers();
  22755. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22756. // Draw order
  22757. engine.draw(true, 0, 6);
  22758. if (pp.onAfterRender) {
  22759. pp.onAfterRender(effect);
  22760. }
  22761. }
  22762. }
  22763. // Restore depth buffer
  22764. engine.setDepthBuffer(true);
  22765. engine.setDepthWrite(true);
  22766. };
  22767. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22768. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22769. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22770. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22771. return;
  22772. }
  22773. var engine = this._scene.getEngine();
  22774. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22775. if (index < postProcessesTakenIndices.length - 1) {
  22776. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22777. }
  22778. else {
  22779. if (targetTexture) {
  22780. engine.bindFramebuffer(targetTexture);
  22781. }
  22782. else {
  22783. engine.restoreDefaultFramebuffer();
  22784. }
  22785. }
  22786. if (doNotPresent) {
  22787. break;
  22788. }
  22789. var pp = postProcesses[postProcessesTakenIndices[index]];
  22790. var effect = pp.apply();
  22791. if (effect) {
  22792. if (pp.onBeforeRender) {
  22793. pp.onBeforeRender(effect);
  22794. }
  22795. // VBOs
  22796. this._prepareBuffers();
  22797. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22798. // Draw order
  22799. engine.draw(true, 0, 6);
  22800. if (pp.onAfterRender) {
  22801. pp.onAfterRender(effect);
  22802. }
  22803. }
  22804. }
  22805. // Restore depth buffer
  22806. engine.setDepthBuffer(true);
  22807. engine.setDepthWrite(true);
  22808. };
  22809. PostProcessManager.prototype.dispose = function () {
  22810. if (this._vertexBuffer) {
  22811. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22812. this._vertexBuffer = null;
  22813. }
  22814. if (this._indexBuffer) {
  22815. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22816. this._indexBuffer = null;
  22817. }
  22818. };
  22819. return PostProcessManager;
  22820. })();
  22821. BABYLON.PostProcessManager = PostProcessManager;
  22822. })(BABYLON || (BABYLON = {}));
  22823. var BABYLON;
  22824. (function (BABYLON) {
  22825. var PassPostProcess = (function (_super) {
  22826. __extends(PassPostProcess, _super);
  22827. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22828. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22829. }
  22830. return PassPostProcess;
  22831. })(BABYLON.PostProcess);
  22832. BABYLON.PassPostProcess = PassPostProcess;
  22833. })(BABYLON || (BABYLON = {}));
  22834. var BABYLON;
  22835. (function (BABYLON) {
  22836. var BlurPostProcess = (function (_super) {
  22837. __extends(BlurPostProcess, _super);
  22838. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22839. var _this = this;
  22840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22841. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22842. this.direction = direction;
  22843. this.blurWidth = blurWidth;
  22844. this.onApply = function (effect) {
  22845. effect.setFloat2("screenSize", _this.width, _this.height);
  22846. effect.setVector2("direction", _this.direction);
  22847. effect.setFloat("blurWidth", _this.blurWidth);
  22848. };
  22849. }
  22850. return BlurPostProcess;
  22851. })(BABYLON.PostProcess);
  22852. BABYLON.BlurPostProcess = BlurPostProcess;
  22853. })(BABYLON || (BABYLON = {}));
  22854. var BABYLON;
  22855. (function (BABYLON) {
  22856. var RefractionPostProcess = (function (_super) {
  22857. __extends(RefractionPostProcess, _super);
  22858. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22859. var _this = this;
  22860. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22861. this.color = color;
  22862. this.depth = depth;
  22863. this.colorLevel = colorLevel;
  22864. this.onActivate = function (cam) {
  22865. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22866. };
  22867. this.onApply = function (effect) {
  22868. effect.setColor3("baseColor", _this.color);
  22869. effect.setFloat("depth", _this.depth);
  22870. effect.setFloat("colorLevel", _this.colorLevel);
  22871. effect.setTexture("refractionSampler", _this._refRexture);
  22872. };
  22873. }
  22874. // Methods
  22875. RefractionPostProcess.prototype.dispose = function (camera) {
  22876. if (this._refRexture) {
  22877. this._refRexture.dispose();
  22878. }
  22879. _super.prototype.dispose.call(this, camera);
  22880. };
  22881. return RefractionPostProcess;
  22882. })(BABYLON.PostProcess);
  22883. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22884. })(BABYLON || (BABYLON = {}));
  22885. var BABYLON;
  22886. (function (BABYLON) {
  22887. var BlackAndWhitePostProcess = (function (_super) {
  22888. __extends(BlackAndWhitePostProcess, _super);
  22889. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22890. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22891. }
  22892. return BlackAndWhitePostProcess;
  22893. })(BABYLON.PostProcess);
  22894. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22895. })(BABYLON || (BABYLON = {}));
  22896. var BABYLON;
  22897. (function (BABYLON) {
  22898. var ConvolutionPostProcess = (function (_super) {
  22899. __extends(ConvolutionPostProcess, _super);
  22900. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22901. var _this = this;
  22902. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22903. this.kernel = kernel;
  22904. this.onApply = function (effect) {
  22905. effect.setFloat2("screenSize", _this.width, _this.height);
  22906. effect.setArray("kernel", _this.kernel);
  22907. };
  22908. }
  22909. // Statics
  22910. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22911. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22912. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22913. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22914. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22915. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22916. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22917. return ConvolutionPostProcess;
  22918. })(BABYLON.PostProcess);
  22919. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22920. })(BABYLON || (BABYLON = {}));
  22921. var BABYLON;
  22922. (function (BABYLON) {
  22923. var FilterPostProcess = (function (_super) {
  22924. __extends(FilterPostProcess, _super);
  22925. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22926. var _this = this;
  22927. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22928. this.kernelMatrix = kernelMatrix;
  22929. this.onApply = function (effect) {
  22930. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22931. };
  22932. }
  22933. return FilterPostProcess;
  22934. })(BABYLON.PostProcess);
  22935. BABYLON.FilterPostProcess = FilterPostProcess;
  22936. })(BABYLON || (BABYLON = {}));
  22937. var BABYLON;
  22938. (function (BABYLON) {
  22939. var FxaaPostProcess = (function (_super) {
  22940. __extends(FxaaPostProcess, _super);
  22941. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22942. var _this = this;
  22943. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22944. this.onSizeChanged = function () {
  22945. _this.texelWidth = 1.0 / _this.width;
  22946. _this.texelHeight = 1.0 / _this.height;
  22947. };
  22948. this.onApply = function (effect) {
  22949. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22950. };
  22951. }
  22952. return FxaaPostProcess;
  22953. })(BABYLON.PostProcess);
  22954. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22955. })(BABYLON || (BABYLON = {}));
  22956. var BABYLON;
  22957. (function (BABYLON) {
  22958. var StereoscopicInterlacePostProcess = (function (_super) {
  22959. __extends(StereoscopicInterlacePostProcess, _super);
  22960. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22961. var _this = this;
  22962. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22963. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22964. this.onSizeChanged = function () {
  22965. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22966. };
  22967. this.onApply = function (effect) {
  22968. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22969. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22970. };
  22971. }
  22972. return StereoscopicInterlacePostProcess;
  22973. })(BABYLON.PostProcess);
  22974. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22975. })(BABYLON || (BABYLON = {}));
  22976. var BABYLON;
  22977. (function (BABYLON) {
  22978. var LensFlare = (function () {
  22979. function LensFlare(size, position, color, imgUrl, system) {
  22980. this.size = size;
  22981. this.position = position;
  22982. this.dispose = function () {
  22983. if (this.texture) {
  22984. this.texture.dispose();
  22985. }
  22986. // Remove from scene
  22987. var index = this._system.lensFlares.indexOf(this);
  22988. this._system.lensFlares.splice(index, 1);
  22989. };
  22990. this.color = color || new BABYLON.Color3(1, 1, 1);
  22991. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22992. this._system = system;
  22993. system.lensFlares.push(this);
  22994. }
  22995. return LensFlare;
  22996. })();
  22997. BABYLON.LensFlare = LensFlare;
  22998. })(BABYLON || (BABYLON = {}));
  22999. var BABYLON;
  23000. (function (BABYLON) {
  23001. var LensFlareSystem = (function () {
  23002. function LensFlareSystem(name, emitter, scene) {
  23003. this.name = name;
  23004. this.lensFlares = new Array();
  23005. this.borderLimit = 300;
  23006. this._vertexDeclaration = [2];
  23007. this._vertexStrideSize = 2 * 4;
  23008. this._isEnabled = true;
  23009. this._scene = scene;
  23010. this._emitter = emitter;
  23011. scene.lensFlareSystems.push(this);
  23012. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23013. // VBO
  23014. var vertices = [];
  23015. vertices.push(1, 1);
  23016. vertices.push(-1, 1);
  23017. vertices.push(-1, -1);
  23018. vertices.push(1, -1);
  23019. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23020. // Indices
  23021. var indices = [];
  23022. indices.push(0);
  23023. indices.push(1);
  23024. indices.push(2);
  23025. indices.push(0);
  23026. indices.push(2);
  23027. indices.push(3);
  23028. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23029. // Effects
  23030. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23031. }
  23032. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23033. get: function () {
  23034. return this._isEnabled;
  23035. },
  23036. set: function (value) {
  23037. this._isEnabled = value;
  23038. },
  23039. enumerable: true,
  23040. configurable: true
  23041. });
  23042. LensFlareSystem.prototype.getScene = function () {
  23043. return this._scene;
  23044. };
  23045. LensFlareSystem.prototype.getEmitter = function () {
  23046. return this._emitter;
  23047. };
  23048. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23049. this._emitter = newEmitter;
  23050. };
  23051. LensFlareSystem.prototype.getEmitterPosition = function () {
  23052. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23053. };
  23054. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23055. var position = this.getEmitterPosition();
  23056. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23057. this._positionX = position.x;
  23058. this._positionY = position.y;
  23059. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23060. if (position.z > 0) {
  23061. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23062. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23063. return true;
  23064. }
  23065. }
  23066. return false;
  23067. };
  23068. LensFlareSystem.prototype._isVisible = function () {
  23069. if (!this._isEnabled) {
  23070. return false;
  23071. }
  23072. var emitterPosition = this.getEmitterPosition();
  23073. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23074. var distance = direction.length();
  23075. direction.normalize();
  23076. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23077. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23078. return !pickInfo.hit || pickInfo.distance > distance;
  23079. };
  23080. LensFlareSystem.prototype.render = function () {
  23081. if (!this._effect.isReady())
  23082. return false;
  23083. var engine = this._scene.getEngine();
  23084. var viewport = this._scene.activeCamera.viewport;
  23085. var globalViewport = viewport.toGlobal(engine);
  23086. // Position
  23087. if (!this.computeEffectivePosition(globalViewport)) {
  23088. return false;
  23089. }
  23090. // Visibility
  23091. if (!this._isVisible()) {
  23092. return false;
  23093. }
  23094. // Intensity
  23095. var awayX;
  23096. var awayY;
  23097. if (this._positionX < this.borderLimit + globalViewport.x) {
  23098. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23099. }
  23100. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23101. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23102. }
  23103. else {
  23104. awayX = 0;
  23105. }
  23106. if (this._positionY < this.borderLimit + globalViewport.y) {
  23107. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23108. }
  23109. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23110. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23111. }
  23112. else {
  23113. awayY = 0;
  23114. }
  23115. var away = (awayX > awayY) ? awayX : awayY;
  23116. if (away > this.borderLimit) {
  23117. away = this.borderLimit;
  23118. }
  23119. var intensity = 1.0 - (away / this.borderLimit);
  23120. if (intensity < 0) {
  23121. return false;
  23122. }
  23123. if (intensity > 1.0) {
  23124. intensity = 1.0;
  23125. }
  23126. // Position
  23127. var centerX = globalViewport.x + globalViewport.width / 2;
  23128. var centerY = globalViewport.y + globalViewport.height / 2;
  23129. var distX = centerX - this._positionX;
  23130. var distY = centerY - this._positionY;
  23131. // Effects
  23132. engine.enableEffect(this._effect);
  23133. engine.setState(false);
  23134. engine.setDepthBuffer(false);
  23135. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23136. // VBOs
  23137. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23138. // Flares
  23139. for (var index = 0; index < this.lensFlares.length; index++) {
  23140. var flare = this.lensFlares[index];
  23141. var x = centerX - (distX * flare.position);
  23142. var y = centerY - (distY * flare.position);
  23143. var cw = flare.size;
  23144. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23145. var cx = 2 * (x / globalViewport.width) - 1.0;
  23146. var cy = 1.0 - 2 * (y / globalViewport.height);
  23147. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23148. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23149. // Texture
  23150. this._effect.setTexture("textureSampler", flare.texture);
  23151. // Color
  23152. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23153. // Draw order
  23154. engine.draw(true, 0, 6);
  23155. }
  23156. engine.setDepthBuffer(true);
  23157. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23158. return true;
  23159. };
  23160. LensFlareSystem.prototype.dispose = function () {
  23161. if (this._vertexBuffer) {
  23162. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23163. this._vertexBuffer = null;
  23164. }
  23165. if (this._indexBuffer) {
  23166. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23167. this._indexBuffer = null;
  23168. }
  23169. while (this.lensFlares.length) {
  23170. this.lensFlares[0].dispose();
  23171. }
  23172. // Remove from scene
  23173. var index = this._scene.lensFlareSystems.indexOf(this);
  23174. this._scene.lensFlareSystems.splice(index, 1);
  23175. };
  23176. return LensFlareSystem;
  23177. })();
  23178. BABYLON.LensFlareSystem = LensFlareSystem;
  23179. })(BABYLON || (BABYLON = {}));
  23180. var BABYLON;
  23181. (function (BABYLON) {
  23182. var CannonJSPlugin = (function () {
  23183. function CannonJSPlugin() {
  23184. this._registeredMeshes = [];
  23185. this._physicsMaterials = [];
  23186. this.updateBodyPosition = function (mesh) {
  23187. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23188. var registeredMesh = this._registeredMeshes[index];
  23189. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23190. var body = registeredMesh.body;
  23191. var center = mesh.getBoundingInfo().boundingBox.center;
  23192. body.position.set(center.x, center.z, center.y);
  23193. body.quaternion.x = mesh.rotationQuaternion.x;
  23194. body.quaternion.z = mesh.rotationQuaternion.y;
  23195. body.quaternion.y = mesh.rotationQuaternion.z;
  23196. body.quaternion.w = -mesh.rotationQuaternion.w;
  23197. return;
  23198. }
  23199. }
  23200. };
  23201. }
  23202. CannonJSPlugin.prototype.initialize = function (iterations) {
  23203. if (iterations === void 0) { iterations = 10; }
  23204. this._world = new CANNON.World();
  23205. this._world.broadphase = new CANNON.NaiveBroadphase();
  23206. this._world.solver.iterations = iterations;
  23207. };
  23208. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23209. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23210. };
  23211. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23212. this._world.step(delta);
  23213. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23214. var registeredMesh = this._registeredMeshes[index];
  23215. if (registeredMesh.isChild) {
  23216. continue;
  23217. }
  23218. // Body position
  23219. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23220. var deltaPos = registeredMesh.delta;
  23221. if (deltaPos) {
  23222. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23223. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23224. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23225. }
  23226. else {
  23227. registeredMesh.mesh.position.x = bodyX;
  23228. registeredMesh.mesh.position.y = bodyZ;
  23229. registeredMesh.mesh.position.z = bodyY;
  23230. }
  23231. if (!registeredMesh.mesh.rotationQuaternion) {
  23232. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23233. }
  23234. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23235. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23236. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23237. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23238. }
  23239. };
  23240. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23241. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23242. };
  23243. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23244. this.unregisterMesh(mesh);
  23245. mesh.computeWorldMatrix(true);
  23246. switch (impostor) {
  23247. case BABYLON.PhysicsEngine.SphereImpostor:
  23248. var bbox = mesh.getBoundingInfo().boundingBox;
  23249. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23250. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23251. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23252. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23253. case BABYLON.PhysicsEngine.BoxImpostor:
  23254. bbox = mesh.getBoundingInfo().boundingBox;
  23255. var min = bbox.minimumWorld;
  23256. var max = bbox.maximumWorld;
  23257. var box = max.subtract(min).scale(0.5);
  23258. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23259. case BABYLON.PhysicsEngine.PlaneImpostor:
  23260. return this._createPlane(mesh, options);
  23261. case BABYLON.PhysicsEngine.MeshImpostor:
  23262. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23263. var rawFaces = mesh.getIndices();
  23264. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23265. }
  23266. return null;
  23267. };
  23268. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23269. var shape = new CANNON.Sphere(radius);
  23270. if (!options) {
  23271. return shape;
  23272. }
  23273. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23274. };
  23275. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23276. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23277. if (!options) {
  23278. return shape;
  23279. }
  23280. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23281. };
  23282. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23283. var shape = new CANNON.Plane();
  23284. if (!options) {
  23285. return shape;
  23286. }
  23287. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23288. };
  23289. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23290. var verts = [], faces = [];
  23291. mesh.computeWorldMatrix(true);
  23292. // Get vertices
  23293. for (var i = 0; i < rawVerts.length; i += 3) {
  23294. var transformed = BABYLON.Vector3.Zero();
  23295. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23296. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23297. }
  23298. // Get faces
  23299. for (var j = 0; j < rawFaces.length; j += 3) {
  23300. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23301. }
  23302. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23303. if (!options) {
  23304. return shape;
  23305. }
  23306. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23307. };
  23308. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23309. var index;
  23310. var mat;
  23311. for (index = 0; index < this._physicsMaterials.length; index++) {
  23312. mat = this._physicsMaterials[index];
  23313. if (mat.friction === friction && mat.restitution === restitution) {
  23314. return mat;
  23315. }
  23316. }
  23317. var currentMat = new CANNON.Material();
  23318. currentMat.friction = friction;
  23319. currentMat.restitution = restitution;
  23320. this._physicsMaterials.push(currentMat);
  23321. for (index = 0; index < this._physicsMaterials.length; index++) {
  23322. mat = this._physicsMaterials[index];
  23323. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23324. contactMaterial.contactEquationStiffness = 1e10;
  23325. contactMaterial.contactEquationRegularizationTime = 10;
  23326. this._world.addContactMaterial(contactMaterial);
  23327. }
  23328. return currentMat;
  23329. };
  23330. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23331. var initialRotation = null;
  23332. if (mesh.rotationQuaternion) {
  23333. initialRotation = mesh.rotationQuaternion.clone();
  23334. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23335. }
  23336. // The delta between the mesh position and the mesh bounding box center
  23337. var bbox = mesh.getBoundingInfo().boundingBox;
  23338. var deltaPosition = mesh.position.subtract(bbox.center);
  23339. var material = this._addMaterial(friction, restitution);
  23340. var body = new CANNON.RigidBody(mass, shape, material);
  23341. if (initialRotation) {
  23342. body.quaternion.x = initialRotation.x;
  23343. body.quaternion.z = initialRotation.y;
  23344. body.quaternion.y = initialRotation.z;
  23345. body.quaternion.w = -initialRotation.w;
  23346. }
  23347. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23348. this._world.add(body);
  23349. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23350. return body;
  23351. };
  23352. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23353. var compoundShape = new CANNON.Compound();
  23354. for (var index = 0; index < parts.length; index++) {
  23355. var mesh = parts[index].mesh;
  23356. var shape = this.registerMesh(mesh, parts[index].impostor);
  23357. if (index == 0) {
  23358. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23359. }
  23360. else {
  23361. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23362. }
  23363. }
  23364. var initialMesh = parts[0].mesh;
  23365. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23366. body.parts = parts;
  23367. return body;
  23368. };
  23369. CannonJSPlugin.prototype._unbindBody = function (body) {
  23370. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23371. var registeredMesh = this._registeredMeshes[index];
  23372. if (registeredMesh.body === body) {
  23373. registeredMesh.body = null;
  23374. registeredMesh.delta = 0;
  23375. }
  23376. }
  23377. };
  23378. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23379. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23380. var registeredMesh = this._registeredMeshes[index];
  23381. if (registeredMesh.mesh === mesh) {
  23382. // Remove body
  23383. if (registeredMesh.body) {
  23384. this._world.remove(registeredMesh.body);
  23385. this._unbindBody(registeredMesh.body);
  23386. }
  23387. this._registeredMeshes.splice(index, 1);
  23388. return;
  23389. }
  23390. }
  23391. };
  23392. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23393. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23394. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23395. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23396. var registeredMesh = this._registeredMeshes[index];
  23397. if (registeredMesh.mesh === mesh) {
  23398. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23399. return;
  23400. }
  23401. }
  23402. };
  23403. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23404. var body1 = null, body2 = null;
  23405. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23406. var registeredMesh = this._registeredMeshes[index];
  23407. if (registeredMesh.mesh === mesh1) {
  23408. body1 = registeredMesh.body;
  23409. }
  23410. else if (registeredMesh.mesh === mesh2) {
  23411. body2 = registeredMesh.body;
  23412. }
  23413. }
  23414. if (!body1 || !body2) {
  23415. return false;
  23416. }
  23417. 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));
  23418. this._world.addConstraint(constraint);
  23419. return true;
  23420. };
  23421. CannonJSPlugin.prototype.dispose = function () {
  23422. while (this._registeredMeshes.length) {
  23423. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23424. }
  23425. };
  23426. CannonJSPlugin.prototype.isSupported = function () {
  23427. return window.CANNON !== undefined;
  23428. };
  23429. return CannonJSPlugin;
  23430. })();
  23431. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23432. })(BABYLON || (BABYLON = {}));
  23433. var BABYLON;
  23434. (function (BABYLON) {
  23435. var OimoJSPlugin = (function () {
  23436. function OimoJSPlugin() {
  23437. this._registeredMeshes = [];
  23438. /**
  23439. * Update the body position according to the mesh position
  23440. * @param mesh
  23441. */
  23442. this.updateBodyPosition = function (mesh) {
  23443. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23444. var registeredMesh = this._registeredMeshes[index];
  23445. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23446. var body = registeredMesh.body.body;
  23447. mesh.computeWorldMatrix(true);
  23448. var center = mesh.getBoundingInfo().boundingBox.center;
  23449. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23450. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23451. body.sleeping = false;
  23452. return;
  23453. }
  23454. // Case where the parent has been updated
  23455. if (registeredMesh.mesh.parent === mesh) {
  23456. mesh.computeWorldMatrix(true);
  23457. registeredMesh.mesh.computeWorldMatrix(true);
  23458. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23459. var absoluteRotation = mesh.rotation;
  23460. body = registeredMesh.body.body;
  23461. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23462. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23463. body.sleeping = false;
  23464. return;
  23465. }
  23466. }
  23467. };
  23468. }
  23469. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23470. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23471. };
  23472. OimoJSPlugin.prototype.initialize = function (iterations) {
  23473. this._world = new OIMO.World();
  23474. this._world.clear();
  23475. };
  23476. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23477. this._world.gravity = gravity;
  23478. };
  23479. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23480. var body = null;
  23481. this.unregisterMesh(mesh);
  23482. mesh.computeWorldMatrix(true);
  23483. var initialRotation = null;
  23484. if (mesh.rotationQuaternion) {
  23485. initialRotation = mesh.rotationQuaternion.clone();
  23486. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23487. mesh.computeWorldMatrix(true);
  23488. }
  23489. var bbox = mesh.getBoundingInfo().boundingBox;
  23490. // The delta between the mesh position and the mesh bounding box center
  23491. var deltaPosition = mesh.position.subtract(bbox.center);
  23492. // Transform delta position with the rotation
  23493. if (initialRotation) {
  23494. var m = new BABYLON.Matrix();
  23495. initialRotation.toRotationMatrix(m);
  23496. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23497. }
  23498. // register mesh
  23499. switch (impostor) {
  23500. case BABYLON.PhysicsEngine.SphereImpostor:
  23501. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23502. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23503. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23504. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23505. body = new OIMO.Body({
  23506. type: 'sphere',
  23507. size: [size],
  23508. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23509. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23510. move: options.mass != 0,
  23511. config: [options.mass, options.friction, options.restitution],
  23512. world: this._world
  23513. });
  23514. break;
  23515. case BABYLON.PhysicsEngine.PlaneImpostor:
  23516. //Oimo "fakes" a cylinder as a box, so why don't we!
  23517. case BABYLON.PhysicsEngine.CylinderImpostor:
  23518. case BABYLON.PhysicsEngine.BoxImpostor:
  23519. var min = bbox.minimumWorld;
  23520. var max = bbox.maximumWorld;
  23521. var box = max.subtract(min);
  23522. var sizeX = this._checkWithEpsilon(box.x);
  23523. var sizeY = this._checkWithEpsilon(box.y);
  23524. var sizeZ = this._checkWithEpsilon(box.z);
  23525. body = new OIMO.Body({
  23526. type: 'box',
  23527. size: [sizeX, sizeY, sizeZ],
  23528. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23529. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23530. move: options.mass != 0,
  23531. config: [options.mass, options.friction, options.restitution],
  23532. world: this._world
  23533. });
  23534. break;
  23535. }
  23536. //If quaternion was set as the rotation of the object
  23537. if (initialRotation) {
  23538. //We have to access the rigid body's properties to set the quaternion.
  23539. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23540. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23541. //update the internal rotation matrix
  23542. body.body.syncShapes();
  23543. }
  23544. this._registeredMeshes.push({
  23545. mesh: mesh,
  23546. body: body,
  23547. delta: deltaPosition
  23548. });
  23549. return body;
  23550. };
  23551. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23552. var types = [], sizes = [], positions = [], rotations = [];
  23553. var initialMesh = parts[0].mesh;
  23554. for (var index = 0; index < parts.length; index++) {
  23555. var part = parts[index];
  23556. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23557. types.push(bodyParameters.type);
  23558. sizes.push.apply(sizes, bodyParameters.size);
  23559. positions.push.apply(positions, bodyParameters.pos);
  23560. rotations.push.apply(rotations, bodyParameters.rot);
  23561. }
  23562. var body = new OIMO.Body({
  23563. type: types,
  23564. size: sizes,
  23565. pos: positions,
  23566. rot: rotations,
  23567. move: options.mass != 0,
  23568. config: [options.mass, options.friction, options.restitution],
  23569. world: this._world
  23570. });
  23571. this._registeredMeshes.push({
  23572. mesh: initialMesh,
  23573. body: body
  23574. });
  23575. return body;
  23576. };
  23577. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23578. var bodyParameters = null;
  23579. var mesh = part.mesh;
  23580. // We need the bounding box/sphere info to compute the physics body
  23581. mesh.computeWorldMatrix();
  23582. switch (part.impostor) {
  23583. case BABYLON.PhysicsEngine.SphereImpostor:
  23584. var bbox = mesh.getBoundingInfo().boundingBox;
  23585. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23586. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23587. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23588. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23589. bodyParameters = {
  23590. type: 'sphere',
  23591. /* bug with oimo : sphere needs 3 sizes in this case */
  23592. size: [size, -1, -1],
  23593. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23594. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23595. };
  23596. break;
  23597. case BABYLON.PhysicsEngine.PlaneImpostor:
  23598. case BABYLON.PhysicsEngine.BoxImpostor:
  23599. bbox = mesh.getBoundingInfo().boundingBox;
  23600. var min = bbox.minimumWorld;
  23601. var max = bbox.maximumWorld;
  23602. var box = max.subtract(min);
  23603. var sizeX = this._checkWithEpsilon(box.x);
  23604. var sizeY = this._checkWithEpsilon(box.y);
  23605. var sizeZ = this._checkWithEpsilon(box.z);
  23606. var relativePosition = mesh.position;
  23607. bodyParameters = {
  23608. type: 'box',
  23609. size: [sizeX, sizeY, sizeZ],
  23610. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23611. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23612. };
  23613. break;
  23614. }
  23615. return bodyParameters;
  23616. };
  23617. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23618. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23619. var registeredMesh = this._registeredMeshes[index];
  23620. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23621. if (registeredMesh.body) {
  23622. this._world.removeRigidBody(registeredMesh.body.body);
  23623. this._unbindBody(registeredMesh.body);
  23624. }
  23625. this._registeredMeshes.splice(index, 1);
  23626. return;
  23627. }
  23628. }
  23629. };
  23630. OimoJSPlugin.prototype._unbindBody = function (body) {
  23631. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23632. var registeredMesh = this._registeredMeshes[index];
  23633. if (registeredMesh.body === body) {
  23634. registeredMesh.body = null;
  23635. }
  23636. }
  23637. };
  23638. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23639. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23640. var registeredMesh = this._registeredMeshes[index];
  23641. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23642. // Get object mass to have a behaviour similar to cannon.js
  23643. var mass = registeredMesh.body.body.massInfo.mass;
  23644. // The force is scaled with the mass of object
  23645. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23646. return;
  23647. }
  23648. }
  23649. };
  23650. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23651. var body1 = null, body2 = null;
  23652. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23653. var registeredMesh = this._registeredMeshes[index];
  23654. if (registeredMesh.mesh === mesh1) {
  23655. body1 = registeredMesh.body.body;
  23656. }
  23657. else if (registeredMesh.mesh === mesh2) {
  23658. body2 = registeredMesh.body.body;
  23659. }
  23660. }
  23661. if (!body1 || !body2) {
  23662. return false;
  23663. }
  23664. if (!options) {
  23665. options = {};
  23666. }
  23667. new OIMO.Link({
  23668. type: options.type,
  23669. body1: body1,
  23670. body2: body2,
  23671. min: options.min,
  23672. max: options.max,
  23673. axe1: options.axe1,
  23674. axe2: options.axe2,
  23675. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23676. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23677. collision: options.collision,
  23678. spring: options.spring,
  23679. world: this._world
  23680. });
  23681. return true;
  23682. };
  23683. OimoJSPlugin.prototype.dispose = function () {
  23684. this._world.clear();
  23685. while (this._registeredMeshes.length) {
  23686. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23687. }
  23688. };
  23689. OimoJSPlugin.prototype.isSupported = function () {
  23690. return OIMO !== undefined;
  23691. };
  23692. OimoJSPlugin.prototype._getLastShape = function (body) {
  23693. var lastShape = body.shapes;
  23694. while (lastShape.next) {
  23695. lastShape = lastShape.next;
  23696. }
  23697. return lastShape;
  23698. };
  23699. OimoJSPlugin.prototype.runOneStep = function (time) {
  23700. this._world.step();
  23701. // Update the position of all registered meshes
  23702. var i = this._registeredMeshes.length;
  23703. var m;
  23704. while (i--) {
  23705. var body = this._registeredMeshes[i].body.body;
  23706. var mesh = this._registeredMeshes[i].mesh;
  23707. var delta = this._registeredMeshes[i].delta;
  23708. if (!body.sleeping) {
  23709. if (body.shapes.next) {
  23710. var parentShape = this._getLastShape(body);
  23711. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23712. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23713. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23714. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23715. if (!mesh.rotationQuaternion) {
  23716. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23717. }
  23718. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23719. mesh.computeWorldMatrix();
  23720. }
  23721. else {
  23722. m = body.getMatrix();
  23723. mtx = BABYLON.Matrix.FromArray(m);
  23724. // Body position
  23725. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23726. if (!delta) {
  23727. mesh.position.x = bodyX;
  23728. mesh.position.y = bodyY;
  23729. mesh.position.z = bodyZ;
  23730. }
  23731. else {
  23732. mesh.position.x = bodyX + delta.x;
  23733. mesh.position.y = bodyY + delta.y;
  23734. mesh.position.z = bodyZ + delta.z;
  23735. }
  23736. if (!mesh.rotationQuaternion) {
  23737. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23738. }
  23739. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23740. mesh.computeWorldMatrix();
  23741. }
  23742. }
  23743. }
  23744. };
  23745. return OimoJSPlugin;
  23746. })();
  23747. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23748. })(BABYLON || (BABYLON = {}));
  23749. var BABYLON;
  23750. (function (BABYLON) {
  23751. var PhysicsEngine = (function () {
  23752. function PhysicsEngine(plugin) {
  23753. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23754. }
  23755. PhysicsEngine.prototype._initialize = function (gravity) {
  23756. this._currentPlugin.initialize();
  23757. this._setGravity(gravity);
  23758. };
  23759. PhysicsEngine.prototype._runOneStep = function (delta) {
  23760. if (delta > 0.1) {
  23761. delta = 0.1;
  23762. }
  23763. else if (delta <= 0) {
  23764. delta = 1.0 / 60.0;
  23765. }
  23766. this._currentPlugin.runOneStep(delta);
  23767. };
  23768. PhysicsEngine.prototype._setGravity = function (gravity) {
  23769. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23770. this._currentPlugin.setGravity(this.gravity);
  23771. };
  23772. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23773. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23774. };
  23775. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23776. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23777. };
  23778. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23779. this._currentPlugin.unregisterMesh(mesh);
  23780. };
  23781. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23782. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23783. };
  23784. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23785. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23786. };
  23787. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23788. this._currentPlugin.updateBodyPosition(mesh);
  23789. };
  23790. PhysicsEngine.prototype.dispose = function () {
  23791. this._currentPlugin.dispose();
  23792. };
  23793. PhysicsEngine.prototype.isSupported = function () {
  23794. return this._currentPlugin.isSupported();
  23795. };
  23796. // Statics
  23797. PhysicsEngine.NoImpostor = 0;
  23798. PhysicsEngine.SphereImpostor = 1;
  23799. PhysicsEngine.BoxImpostor = 2;
  23800. PhysicsEngine.PlaneImpostor = 3;
  23801. PhysicsEngine.MeshImpostor = 4;
  23802. PhysicsEngine.CapsuleImpostor = 5;
  23803. PhysicsEngine.ConeImpostor = 6;
  23804. PhysicsEngine.CylinderImpostor = 7;
  23805. PhysicsEngine.ConvexHullImpostor = 8;
  23806. PhysicsEngine.Epsilon = 0.001;
  23807. return PhysicsEngine;
  23808. })();
  23809. BABYLON.PhysicsEngine = PhysicsEngine;
  23810. })(BABYLON || (BABYLON = {}));
  23811. var BABYLON;
  23812. (function (BABYLON) {
  23813. var serializeLight = function (light) {
  23814. var serializationObject = {};
  23815. serializationObject.name = light.name;
  23816. serializationObject.id = light.id;
  23817. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23818. if (light instanceof BABYLON.PointLight) {
  23819. serializationObject.type = 0;
  23820. serializationObject.position = light.position.asArray();
  23821. }
  23822. else if (light instanceof BABYLON.DirectionalLight) {
  23823. serializationObject.type = 1;
  23824. var directionalLight = light;
  23825. serializationObject.position = directionalLight.position.asArray();
  23826. serializationObject.direction = directionalLight.direction.asArray();
  23827. }
  23828. else if (light instanceof BABYLON.SpotLight) {
  23829. serializationObject.type = 2;
  23830. var spotLight = light;
  23831. serializationObject.position = spotLight.position.asArray();
  23832. serializationObject.direction = spotLight.position.asArray();
  23833. serializationObject.angle = spotLight.angle;
  23834. serializationObject.exponent = spotLight.exponent;
  23835. }
  23836. else if (light instanceof BABYLON.HemisphericLight) {
  23837. serializationObject.type = 3;
  23838. var hemisphericLight = light;
  23839. serializationObject.direction = hemisphericLight.direction.asArray();
  23840. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23841. }
  23842. if (light.intensity) {
  23843. serializationObject.intensity = light.intensity;
  23844. }
  23845. serializationObject.range = light.range;
  23846. serializationObject.diffuse = light.diffuse.asArray();
  23847. serializationObject.specular = light.specular.asArray();
  23848. return serializationObject;
  23849. };
  23850. var serializeFresnelParameter = function (fresnelParameter) {
  23851. var serializationObject = {};
  23852. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23853. serializationObject.leftColor = fresnelParameter.leftColor;
  23854. serializationObject.rightColor = fresnelParameter.rightColor;
  23855. serializationObject.bias = fresnelParameter.bias;
  23856. serializationObject.power = fresnelParameter.power;
  23857. return serializationObject;
  23858. };
  23859. var appendAnimations = function (source, destination) {
  23860. if (source.animations) {
  23861. destination.animations = [];
  23862. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23863. var animation = source.animations[animationIndex];
  23864. destination.animations.push(serializeAnimation(animation));
  23865. }
  23866. }
  23867. };
  23868. var serializeCamera = function (camera) {
  23869. var serializationObject = {};
  23870. serializationObject.name = camera.name;
  23871. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23872. serializationObject.id = camera.id;
  23873. serializationObject.position = camera.position.asArray();
  23874. // Parent
  23875. if (camera.parent) {
  23876. serializationObject.parentId = camera.parent.id;
  23877. }
  23878. serializationObject.fov = camera.fov;
  23879. serializationObject.minZ = camera.minZ;
  23880. serializationObject.maxZ = camera.maxZ;
  23881. serializationObject.inertia = camera.inertia;
  23882. //setting the type
  23883. if (camera instanceof BABYLON.FreeCamera) {
  23884. serializationObject.type = "FreeCamera";
  23885. }
  23886. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23887. serializationObject.type = "ArcRotateCamera";
  23888. }
  23889. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23890. serializationObject.type = "AnaglyphArcRotateCamera";
  23891. }
  23892. else if (camera instanceof BABYLON.GamepadCamera) {
  23893. serializationObject.type = "GamepadCamera";
  23894. }
  23895. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23896. serializationObject.type = "AnaglyphFreeCamera";
  23897. }
  23898. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23899. serializationObject.type = "DeviceOrientationCamera";
  23900. }
  23901. else if (camera instanceof BABYLON.FollowCamera) {
  23902. serializationObject.type = "FollowCamera";
  23903. }
  23904. else if (camera instanceof BABYLON.TouchCamera) {
  23905. serializationObject.type = "TouchCamera";
  23906. }
  23907. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23908. serializationObject.type = "VirtualJoysticksCamera";
  23909. }
  23910. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23911. serializationObject.type = "WebVRFreeCamera";
  23912. }
  23913. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23914. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23915. }
  23916. //special properties of specific cameras
  23917. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23918. var arcCamera = camera;
  23919. serializationObject.alpha = arcCamera.alpha;
  23920. serializationObject.beta = arcCamera.beta;
  23921. serializationObject.radius = arcCamera.radius;
  23922. if (arcCamera.target && arcCamera.target.id) {
  23923. serializationObject.lockedTargetId = arcCamera.target.id;
  23924. }
  23925. }
  23926. else if (camera instanceof BABYLON.FollowCamera) {
  23927. var followCam = camera;
  23928. serializationObject.radius = followCam.radius;
  23929. serializationObject.heightOffset = followCam.heightOffset;
  23930. serializationObject.rotationOffset = followCam.rotationOffset;
  23931. }
  23932. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23933. //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.
  23934. if (camera['_interaxialDistance'] !== undefined) {
  23935. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  23936. }
  23937. }
  23938. //general properties that not all cameras have. The [] is due to typescript's type safety
  23939. if (camera['speed'] !== undefined) {
  23940. serializationObject.speed = camera['speed'];
  23941. }
  23942. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23943. serializationObject.target = camera['target'].asArray();
  23944. }
  23945. // Target
  23946. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23947. serializationObject.rotation = camera['rotation'].asArray();
  23948. }
  23949. // Locked target
  23950. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23951. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23952. }
  23953. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23954. serializationObject.applyGravity = camera['applyGravity'] || false;
  23955. if (camera['ellipsoid']) {
  23956. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23957. }
  23958. // Animations
  23959. appendAnimations(camera, serializationObject);
  23960. // Layer mask
  23961. serializationObject.layerMask = camera.layerMask;
  23962. return serializationObject;
  23963. };
  23964. var serializeAnimation = function (animation) {
  23965. var serializationObject = {};
  23966. serializationObject.name = animation.name;
  23967. serializationObject.property = animation.targetProperty;
  23968. serializationObject.framePerSecond = animation.framePerSecond;
  23969. serializationObject.dataType = animation.dataType;
  23970. serializationObject.loopBehavior = animation.loopMode;
  23971. var dataType = animation.dataType;
  23972. serializationObject.keys = [];
  23973. var keys = animation.getKeys();
  23974. for (var index = 0; index < keys.length; index++) {
  23975. var animationKey = keys[index];
  23976. var key = {};
  23977. key.frame = animationKey.frame;
  23978. switch (dataType) {
  23979. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23980. key.values = [animationKey.value];
  23981. break;
  23982. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23983. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23984. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23985. key.values = animationKey.value.asArray();
  23986. break;
  23987. }
  23988. serializationObject.keys.push(key);
  23989. }
  23990. return serializationObject;
  23991. };
  23992. var serializeMultiMaterial = function (material) {
  23993. var serializationObject = {};
  23994. serializationObject.name = material.name;
  23995. serializationObject.id = material.id;
  23996. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23997. serializationObject.materials = [];
  23998. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23999. var subMat = material.subMaterials[matIndex];
  24000. if (subMat) {
  24001. serializationObject.materials.push(subMat.id);
  24002. }
  24003. else {
  24004. serializationObject.materials.push(null);
  24005. }
  24006. }
  24007. return serializationObject;
  24008. };
  24009. var serializeMaterial = function (material) {
  24010. var serializationObject = {};
  24011. serializationObject.name = material.name;
  24012. serializationObject.ambient = material.ambientColor.asArray();
  24013. serializationObject.diffuse = material.diffuseColor.asArray();
  24014. serializationObject.specular = material.specularColor.asArray();
  24015. serializationObject.specularPower = material.specularPower;
  24016. serializationObject.emissive = material.emissiveColor.asArray();
  24017. serializationObject.alpha = material.alpha;
  24018. serializationObject.id = material.id;
  24019. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24020. serializationObject.backFaceCulling = material.backFaceCulling;
  24021. if (material.diffuseTexture) {
  24022. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24023. }
  24024. if (material.diffuseFresnelParameters) {
  24025. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24026. }
  24027. if (material.ambientTexture) {
  24028. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24029. }
  24030. if (material.opacityTexture) {
  24031. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24032. }
  24033. if (material.opacityFresnelParameters) {
  24034. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24035. }
  24036. if (material.reflectionTexture) {
  24037. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24038. }
  24039. if (material.reflectionFresnelParameters) {
  24040. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24041. }
  24042. if (material.emissiveTexture) {
  24043. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24044. }
  24045. if (material.emissiveFresnelParameters) {
  24046. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24047. }
  24048. if (material.specularTexture) {
  24049. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24050. }
  24051. if (material.bumpTexture) {
  24052. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24053. }
  24054. return serializationObject;
  24055. };
  24056. var serializeTexture = function (texture) {
  24057. var serializationObject = {};
  24058. if (!texture.name) {
  24059. return null;
  24060. }
  24061. if (texture instanceof BABYLON.CubeTexture) {
  24062. serializationObject.name = texture.name;
  24063. serializationObject.hasAlpha = texture.hasAlpha;
  24064. serializationObject.isCube = true;
  24065. serializationObject.level = texture.level;
  24066. serializationObject.coordinatesMode = texture.coordinatesMode;
  24067. return serializationObject;
  24068. }
  24069. if (texture instanceof BABYLON.MirrorTexture) {
  24070. var mirrorTexture = texture;
  24071. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24072. serializationObject.renderList = [];
  24073. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  24074. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24075. }
  24076. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24077. }
  24078. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24079. var renderTargetTexture = texture;
  24080. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24081. serializationObject.renderList = [];
  24082. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24083. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24084. }
  24085. }
  24086. var regularTexture = texture;
  24087. serializationObject.name = texture.name;
  24088. serializationObject.hasAlpha = texture.hasAlpha;
  24089. serializationObject.level = texture.level;
  24090. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24091. serializationObject.coordinatesMode = texture.coordinatesMode;
  24092. serializationObject.uOffset = regularTexture.uOffset;
  24093. serializationObject.vOffset = regularTexture.vOffset;
  24094. serializationObject.uScale = regularTexture.uScale;
  24095. serializationObject.vScale = regularTexture.vScale;
  24096. serializationObject.uAng = regularTexture.uAng;
  24097. serializationObject.vAng = regularTexture.vAng;
  24098. serializationObject.wAng = regularTexture.wAng;
  24099. serializationObject.wrapU = texture.wrapU;
  24100. serializationObject.wrapV = texture.wrapV;
  24101. // Animations
  24102. appendAnimations(texture, serializationObject);
  24103. return serializationObject;
  24104. };
  24105. var serializeSkeleton = function (skeleton) {
  24106. var serializationObject = {};
  24107. serializationObject.name = skeleton.name;
  24108. serializationObject.id = skeleton.id;
  24109. serializationObject.bones = [];
  24110. for (var index = 0; index < skeleton.bones.length; index++) {
  24111. var bone = skeleton.bones[index];
  24112. var serializedBone = {
  24113. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24114. name: bone.name,
  24115. matrix: bone.getLocalMatrix().toArray()
  24116. };
  24117. serializationObject.bones.push(serializedBone);
  24118. if (bone.animations && bone.animations.length > 0) {
  24119. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24120. }
  24121. }
  24122. return serializationObject;
  24123. };
  24124. var serializeParticleSystem = function (particleSystem) {
  24125. var serializationObject = {};
  24126. serializationObject.emitterId = particleSystem.emitter.id;
  24127. serializationObject.capacity = particleSystem.getCapacity();
  24128. if (particleSystem.particleTexture) {
  24129. serializationObject.textureName = particleSystem.particleTexture.name;
  24130. }
  24131. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24132. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24133. serializationObject.minSize = particleSystem.minSize;
  24134. serializationObject.maxSize = particleSystem.maxSize;
  24135. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24136. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24137. serializationObject.emitRate = particleSystem.emitRate;
  24138. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24139. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24140. serializationObject.gravity = particleSystem.gravity.asArray();
  24141. serializationObject.direction1 = particleSystem.direction1.asArray();
  24142. serializationObject.direction2 = particleSystem.direction2.asArray();
  24143. serializationObject.color1 = particleSystem.color1.asArray();
  24144. serializationObject.color2 = particleSystem.color2.asArray();
  24145. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24146. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24147. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24148. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24149. serializationObject.blendMode = particleSystem.blendMode;
  24150. return serializationObject;
  24151. };
  24152. var serializeLensFlareSystem = function (lensFlareSystem) {
  24153. var serializationObject = {};
  24154. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24155. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24156. serializationObject.flares = [];
  24157. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24158. var flare = lensFlareSystem.lensFlares[index];
  24159. serializationObject.flares.push({
  24160. size: flare.size,
  24161. position: flare.position,
  24162. color: flare.color.asArray(),
  24163. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24164. });
  24165. }
  24166. return serializationObject;
  24167. };
  24168. var serializeShadowGenerator = function (light) {
  24169. var serializationObject = {};
  24170. var shadowGenerator = light.getShadowGenerator();
  24171. serializationObject.lightId = light.id;
  24172. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24173. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24174. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24175. serializationObject.renderList = [];
  24176. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24177. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24178. serializationObject.renderList.push(mesh.id);
  24179. }
  24180. return serializationObject;
  24181. };
  24182. var serializedGeometries = [];
  24183. var serializeGeometry = function (geometry, serializationGeometries) {
  24184. if (serializedGeometries[geometry.id]) {
  24185. return;
  24186. }
  24187. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24188. serializationGeometries.boxes.push(serializeBox(geometry));
  24189. }
  24190. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24191. serializationGeometries.spheres.push(serializeSphere(geometry));
  24192. }
  24193. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24194. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24195. }
  24196. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24197. serializationGeometries.toruses.push(serializeTorus(geometry));
  24198. }
  24199. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24200. serializationGeometries.grounds.push(serializeGround(geometry));
  24201. }
  24202. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24203. serializationGeometries.planes.push(serializePlane(geometry));
  24204. }
  24205. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24206. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24207. }
  24208. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24209. throw new Error("Unknown primitive type");
  24210. }
  24211. else {
  24212. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24213. }
  24214. serializedGeometries[geometry.id] = true;
  24215. };
  24216. var serializeGeometryBase = function (geometry) {
  24217. var serializationObject = {};
  24218. serializationObject.id = geometry.id;
  24219. if (BABYLON.Tags.HasTags(geometry)) {
  24220. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24221. }
  24222. return serializationObject;
  24223. };
  24224. var serializeVertexData = function (vertexData) {
  24225. var serializationObject = serializeGeometryBase(vertexData);
  24226. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24227. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24228. }
  24229. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24230. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24231. }
  24232. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24233. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24234. }
  24235. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24236. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24237. }
  24238. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24239. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24240. }
  24241. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24242. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24243. }
  24244. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24245. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24246. }
  24247. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24248. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24249. }
  24250. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24251. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24252. }
  24253. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24254. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24255. serializationObject.matricesIndices._isExpanded = true;
  24256. }
  24257. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24258. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24259. }
  24260. serializationObject.indices = vertexData.getIndices();
  24261. return serializationObject;
  24262. };
  24263. var serializePrimitive = function (primitive) {
  24264. var serializationObject = serializeGeometryBase(primitive);
  24265. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24266. return serializationObject;
  24267. };
  24268. var serializeBox = function (box) {
  24269. var serializationObject = serializePrimitive(box);
  24270. serializationObject.size = box.size;
  24271. return serializationObject;
  24272. };
  24273. var serializeSphere = function (sphere) {
  24274. var serializationObject = serializePrimitive(sphere);
  24275. serializationObject.segments = sphere.segments;
  24276. serializationObject.diameter = sphere.diameter;
  24277. return serializationObject;
  24278. };
  24279. var serializeCylinder = function (cylinder) {
  24280. var serializationObject = serializePrimitive(cylinder);
  24281. serializationObject.height = cylinder.height;
  24282. serializationObject.diameterTop = cylinder.diameterTop;
  24283. serializationObject.diameterBottom = cylinder.diameterBottom;
  24284. serializationObject.tessellation = cylinder.tessellation;
  24285. return serializationObject;
  24286. };
  24287. var serializeTorus = function (torus) {
  24288. var serializationObject = serializePrimitive(torus);
  24289. serializationObject.diameter = torus.diameter;
  24290. serializationObject.thickness = torus.thickness;
  24291. serializationObject.tessellation = torus.tessellation;
  24292. return serializationObject;
  24293. };
  24294. var serializeGround = function (ground) {
  24295. var serializationObject = serializePrimitive(ground);
  24296. serializationObject.width = ground.width;
  24297. serializationObject.height = ground.height;
  24298. serializationObject.subdivisions = ground.subdivisions;
  24299. return serializationObject;
  24300. };
  24301. var serializePlane = function (plane) {
  24302. var serializationObject = serializePrimitive(plane);
  24303. serializationObject.size = plane.size;
  24304. return serializationObject;
  24305. };
  24306. var serializeTorusKnot = function (torusKnot) {
  24307. var serializationObject = serializePrimitive(torusKnot);
  24308. serializationObject.radius = torusKnot.radius;
  24309. serializationObject.tube = torusKnot.tube;
  24310. serializationObject.radialSegments = torusKnot.radialSegments;
  24311. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24312. serializationObject.p = torusKnot.p;
  24313. serializationObject.q = torusKnot.q;
  24314. return serializationObject;
  24315. };
  24316. var serializeMesh = function (mesh, serializationScene) {
  24317. var serializationObject = {};
  24318. serializationObject.name = mesh.name;
  24319. serializationObject.id = mesh.id;
  24320. if (BABYLON.Tags.HasTags(mesh)) {
  24321. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24322. }
  24323. serializationObject.position = mesh.position.asArray();
  24324. if (mesh.rotationQuaternion) {
  24325. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24326. }
  24327. else if (mesh.rotation) {
  24328. serializationObject.rotation = mesh.rotation.asArray();
  24329. }
  24330. serializationObject.scaling = mesh.scaling.asArray();
  24331. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24332. serializationObject.isEnabled = mesh.isEnabled();
  24333. serializationObject.isVisible = mesh.isVisible;
  24334. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24335. serializationObject.pickable = mesh.isPickable;
  24336. serializationObject.receiveShadows = mesh.receiveShadows;
  24337. serializationObject.billboardMode = mesh.billboardMode;
  24338. serializationObject.visibility = mesh.visibility;
  24339. serializationObject.checkCollisions = mesh.checkCollisions;
  24340. // Parent
  24341. if (mesh.parent) {
  24342. serializationObject.parentId = mesh.parent.id;
  24343. }
  24344. // Geometry
  24345. var geometry = mesh._geometry;
  24346. if (geometry) {
  24347. var geometryId = geometry.id;
  24348. serializationObject.geometryId = geometryId;
  24349. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24350. // 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
  24351. serializeGeometry(geometry, serializationScene.geometries);
  24352. }
  24353. // SubMeshes
  24354. serializationObject.subMeshes = [];
  24355. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24356. var subMesh = mesh.subMeshes[subIndex];
  24357. serializationObject.subMeshes.push({
  24358. materialIndex: subMesh.materialIndex,
  24359. verticesStart: subMesh.verticesStart,
  24360. verticesCount: subMesh.verticesCount,
  24361. indexStart: subMesh.indexStart,
  24362. indexCount: subMesh.indexCount
  24363. });
  24364. }
  24365. }
  24366. // Material
  24367. if (mesh.material) {
  24368. serializationObject.materialId = mesh.material.id;
  24369. }
  24370. else {
  24371. mesh.material = null;
  24372. }
  24373. // Skeleton
  24374. if (mesh.skeleton) {
  24375. serializationObject.skeletonId = mesh.skeleton.id;
  24376. }
  24377. // Physics
  24378. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24379. serializationObject.physicsMass = mesh.getPhysicsMass();
  24380. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24381. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24382. switch (mesh.getPhysicsImpostor()) {
  24383. case BABYLON.PhysicsEngine.BoxImpostor:
  24384. serializationObject.physicsImpostor = 1;
  24385. break;
  24386. case BABYLON.PhysicsEngine.SphereImpostor:
  24387. serializationObject.physicsImpostor = 2;
  24388. break;
  24389. }
  24390. }
  24391. // Instances
  24392. serializationObject.instances = [];
  24393. for (var index = 0; index < mesh.instances.length; index++) {
  24394. var instance = mesh.instances[index];
  24395. var serializationInstance = {
  24396. name: instance.name,
  24397. position: instance.position,
  24398. rotation: instance.rotation,
  24399. rotationQuaternion: instance.rotationQuaternion,
  24400. scaling: instance.scaling
  24401. };
  24402. serializationObject.instances.push(serializationInstance);
  24403. // Animations
  24404. appendAnimations(instance, serializationInstance);
  24405. }
  24406. // Animations
  24407. appendAnimations(mesh, serializationObject);
  24408. // Layer mask
  24409. serializationObject.layerMask = mesh.layerMask;
  24410. return serializationObject;
  24411. };
  24412. var finalizeSingleMesh = function (mesh, serializationObject) {
  24413. //only works if the mesh is already loaded
  24414. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24415. //serialize material
  24416. if (mesh.material) {
  24417. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24418. serializationObject.materials = serializationObject.materials || [];
  24419. if (!serializationObject.materials.some(function (mat) {
  24420. return mat.id == mesh.material.id;
  24421. })) {
  24422. serializationObject.materials.push(serializeMaterial(mesh.material));
  24423. }
  24424. }
  24425. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24426. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24427. if (!serializationObject.multiMaterials.some(function (mat) {
  24428. return mat.id == mesh.material.id;
  24429. })) {
  24430. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24431. }
  24432. }
  24433. }
  24434. //serialize geometry
  24435. var geometry = mesh._geometry;
  24436. if (geometry) {
  24437. if (!serializationObject.geometries) {
  24438. serializationObject.geometries = {};
  24439. serializationObject.geometries.boxes = [];
  24440. serializationObject.geometries.spheres = [];
  24441. serializationObject.geometries.cylinders = [];
  24442. serializationObject.geometries.toruses = [];
  24443. serializationObject.geometries.grounds = [];
  24444. serializationObject.geometries.planes = [];
  24445. serializationObject.geometries.torusKnots = [];
  24446. serializationObject.geometries.vertexData = [];
  24447. }
  24448. serializeGeometry(geometry, serializationObject.geometries);
  24449. }
  24450. // Skeletons
  24451. if (mesh.skeleton) {
  24452. serializationObject.skeletons = serializationObject.skeletons || [];
  24453. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24454. }
  24455. //serialize the actual mesh
  24456. serializationObject.meshes = serializationObject.meshes || [];
  24457. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24458. }
  24459. };
  24460. var SceneSerializer = (function () {
  24461. function SceneSerializer() {
  24462. }
  24463. SceneSerializer.Serialize = function (scene) {
  24464. var serializationObject = {};
  24465. // Scene
  24466. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24467. serializationObject.autoClear = scene.autoClear;
  24468. serializationObject.clearColor = scene.clearColor.asArray();
  24469. serializationObject.ambientColor = scene.ambientColor.asArray();
  24470. serializationObject.gravity = scene.gravity.asArray();
  24471. // Fog
  24472. if (scene.fogMode && scene.fogMode !== 0) {
  24473. serializationObject.fogMode = scene.fogMode;
  24474. serializationObject.fogColor = scene.fogColor.asArray();
  24475. serializationObject.fogStart = scene.fogStart;
  24476. serializationObject.fogEnd = scene.fogEnd;
  24477. serializationObject.fogDensity = scene.fogDensity;
  24478. }
  24479. // Lights
  24480. serializationObject.lights = [];
  24481. for (var index = 0; index < scene.lights.length; index++) {
  24482. var light = scene.lights[index];
  24483. serializationObject.lights.push(serializeLight(light));
  24484. }
  24485. // Cameras
  24486. serializationObject.cameras = [];
  24487. for (index = 0; index < scene.cameras.length; index++) {
  24488. var camera = scene.cameras[index];
  24489. serializationObject.cameras.push(serializeCamera(camera));
  24490. }
  24491. if (scene.activeCamera) {
  24492. serializationObject.activeCameraID = scene.activeCamera.id;
  24493. }
  24494. // Materials
  24495. serializationObject.materials = [];
  24496. serializationObject.multiMaterials = [];
  24497. for (index = 0; index < scene.materials.length; index++) {
  24498. var material = scene.materials[index];
  24499. if (material instanceof BABYLON.StandardMaterial) {
  24500. serializationObject.materials.push(serializeMaterial(material));
  24501. }
  24502. else if (material instanceof BABYLON.MultiMaterial) {
  24503. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24504. }
  24505. }
  24506. // Skeletons
  24507. serializationObject.skeletons = [];
  24508. for (index = 0; index < scene.skeletons.length; index++) {
  24509. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24510. }
  24511. // Geometries
  24512. serializationObject.geometries = {};
  24513. serializationObject.geometries.boxes = [];
  24514. serializationObject.geometries.spheres = [];
  24515. serializationObject.geometries.cylinders = [];
  24516. serializationObject.geometries.toruses = [];
  24517. serializationObject.geometries.grounds = [];
  24518. serializationObject.geometries.planes = [];
  24519. serializationObject.geometries.torusKnots = [];
  24520. serializationObject.geometries.vertexData = [];
  24521. serializedGeometries = [];
  24522. var geometries = scene.getGeometries();
  24523. for (index = 0; index < geometries.length; index++) {
  24524. var geometry = geometries[index];
  24525. if (geometry.isReady()) {
  24526. serializeGeometry(geometry, serializationObject.geometries);
  24527. }
  24528. }
  24529. // Meshes
  24530. serializationObject.meshes = [];
  24531. for (index = 0; index < scene.meshes.length; index++) {
  24532. var abstractMesh = scene.meshes[index];
  24533. if (abstractMesh instanceof BABYLON.Mesh) {
  24534. var mesh = abstractMesh;
  24535. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24536. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24537. }
  24538. }
  24539. }
  24540. // Particles Systems
  24541. serializationObject.particleSystems = [];
  24542. for (index = 0; index < scene.particleSystems.length; index++) {
  24543. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24544. }
  24545. // Lens flares
  24546. serializationObject.lensFlareSystems = [];
  24547. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24548. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24549. }
  24550. // Shadows
  24551. serializationObject.shadowGenerators = [];
  24552. for (index = 0; index < scene.lights.length; index++) {
  24553. light = scene.lights[index];
  24554. if (light.getShadowGenerator()) {
  24555. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24556. }
  24557. }
  24558. return serializationObject;
  24559. };
  24560. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24561. if (withParents === void 0) { withParents = false; }
  24562. if (withChildren === void 0) { withChildren = false; }
  24563. var serializationObject = {};
  24564. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24565. if (withParents || withChildren) {
  24566. //deliberate for loop! not for each, appended should be processed as well.
  24567. for (var i = 0; i < toSerialize.length; ++i) {
  24568. if (withChildren) {
  24569. toSerialize[i].getDescendants().forEach(function (node) {
  24570. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24571. toSerialize.push(node);
  24572. }
  24573. });
  24574. }
  24575. //make sure the array doesn't contain the object already
  24576. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24577. toSerialize.push(toSerialize[i].parent);
  24578. }
  24579. }
  24580. }
  24581. toSerialize.forEach(function (mesh) {
  24582. finalizeSingleMesh(mesh, serializationObject);
  24583. });
  24584. return serializationObject;
  24585. };
  24586. return SceneSerializer;
  24587. })();
  24588. BABYLON.SceneSerializer = SceneSerializer;
  24589. })(BABYLON || (BABYLON = {}));
  24590. var BABYLON;
  24591. (function (BABYLON) {
  24592. // Unique ID when we import meshes from Babylon to CSG
  24593. var currentCSGMeshId = 0;
  24594. // # class Vertex
  24595. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24596. // one to provide additional features like texture coordinates and vertex
  24597. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24598. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24599. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24600. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24601. // is not used anywhere else.
  24602. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24603. var Vertex = (function () {
  24604. function Vertex(pos, normal, uv) {
  24605. this.pos = pos;
  24606. this.normal = normal;
  24607. this.uv = uv;
  24608. }
  24609. Vertex.prototype.clone = function () {
  24610. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24611. };
  24612. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24613. // orientation of a polygon is flipped.
  24614. Vertex.prototype.flip = function () {
  24615. this.normal = this.normal.scale(-1);
  24616. };
  24617. // Create a new vertex between this vertex and `other` by linearly
  24618. // interpolating all properties using a parameter of `t`. Subclasses should
  24619. // override this to interpolate additional properties.
  24620. Vertex.prototype.interpolate = function (other, t) {
  24621. 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));
  24622. };
  24623. return Vertex;
  24624. })();
  24625. // # class Plane
  24626. // Represents a plane in 3D space.
  24627. var Plane = (function () {
  24628. function Plane(normal, w) {
  24629. this.normal = normal;
  24630. this.w = w;
  24631. }
  24632. Plane.FromPoints = function (a, b, c) {
  24633. var v0 = c.subtract(a);
  24634. var v1 = b.subtract(a);
  24635. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24636. return null;
  24637. }
  24638. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24639. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24640. };
  24641. Plane.prototype.clone = function () {
  24642. return new Plane(this.normal.clone(), this.w);
  24643. };
  24644. Plane.prototype.flip = function () {
  24645. this.normal.scaleInPlace(-1);
  24646. this.w = -this.w;
  24647. };
  24648. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24649. // fragments in the appropriate lists. Coplanar polygons go into either
  24650. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24651. // respect to this plane. Polygons in front or in back of this plane go into
  24652. // either `front` or `back`.
  24653. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24654. var COPLANAR = 0;
  24655. var FRONT = 1;
  24656. var BACK = 2;
  24657. var SPANNING = 3;
  24658. // Classify each point as well as the entire polygon into one of the above
  24659. // four classes.
  24660. var polygonType = 0;
  24661. var types = [];
  24662. for (var i = 0; i < polygon.vertices.length; i++) {
  24663. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24664. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24665. polygonType |= type;
  24666. types.push(type);
  24667. }
  24668. // Put the polygon in the correct list, splitting it when necessary.
  24669. switch (polygonType) {
  24670. case COPLANAR:
  24671. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24672. break;
  24673. case FRONT:
  24674. front.push(polygon);
  24675. break;
  24676. case BACK:
  24677. back.push(polygon);
  24678. break;
  24679. case SPANNING:
  24680. var f = [], b = [];
  24681. for (i = 0; i < polygon.vertices.length; i++) {
  24682. var j = (i + 1) % polygon.vertices.length;
  24683. var ti = types[i], tj = types[j];
  24684. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24685. if (ti != BACK)
  24686. f.push(vi);
  24687. if (ti != FRONT)
  24688. b.push(ti != BACK ? vi.clone() : vi);
  24689. if ((ti | tj) == SPANNING) {
  24690. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24691. var v = vi.interpolate(vj, t);
  24692. f.push(v);
  24693. b.push(v.clone());
  24694. }
  24695. }
  24696. if (f.length >= 3) {
  24697. var poly = new Polygon(f, polygon.shared);
  24698. if (poly.plane)
  24699. front.push(poly);
  24700. }
  24701. if (b.length >= 3) {
  24702. poly = new Polygon(b, polygon.shared);
  24703. if (poly.plane)
  24704. back.push(poly);
  24705. }
  24706. break;
  24707. }
  24708. };
  24709. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24710. // point is on the plane.
  24711. Plane.EPSILON = 1e-5;
  24712. return Plane;
  24713. })();
  24714. // # class Polygon
  24715. // Represents a convex polygon. The vertices used to initialize a polygon must
  24716. // be coplanar and form a convex loop.
  24717. //
  24718. // Each convex polygon has a `shared` property, which is shared between all
  24719. // polygons that are clones of each other or were split from the same polygon.
  24720. // This can be used to define per-polygon properties (such as surface color).
  24721. var Polygon = (function () {
  24722. function Polygon(vertices, shared) {
  24723. this.vertices = vertices;
  24724. this.shared = shared;
  24725. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24726. }
  24727. Polygon.prototype.clone = function () {
  24728. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24729. return new Polygon(vertices, this.shared);
  24730. };
  24731. Polygon.prototype.flip = function () {
  24732. this.vertices.reverse().map(function (v) { v.flip(); });
  24733. this.plane.flip();
  24734. };
  24735. return Polygon;
  24736. })();
  24737. // # class Node
  24738. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24739. // by picking a polygon to split along. That polygon (and all other coplanar
  24740. // polygons) are added directly to that node and the other polygons are added to
  24741. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24742. // no distinction between internal and leaf nodes.
  24743. var Node = (function () {
  24744. function Node(polygons) {
  24745. this.plane = null;
  24746. this.front = null;
  24747. this.back = null;
  24748. this.polygons = [];
  24749. if (polygons) {
  24750. this.build(polygons);
  24751. }
  24752. }
  24753. Node.prototype.clone = function () {
  24754. var node = new Node();
  24755. node.plane = this.plane && this.plane.clone();
  24756. node.front = this.front && this.front.clone();
  24757. node.back = this.back && this.back.clone();
  24758. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24759. return node;
  24760. };
  24761. // Convert solid space to empty space and empty space to solid space.
  24762. Node.prototype.invert = function () {
  24763. for (var i = 0; i < this.polygons.length; i++) {
  24764. this.polygons[i].flip();
  24765. }
  24766. if (this.plane) {
  24767. this.plane.flip();
  24768. }
  24769. if (this.front) {
  24770. this.front.invert();
  24771. }
  24772. if (this.back) {
  24773. this.back.invert();
  24774. }
  24775. var temp = this.front;
  24776. this.front = this.back;
  24777. this.back = temp;
  24778. };
  24779. // Recursively remove all polygons in `polygons` that are inside this BSP
  24780. // tree.
  24781. Node.prototype.clipPolygons = function (polygons) {
  24782. if (!this.plane)
  24783. return polygons.slice();
  24784. var front = [], back = [];
  24785. for (var i = 0; i < polygons.length; i++) {
  24786. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24787. }
  24788. if (this.front) {
  24789. front = this.front.clipPolygons(front);
  24790. }
  24791. if (this.back) {
  24792. back = this.back.clipPolygons(back);
  24793. }
  24794. else {
  24795. back = [];
  24796. }
  24797. return front.concat(back);
  24798. };
  24799. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24800. // `bsp`.
  24801. Node.prototype.clipTo = function (bsp) {
  24802. this.polygons = bsp.clipPolygons(this.polygons);
  24803. if (this.front)
  24804. this.front.clipTo(bsp);
  24805. if (this.back)
  24806. this.back.clipTo(bsp);
  24807. };
  24808. // Return a list of all polygons in this BSP tree.
  24809. Node.prototype.allPolygons = function () {
  24810. var polygons = this.polygons.slice();
  24811. if (this.front)
  24812. polygons = polygons.concat(this.front.allPolygons());
  24813. if (this.back)
  24814. polygons = polygons.concat(this.back.allPolygons());
  24815. return polygons;
  24816. };
  24817. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24818. // new polygons are filtered down to the bottom of the tree and become new
  24819. // nodes there. Each set of polygons is partitioned using the first polygon
  24820. // (no heuristic is used to pick a good split).
  24821. Node.prototype.build = function (polygons) {
  24822. if (!polygons.length)
  24823. return;
  24824. if (!this.plane)
  24825. this.plane = polygons[0].plane.clone();
  24826. var front = [], back = [];
  24827. for (var i = 0; i < polygons.length; i++) {
  24828. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24829. }
  24830. if (front.length) {
  24831. if (!this.front)
  24832. this.front = new Node();
  24833. this.front.build(front);
  24834. }
  24835. if (back.length) {
  24836. if (!this.back)
  24837. this.back = new Node();
  24838. this.back.build(back);
  24839. }
  24840. };
  24841. return Node;
  24842. })();
  24843. var CSG = (function () {
  24844. function CSG() {
  24845. this.polygons = new Array();
  24846. }
  24847. // Convert BABYLON.Mesh to BABYLON.CSG
  24848. CSG.FromMesh = function (mesh) {
  24849. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24850. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24851. if (mesh instanceof BABYLON.Mesh) {
  24852. mesh.computeWorldMatrix(true);
  24853. matrix = mesh.getWorldMatrix();
  24854. meshPosition = mesh.position.clone();
  24855. meshRotation = mesh.rotation.clone();
  24856. if (mesh.rotationQuaternion) {
  24857. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24858. }
  24859. meshScaling = mesh.scaling.clone();
  24860. }
  24861. else {
  24862. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24863. }
  24864. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24865. var subMeshes = mesh.subMeshes;
  24866. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24867. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24868. vertices = [];
  24869. for (var j = 0; j < 3; j++) {
  24870. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24871. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24872. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24873. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24874. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24875. vertex = new Vertex(position, normal, uv);
  24876. vertices.push(vertex);
  24877. }
  24878. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24879. // To handle the case of degenerated triangle
  24880. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24881. if (polygon.plane)
  24882. polygons.push(polygon);
  24883. }
  24884. }
  24885. var csg = CSG.FromPolygons(polygons);
  24886. csg.matrix = matrix;
  24887. csg.position = meshPosition;
  24888. csg.rotation = meshRotation;
  24889. csg.scaling = meshScaling;
  24890. csg.rotationQuaternion = meshRotationQuaternion;
  24891. currentCSGMeshId++;
  24892. return csg;
  24893. };
  24894. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24895. CSG.FromPolygons = function (polygons) {
  24896. var csg = new CSG();
  24897. csg.polygons = polygons;
  24898. return csg;
  24899. };
  24900. CSG.prototype.clone = function () {
  24901. var csg = new CSG();
  24902. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24903. csg.copyTransformAttributes(this);
  24904. return csg;
  24905. };
  24906. CSG.prototype.toPolygons = function () {
  24907. return this.polygons;
  24908. };
  24909. CSG.prototype.union = function (csg) {
  24910. var a = new Node(this.clone().polygons);
  24911. var b = new Node(csg.clone().polygons);
  24912. a.clipTo(b);
  24913. b.clipTo(a);
  24914. b.invert();
  24915. b.clipTo(a);
  24916. b.invert();
  24917. a.build(b.allPolygons());
  24918. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24919. };
  24920. CSG.prototype.unionInPlace = function (csg) {
  24921. var a = new Node(this.polygons);
  24922. var b = new Node(csg.polygons);
  24923. a.clipTo(b);
  24924. b.clipTo(a);
  24925. b.invert();
  24926. b.clipTo(a);
  24927. b.invert();
  24928. a.build(b.allPolygons());
  24929. this.polygons = a.allPolygons();
  24930. };
  24931. CSG.prototype.subtract = function (csg) {
  24932. var a = new Node(this.clone().polygons);
  24933. var b = new Node(csg.clone().polygons);
  24934. a.invert();
  24935. a.clipTo(b);
  24936. b.clipTo(a);
  24937. b.invert();
  24938. b.clipTo(a);
  24939. b.invert();
  24940. a.build(b.allPolygons());
  24941. a.invert();
  24942. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24943. };
  24944. CSG.prototype.subtractInPlace = function (csg) {
  24945. var a = new Node(this.polygons);
  24946. var b = new Node(csg.polygons);
  24947. a.invert();
  24948. a.clipTo(b);
  24949. b.clipTo(a);
  24950. b.invert();
  24951. b.clipTo(a);
  24952. b.invert();
  24953. a.build(b.allPolygons());
  24954. a.invert();
  24955. this.polygons = a.allPolygons();
  24956. };
  24957. CSG.prototype.intersect = function (csg) {
  24958. var a = new Node(this.clone().polygons);
  24959. var b = new Node(csg.clone().polygons);
  24960. a.invert();
  24961. b.clipTo(a);
  24962. b.invert();
  24963. a.clipTo(b);
  24964. b.clipTo(a);
  24965. a.build(b.allPolygons());
  24966. a.invert();
  24967. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24968. };
  24969. CSG.prototype.intersectInPlace = function (csg) {
  24970. var a = new Node(this.polygons);
  24971. var b = new Node(csg.polygons);
  24972. a.invert();
  24973. b.clipTo(a);
  24974. b.invert();
  24975. a.clipTo(b);
  24976. b.clipTo(a);
  24977. a.build(b.allPolygons());
  24978. a.invert();
  24979. this.polygons = a.allPolygons();
  24980. };
  24981. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24982. // not modified.
  24983. CSG.prototype.inverse = function () {
  24984. var csg = this.clone();
  24985. csg.inverseInPlace();
  24986. return csg;
  24987. };
  24988. CSG.prototype.inverseInPlace = function () {
  24989. this.polygons.map(function (p) { p.flip(); });
  24990. };
  24991. // This is used to keep meshes transformations so they can be restored
  24992. // when we build back a Babylon Mesh
  24993. // NB : All CSG operations are performed in world coordinates
  24994. CSG.prototype.copyTransformAttributes = function (csg) {
  24995. this.matrix = csg.matrix;
  24996. this.position = csg.position;
  24997. this.rotation = csg.rotation;
  24998. this.scaling = csg.scaling;
  24999. this.rotationQuaternion = csg.rotationQuaternion;
  25000. return this;
  25001. };
  25002. // Build Raw mesh from CSG
  25003. // Coordinates here are in world space
  25004. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25005. var matrix = this.matrix.clone();
  25006. matrix.invert();
  25007. 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;
  25008. if (keepSubMeshes) {
  25009. // Sort Polygons, since subMeshes are indices range
  25010. polygons.sort(function (a, b) {
  25011. if (a.shared.meshId === b.shared.meshId) {
  25012. return a.shared.subMeshId - b.shared.subMeshId;
  25013. }
  25014. else {
  25015. return a.shared.meshId - b.shared.meshId;
  25016. }
  25017. });
  25018. }
  25019. for (var i = 0, il = polygons.length; i < il; i++) {
  25020. polygon = polygons[i];
  25021. // Building SubMeshes
  25022. if (!subMesh_dict[polygon.shared.meshId]) {
  25023. subMesh_dict[polygon.shared.meshId] = {};
  25024. }
  25025. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25026. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25027. indexStart: +Infinity,
  25028. indexEnd: -Infinity,
  25029. materialIndex: polygon.shared.materialIndex
  25030. };
  25031. }
  25032. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25033. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25034. polygonIndices[0] = 0;
  25035. polygonIndices[1] = j - 1;
  25036. polygonIndices[2] = j;
  25037. for (var k = 0; k < 3; k++) {
  25038. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25039. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25040. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25041. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25042. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25043. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25044. // Check if 2 points can be merged
  25045. if (!(typeof vertex_idx !== 'undefined' &&
  25046. normals[vertex_idx * 3] === localNormal.x &&
  25047. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25048. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25049. uvs[vertex_idx * 2] === uv.x &&
  25050. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25051. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25052. uvs.push(uv.x, uv.y);
  25053. normals.push(normal.x, normal.y, normal.z);
  25054. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25055. }
  25056. indices.push(vertex_idx);
  25057. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25058. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25059. currentIndex++;
  25060. }
  25061. }
  25062. }
  25063. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25064. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25065. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25066. mesh.setIndices(indices);
  25067. if (keepSubMeshes) {
  25068. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25069. var materialIndexOffset = 0, materialMaxIndex;
  25070. mesh.subMeshes.length = 0;
  25071. for (var m in subMesh_dict) {
  25072. materialMaxIndex = -1;
  25073. for (var sm in subMesh_dict[m]) {
  25074. subMesh_obj = subMesh_dict[m][sm];
  25075. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25076. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25077. }
  25078. materialIndexOffset += ++materialMaxIndex;
  25079. }
  25080. }
  25081. return mesh;
  25082. };
  25083. // Build Mesh from CSG taking material and transforms into account
  25084. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25085. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25086. mesh.material = material;
  25087. mesh.position.copyFrom(this.position);
  25088. mesh.rotation.copyFrom(this.rotation);
  25089. if (this.rotationQuaternion) {
  25090. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25091. }
  25092. mesh.scaling.copyFrom(this.scaling);
  25093. mesh.computeWorldMatrix(true);
  25094. return mesh;
  25095. };
  25096. return CSG;
  25097. })();
  25098. BABYLON.CSG = CSG;
  25099. })(BABYLON || (BABYLON = {}));
  25100. var BABYLON;
  25101. (function (BABYLON) {
  25102. var VRDistortionCorrectionPostProcess = (function (_super) {
  25103. __extends(VRDistortionCorrectionPostProcess, _super);
  25104. //ANY
  25105. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25106. var _this = this;
  25107. _super.call(this, name, "vrDistortionCorrection", [
  25108. 'LensCenter',
  25109. 'Scale',
  25110. 'ScaleIn',
  25111. 'HmdWarpParam'
  25112. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25113. this._isRightEye = isRightEye;
  25114. this._distortionFactors = vrMetrics.distortionK;
  25115. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25116. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25117. this.onSizeChanged = function () {
  25118. _this.aspectRatio = _this.width * .5 / _this.height;
  25119. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25120. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25121. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25122. };
  25123. this.onApply = function (effect) {
  25124. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25125. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25126. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25127. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25128. };
  25129. }
  25130. return VRDistortionCorrectionPostProcess;
  25131. })(BABYLON.PostProcess);
  25132. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25133. })(BABYLON || (BABYLON = {}));
  25134. // Mainly based on these 2 articles :
  25135. // 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
  25136. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25137. var BABYLON;
  25138. (function (BABYLON) {
  25139. (function (JoystickAxis) {
  25140. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25141. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25142. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25143. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25144. var JoystickAxis = BABYLON.JoystickAxis;
  25145. var VirtualJoystick = (function () {
  25146. function VirtualJoystick(leftJoystick) {
  25147. var _this = this;
  25148. if (leftJoystick) {
  25149. this._leftJoystick = true;
  25150. }
  25151. else {
  25152. this._leftJoystick = false;
  25153. }
  25154. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25155. VirtualJoystick._globalJoystickIndex++;
  25156. // By default left & right arrow keys are moving the X
  25157. // and up & down keys are moving the Y
  25158. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25159. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25160. this.reverseLeftRight = false;
  25161. this.reverseUpDown = false;
  25162. // collections of pointers
  25163. this._touches = new BABYLON.SmartCollection();
  25164. this.deltaPosition = BABYLON.Vector3.Zero();
  25165. this._joystickSensibility = 25;
  25166. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25167. this._rotationSpeed = 25;
  25168. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25169. this._rotateOnAxisRelativeToMesh = false;
  25170. this._onResize = function (evt) {
  25171. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25172. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25173. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25174. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25175. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25176. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25177. };
  25178. // injecting a canvas element on top of the canvas 3D game
  25179. if (!VirtualJoystick.vjCanvas) {
  25180. window.addEventListener("resize", this._onResize, false);
  25181. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25182. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25183. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25184. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25185. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25186. VirtualJoystick.vjCanvas.style.width = "100%";
  25187. VirtualJoystick.vjCanvas.style.height = "100%";
  25188. VirtualJoystick.vjCanvas.style.position = "absolute";
  25189. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25190. VirtualJoystick.vjCanvas.style.top = "0px";
  25191. VirtualJoystick.vjCanvas.style.left = "0px";
  25192. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25193. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25194. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25195. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25196. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25197. document.body.appendChild(VirtualJoystick.vjCanvas);
  25198. }
  25199. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25200. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25201. this.pressed = false;
  25202. // default joystick color
  25203. this._joystickColor = "cyan";
  25204. this._joystickPointerID = -1;
  25205. // current joystick position
  25206. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25207. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25208. // origin joystick position
  25209. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25210. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25211. this._onPointerDownHandlerRef = function (evt) {
  25212. _this._onPointerDown(evt);
  25213. };
  25214. this._onPointerMoveHandlerRef = function (evt) {
  25215. _this._onPointerMove(evt);
  25216. };
  25217. this._onPointerOutHandlerRef = function (evt) {
  25218. _this._onPointerUp(evt);
  25219. };
  25220. this._onPointerUpHandlerRef = function (evt) {
  25221. _this._onPointerUp(evt);
  25222. };
  25223. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25224. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25225. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25226. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25227. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25228. evt.preventDefault(); // Disables system menu
  25229. }, false);
  25230. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25231. }
  25232. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25233. this._joystickSensibility = newJoystickSensibility;
  25234. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25235. };
  25236. VirtualJoystick.prototype._onPointerDown = function (e) {
  25237. var positionOnScreenCondition;
  25238. e.preventDefault();
  25239. if (this._leftJoystick === true) {
  25240. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25241. }
  25242. else {
  25243. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25244. }
  25245. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25246. // First contact will be dedicated to the virtual joystick
  25247. this._joystickPointerID = e.pointerId;
  25248. this._joystickPointerStartPos.x = e.clientX;
  25249. this._joystickPointerStartPos.y = e.clientY;
  25250. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25251. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25252. this._deltaJoystickVector.x = 0;
  25253. this._deltaJoystickVector.y = 0;
  25254. this.pressed = true;
  25255. this._touches.add(e.pointerId.toString(), e);
  25256. }
  25257. else {
  25258. // You can only trigger the action buttons with a joystick declared
  25259. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25260. this._action();
  25261. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25262. }
  25263. }
  25264. };
  25265. VirtualJoystick.prototype._onPointerMove = function (e) {
  25266. // If the current pointer is the one associated to the joystick (first touch contact)
  25267. if (this._joystickPointerID == e.pointerId) {
  25268. this._joystickPointerPos.x = e.clientX;
  25269. this._joystickPointerPos.y = e.clientY;
  25270. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25271. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25272. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25273. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25274. switch (this._axisTargetedByLeftAndRight) {
  25275. case JoystickAxis.X:
  25276. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25277. break;
  25278. case JoystickAxis.Y:
  25279. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25280. break;
  25281. case JoystickAxis.Z:
  25282. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25283. break;
  25284. }
  25285. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25286. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25287. switch (this._axisTargetedByUpAndDown) {
  25288. case JoystickAxis.X:
  25289. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25290. break;
  25291. case JoystickAxis.Y:
  25292. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25293. break;
  25294. case JoystickAxis.Z:
  25295. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25296. break;
  25297. }
  25298. }
  25299. else {
  25300. if (this._touches.item(e.pointerId.toString())) {
  25301. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25302. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25303. }
  25304. }
  25305. };
  25306. VirtualJoystick.prototype._onPointerUp = function (e) {
  25307. if (this._joystickPointerID == e.pointerId) {
  25308. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25309. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25310. this._joystickPointerID = -1;
  25311. this.pressed = false;
  25312. }
  25313. else {
  25314. var touch = this._touches.item(e.pointerId.toString());
  25315. if (touch) {
  25316. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25317. }
  25318. }
  25319. this._deltaJoystickVector.x = 0;
  25320. this._deltaJoystickVector.y = 0;
  25321. this._touches.remove(e.pointerId.toString());
  25322. };
  25323. /**
  25324. * Change the color of the virtual joystick
  25325. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25326. */
  25327. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25328. this._joystickColor = newColor;
  25329. };
  25330. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25331. this._action = action;
  25332. };
  25333. // Define which axis you'd like to control for left & right
  25334. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25335. switch (axis) {
  25336. case JoystickAxis.X:
  25337. case JoystickAxis.Y:
  25338. case JoystickAxis.Z:
  25339. this._axisTargetedByLeftAndRight = axis;
  25340. break;
  25341. default:
  25342. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25343. break;
  25344. }
  25345. };
  25346. // Define which axis you'd like to control for up & down
  25347. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25348. switch (axis) {
  25349. case JoystickAxis.X:
  25350. case JoystickAxis.Y:
  25351. case JoystickAxis.Z:
  25352. this._axisTargetedByUpAndDown = axis;
  25353. break;
  25354. default:
  25355. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25356. break;
  25357. }
  25358. };
  25359. VirtualJoystick.prototype._clearCanvas = function () {
  25360. if (this._leftJoystick) {
  25361. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25362. }
  25363. else {
  25364. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25365. }
  25366. };
  25367. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25368. var _this = this;
  25369. if (this.pressed) {
  25370. this._touches.forEach(function (touch) {
  25371. if (touch.pointerId === _this._joystickPointerID) {
  25372. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25373. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25374. VirtualJoystick.vjCanvasContext.beginPath();
  25375. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25376. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25377. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25378. VirtualJoystick.vjCanvasContext.stroke();
  25379. VirtualJoystick.vjCanvasContext.closePath();
  25380. VirtualJoystick.vjCanvasContext.beginPath();
  25381. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25382. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25383. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25384. VirtualJoystick.vjCanvasContext.stroke();
  25385. VirtualJoystick.vjCanvasContext.closePath();
  25386. VirtualJoystick.vjCanvasContext.beginPath();
  25387. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25388. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25389. VirtualJoystick.vjCanvasContext.stroke();
  25390. VirtualJoystick.vjCanvasContext.closePath();
  25391. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25392. }
  25393. else {
  25394. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25395. VirtualJoystick.vjCanvasContext.beginPath();
  25396. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25397. VirtualJoystick.vjCanvasContext.beginPath();
  25398. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25399. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25400. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25401. VirtualJoystick.vjCanvasContext.stroke();
  25402. VirtualJoystick.vjCanvasContext.closePath();
  25403. touch.prevX = touch.x;
  25404. touch.prevY = touch.y;
  25405. }
  25406. ;
  25407. });
  25408. }
  25409. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25410. };
  25411. VirtualJoystick.prototype.releaseCanvas = function () {
  25412. if (VirtualJoystick.vjCanvas) {
  25413. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25414. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25415. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25416. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25417. window.removeEventListener("resize", this._onResize);
  25418. document.body.removeChild(VirtualJoystick.vjCanvas);
  25419. VirtualJoystick.vjCanvas = null;
  25420. }
  25421. };
  25422. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25423. VirtualJoystick._globalJoystickIndex = 0;
  25424. return VirtualJoystick;
  25425. })();
  25426. BABYLON.VirtualJoystick = VirtualJoystick;
  25427. })(BABYLON || (BABYLON = {}));
  25428. var BABYLON;
  25429. (function (BABYLON) {
  25430. // We're mainly based on the logic defined into the FreeCamera code
  25431. var VirtualJoysticksCamera = (function (_super) {
  25432. __extends(VirtualJoysticksCamera, _super);
  25433. function VirtualJoysticksCamera(name, position, scene) {
  25434. _super.call(this, name, position, scene);
  25435. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25436. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25437. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25438. this._leftjoystick.setJoystickSensibility(0.15);
  25439. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25440. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25441. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25442. this._rightjoystick.reverseUpDown = true;
  25443. this._rightjoystick.setJoystickSensibility(0.05);
  25444. this._rightjoystick.setJoystickColor("yellow");
  25445. }
  25446. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25447. return this._leftjoystick;
  25448. };
  25449. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25450. return this._rightjoystick;
  25451. };
  25452. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25453. var speed = this._computeLocalCameraSpeed() * 50;
  25454. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25455. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25456. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25457. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25458. if (!this._leftjoystick.pressed) {
  25459. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25460. }
  25461. if (!this._rightjoystick.pressed) {
  25462. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25463. }
  25464. _super.prototype._checkInputs.call(this);
  25465. };
  25466. VirtualJoysticksCamera.prototype.dispose = function () {
  25467. this._leftjoystick.releaseCanvas();
  25468. _super.prototype.dispose.call(this);
  25469. };
  25470. return VirtualJoysticksCamera;
  25471. })(BABYLON.FreeCamera);
  25472. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25473. })(BABYLON || (BABYLON = {}));
  25474. var BABYLON;
  25475. (function (BABYLON) {
  25476. var ShaderMaterial = (function (_super) {
  25477. __extends(ShaderMaterial, _super);
  25478. function ShaderMaterial(name, scene, shaderPath, options) {
  25479. _super.call(this, name, scene);
  25480. this._textures = new Array();
  25481. this._floats = new Array();
  25482. this._floatsArrays = {};
  25483. this._colors3 = new Array();
  25484. this._colors4 = new Array();
  25485. this._vectors2 = new Array();
  25486. this._vectors3 = new Array();
  25487. this._vectors4 = new Array();
  25488. this._matrices = new Array();
  25489. this._matrices3x3 = new Array();
  25490. this._matrices2x2 = new Array();
  25491. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25492. this._shaderPath = shaderPath;
  25493. options.needAlphaBlending = options.needAlphaBlending || false;
  25494. options.needAlphaTesting = options.needAlphaTesting || false;
  25495. options.attributes = options.attributes || ["position", "normal", "uv"];
  25496. options.uniforms = options.uniforms || ["worldViewProjection"];
  25497. options.samplers = options.samplers || [];
  25498. this._options = options;
  25499. }
  25500. ShaderMaterial.prototype.needAlphaBlending = function () {
  25501. return this._options.needAlphaBlending;
  25502. };
  25503. ShaderMaterial.prototype.needAlphaTesting = function () {
  25504. return this._options.needAlphaTesting;
  25505. };
  25506. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25507. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25508. this._options.uniforms.push(uniformName);
  25509. }
  25510. };
  25511. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25512. if (this._options.samplers.indexOf(name) === -1) {
  25513. this._options.samplers.push(name);
  25514. }
  25515. this._textures[name] = texture;
  25516. return this;
  25517. };
  25518. ShaderMaterial.prototype.setFloat = function (name, value) {
  25519. this._checkUniform(name);
  25520. this._floats[name] = value;
  25521. return this;
  25522. };
  25523. ShaderMaterial.prototype.setFloats = function (name, value) {
  25524. this._checkUniform(name);
  25525. this._floatsArrays[name] = value;
  25526. return this;
  25527. };
  25528. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25529. this._checkUniform(name);
  25530. this._colors3[name] = value;
  25531. return this;
  25532. };
  25533. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25534. this._checkUniform(name);
  25535. this._colors4[name] = value;
  25536. return this;
  25537. };
  25538. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25539. this._checkUniform(name);
  25540. this._vectors2[name] = value;
  25541. return this;
  25542. };
  25543. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25544. this._checkUniform(name);
  25545. this._vectors3[name] = value;
  25546. return this;
  25547. };
  25548. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25549. this._checkUniform(name);
  25550. this._vectors4[name] = value;
  25551. return this;
  25552. };
  25553. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25554. this._checkUniform(name);
  25555. this._matrices[name] = value;
  25556. return this;
  25557. };
  25558. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25559. this._checkUniform(name);
  25560. this._matrices3x3[name] = value;
  25561. return this;
  25562. };
  25563. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25564. this._checkUniform(name);
  25565. this._matrices2x2[name] = value;
  25566. return this;
  25567. };
  25568. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25569. var scene = this.getScene();
  25570. var engine = scene.getEngine();
  25571. if (!this.checkReadyOnEveryCall) {
  25572. if (this._renderId === scene.getRenderId()) {
  25573. return true;
  25574. }
  25575. }
  25576. // Instances
  25577. var defines = [];
  25578. var fallbacks = new BABYLON.EffectFallbacks();
  25579. if (useInstances) {
  25580. defines.push("#define INSTANCES");
  25581. }
  25582. // Bones
  25583. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25584. defines.push("#define BONES");
  25585. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25586. defines.push("#define BONES4");
  25587. fallbacks.addFallback(0, "BONES4");
  25588. }
  25589. // Alpha test
  25590. if (engine.getAlphaTesting()) {
  25591. defines.push("#define ALPHATEST");
  25592. }
  25593. var previousEffect = this._effect;
  25594. var join = defines.join("\n");
  25595. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25596. if (!this._effect.isReady()) {
  25597. return false;
  25598. }
  25599. if (previousEffect !== this._effect) {
  25600. scene.resetCachedMaterial();
  25601. }
  25602. this._renderId = scene.getRenderId();
  25603. return true;
  25604. };
  25605. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25606. var scene = this.getScene();
  25607. if (this._options.uniforms.indexOf("world") !== -1) {
  25608. this._effect.setMatrix("world", world);
  25609. }
  25610. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25611. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25612. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25613. }
  25614. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25615. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25616. }
  25617. };
  25618. ShaderMaterial.prototype.bind = function (world, mesh) {
  25619. // Std values
  25620. this.bindOnlyWorldMatrix(world);
  25621. if (this.getScene().getCachedMaterial() !== this) {
  25622. if (this._options.uniforms.indexOf("view") !== -1) {
  25623. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25624. }
  25625. if (this._options.uniforms.indexOf("projection") !== -1) {
  25626. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25627. }
  25628. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25629. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25630. }
  25631. // Bones
  25632. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25633. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25634. }
  25635. // Texture
  25636. for (var name in this._textures) {
  25637. this._effect.setTexture(name, this._textures[name]);
  25638. }
  25639. // Float
  25640. for (name in this._floats) {
  25641. this._effect.setFloat(name, this._floats[name]);
  25642. }
  25643. // Float s
  25644. for (name in this._floatsArrays) {
  25645. this._effect.setArray(name, this._floatsArrays[name]);
  25646. }
  25647. // Color3
  25648. for (name in this._colors3) {
  25649. this._effect.setColor3(name, this._colors3[name]);
  25650. }
  25651. // Color4
  25652. for (name in this._colors4) {
  25653. var color = this._colors4[name];
  25654. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25655. }
  25656. // Vector2
  25657. for (name in this._vectors2) {
  25658. this._effect.setVector2(name, this._vectors2[name]);
  25659. }
  25660. // Vector3
  25661. for (name in this._vectors3) {
  25662. this._effect.setVector3(name, this._vectors3[name]);
  25663. }
  25664. // Vector4
  25665. for (name in this._vectors4) {
  25666. this._effect.setVector4(name, this._vectors4[name]);
  25667. }
  25668. // Matrix
  25669. for (name in this._matrices) {
  25670. this._effect.setMatrix(name, this._matrices[name]);
  25671. }
  25672. // Matrix 3x3
  25673. for (name in this._matrices3x3) {
  25674. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25675. }
  25676. // Matrix 2x2
  25677. for (name in this._matrices2x2) {
  25678. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25679. }
  25680. }
  25681. _super.prototype.bind.call(this, world, mesh);
  25682. };
  25683. ShaderMaterial.prototype.clone = function (name) {
  25684. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25685. return newShaderMaterial;
  25686. };
  25687. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25688. for (var name in this._textures) {
  25689. this._textures[name].dispose();
  25690. }
  25691. this._textures = [];
  25692. _super.prototype.dispose.call(this, forceDisposeEffect);
  25693. };
  25694. return ShaderMaterial;
  25695. })(BABYLON.Material);
  25696. BABYLON.ShaderMaterial = ShaderMaterial;
  25697. })(BABYLON || (BABYLON = {}));
  25698. var BABYLON;
  25699. (function (BABYLON) {
  25700. var VertexData = (function () {
  25701. function VertexData() {
  25702. }
  25703. VertexData.prototype.set = function (data, kind) {
  25704. switch (kind) {
  25705. case BABYLON.VertexBuffer.PositionKind:
  25706. this.positions = data;
  25707. break;
  25708. case BABYLON.VertexBuffer.NormalKind:
  25709. this.normals = data;
  25710. break;
  25711. case BABYLON.VertexBuffer.UVKind:
  25712. this.uvs = data;
  25713. break;
  25714. case BABYLON.VertexBuffer.UV2Kind:
  25715. this.uvs2 = data;
  25716. break;
  25717. case BABYLON.VertexBuffer.UV3Kind:
  25718. this.uvs3 = data;
  25719. break;
  25720. case BABYLON.VertexBuffer.UV4Kind:
  25721. this.uvs4 = data;
  25722. break;
  25723. case BABYLON.VertexBuffer.UV5Kind:
  25724. this.uvs5 = data;
  25725. break;
  25726. case BABYLON.VertexBuffer.UV6Kind:
  25727. this.uvs6 = data;
  25728. break;
  25729. case BABYLON.VertexBuffer.ColorKind:
  25730. this.colors = data;
  25731. break;
  25732. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25733. this.matricesIndices = data;
  25734. break;
  25735. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25736. this.matricesWeights = data;
  25737. break;
  25738. }
  25739. };
  25740. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25741. this._applyTo(mesh, updatable);
  25742. };
  25743. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25744. this._applyTo(geometry, updatable);
  25745. };
  25746. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25747. this._update(mesh);
  25748. };
  25749. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25750. this._update(geometry);
  25751. };
  25752. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25753. if (this.positions) {
  25754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25755. }
  25756. if (this.normals) {
  25757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25758. }
  25759. if (this.uvs) {
  25760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25761. }
  25762. if (this.uvs2) {
  25763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25764. }
  25765. if (this.uvs3) {
  25766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25767. }
  25768. if (this.uvs4) {
  25769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25770. }
  25771. if (this.uvs5) {
  25772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25773. }
  25774. if (this.uvs6) {
  25775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25776. }
  25777. if (this.colors) {
  25778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25779. }
  25780. if (this.matricesIndices) {
  25781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25782. }
  25783. if (this.matricesWeights) {
  25784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25785. }
  25786. if (this.indices) {
  25787. meshOrGeometry.setIndices(this.indices);
  25788. }
  25789. };
  25790. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25791. if (this.positions) {
  25792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25793. }
  25794. if (this.normals) {
  25795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25796. }
  25797. if (this.uvs) {
  25798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25799. }
  25800. if (this.uvs2) {
  25801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25802. }
  25803. if (this.uvs3) {
  25804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25805. }
  25806. if (this.uvs4) {
  25807. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25808. }
  25809. if (this.uvs5) {
  25810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25811. }
  25812. if (this.uvs6) {
  25813. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25814. }
  25815. if (this.colors) {
  25816. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25817. }
  25818. if (this.matricesIndices) {
  25819. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25820. }
  25821. if (this.matricesWeights) {
  25822. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25823. }
  25824. if (this.indices) {
  25825. meshOrGeometry.setIndices(this.indices);
  25826. }
  25827. };
  25828. VertexData.prototype.transform = function (matrix) {
  25829. var transformed = BABYLON.Vector3.Zero();
  25830. if (this.positions) {
  25831. var position = BABYLON.Vector3.Zero();
  25832. for (var index = 0; index < this.positions.length; index += 3) {
  25833. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25834. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25835. this.positions[index] = transformed.x;
  25836. this.positions[index + 1] = transformed.y;
  25837. this.positions[index + 2] = transformed.z;
  25838. }
  25839. }
  25840. if (this.normals) {
  25841. var normal = BABYLON.Vector3.Zero();
  25842. for (index = 0; index < this.normals.length; index += 3) {
  25843. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25844. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25845. this.normals[index] = transformed.x;
  25846. this.normals[index + 1] = transformed.y;
  25847. this.normals[index + 2] = transformed.z;
  25848. }
  25849. }
  25850. };
  25851. VertexData.prototype.merge = function (other) {
  25852. if (other.indices) {
  25853. if (!this.indices) {
  25854. this.indices = [];
  25855. }
  25856. var offset = this.positions ? this.positions.length / 3 : 0;
  25857. for (var index = 0; index < other.indices.length; index++) {
  25858. this.indices.push(other.indices[index] + offset);
  25859. }
  25860. }
  25861. if (other.positions) {
  25862. if (!this.positions) {
  25863. this.positions = [];
  25864. }
  25865. for (index = 0; index < other.positions.length; index++) {
  25866. this.positions.push(other.positions[index]);
  25867. }
  25868. }
  25869. if (other.normals) {
  25870. if (!this.normals) {
  25871. this.normals = [];
  25872. }
  25873. for (index = 0; index < other.normals.length; index++) {
  25874. this.normals.push(other.normals[index]);
  25875. }
  25876. }
  25877. if (other.uvs) {
  25878. if (!this.uvs) {
  25879. this.uvs = [];
  25880. }
  25881. for (index = 0; index < other.uvs.length; index++) {
  25882. this.uvs.push(other.uvs[index]);
  25883. }
  25884. }
  25885. if (other.uvs2) {
  25886. if (!this.uvs2) {
  25887. this.uvs2 = [];
  25888. }
  25889. for (index = 0; index < other.uvs2.length; index++) {
  25890. this.uvs2.push(other.uvs2[index]);
  25891. }
  25892. }
  25893. if (other.uvs3) {
  25894. if (!this.uvs3) {
  25895. this.uvs3 = [];
  25896. }
  25897. for (index = 0; index < other.uvs3.length; index++) {
  25898. this.uvs3.push(other.uvs3[index]);
  25899. }
  25900. }
  25901. if (other.uvs4) {
  25902. if (!this.uvs4) {
  25903. this.uvs4 = [];
  25904. }
  25905. for (index = 0; index < other.uvs4.length; index++) {
  25906. this.uvs4.push(other.uvs4[index]);
  25907. }
  25908. }
  25909. if (other.uvs5) {
  25910. if (!this.uvs5) {
  25911. this.uvs5 = [];
  25912. }
  25913. for (index = 0; index < other.uvs5.length; index++) {
  25914. this.uvs5.push(other.uvs5[index]);
  25915. }
  25916. }
  25917. if (other.uvs6) {
  25918. if (!this.uvs6) {
  25919. this.uvs6 = [];
  25920. }
  25921. for (index = 0; index < other.uvs6.length; index++) {
  25922. this.uvs6.push(other.uvs6[index]);
  25923. }
  25924. }
  25925. if (other.matricesIndices) {
  25926. if (!this.matricesIndices) {
  25927. this.matricesIndices = [];
  25928. }
  25929. for (index = 0; index < other.matricesIndices.length; index++) {
  25930. this.matricesIndices.push(other.matricesIndices[index]);
  25931. }
  25932. }
  25933. if (other.matricesWeights) {
  25934. if (!this.matricesWeights) {
  25935. this.matricesWeights = [];
  25936. }
  25937. for (index = 0; index < other.matricesWeights.length; index++) {
  25938. this.matricesWeights.push(other.matricesWeights[index]);
  25939. }
  25940. }
  25941. if (other.colors) {
  25942. if (!this.colors) {
  25943. this.colors = [];
  25944. }
  25945. for (index = 0; index < other.colors.length; index++) {
  25946. this.colors.push(other.colors[index]);
  25947. }
  25948. }
  25949. };
  25950. // Statics
  25951. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  25952. return VertexData._ExtractFrom(mesh, copyWhenShared);
  25953. };
  25954. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  25955. return VertexData._ExtractFrom(geometry, copyWhenShared);
  25956. };
  25957. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  25958. var result = new VertexData();
  25959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25960. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  25961. }
  25962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25963. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  25964. }
  25965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25966. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  25967. }
  25968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25969. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  25970. }
  25971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25972. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  25973. }
  25974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25975. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  25976. }
  25977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25978. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  25979. }
  25980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25981. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  25982. }
  25983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25984. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  25985. }
  25986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25987. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  25988. }
  25989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25990. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  25991. }
  25992. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25993. return result;
  25994. };
  25995. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  25996. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25997. closeArray = closeArray || false;
  25998. closePath = closePath || false;
  25999. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26000. offset = offset || defaultOffset;
  26001. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26002. var positions = [];
  26003. var indices = [];
  26004. var normals = [];
  26005. var uvs = [];
  26006. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26007. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26008. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26009. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26010. var minlg; // minimal length among all paths from pathArray
  26011. var lg = []; // array of path lengths : nb of vertex per path
  26012. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26013. var p; // path iterator
  26014. var i; // point iterator
  26015. var j; // point iterator
  26016. // if single path in pathArray
  26017. if (pathArray.length < 2) {
  26018. var ar1 = [];
  26019. var ar2 = [];
  26020. for (i = 0; i < pathArray[0].length - offset; i++) {
  26021. ar1.push(pathArray[0][i]);
  26022. ar2.push(pathArray[0][i + offset]);
  26023. }
  26024. pathArray = [ar1, ar2];
  26025. }
  26026. // positions and horizontal distances (u)
  26027. var idc = 0;
  26028. var closePathCorr = (closePath) ? 1 : 0;
  26029. var path;
  26030. var l;
  26031. minlg = pathArray[0].length;
  26032. for (p = 0; p < pathArray.length; p++) {
  26033. uTotalDistance[p] = 0;
  26034. us[p] = [0];
  26035. path = pathArray[p];
  26036. l = path.length;
  26037. minlg = (minlg < l) ? minlg : l;
  26038. j = 0;
  26039. while (j < l) {
  26040. positions.push(path[j].x, path[j].y, path[j].z);
  26041. if (j > 0) {
  26042. var vectlg = path[j].subtract(path[j - 1]).length();
  26043. var dist = vectlg + uTotalDistance[p];
  26044. us[p].push(dist);
  26045. uTotalDistance[p] = dist;
  26046. }
  26047. j++;
  26048. }
  26049. if (closePath) {
  26050. j--;
  26051. positions.push(path[0].x, path[0].y, path[0].z);
  26052. vectlg = path[j].subtract(path[0]).length();
  26053. dist = vectlg + uTotalDistance[p];
  26054. us[p].push(dist);
  26055. uTotalDistance[p] = dist;
  26056. }
  26057. lg[p] = l + closePathCorr;
  26058. idx[p] = idc;
  26059. idc += (l + closePathCorr);
  26060. }
  26061. // vertical distances (v)
  26062. var path1;
  26063. var path2;
  26064. var vertex1;
  26065. var vertex2;
  26066. for (i = 0; i < minlg + closePathCorr; i++) {
  26067. vTotalDistance[i] = 0;
  26068. vs[i] = [0];
  26069. for (p = 0; p < pathArray.length - 1; p++) {
  26070. path1 = pathArray[p];
  26071. path2 = pathArray[p + 1];
  26072. if (i === minlg) {
  26073. vertex1 = path1[0];
  26074. vertex2 = path2[0];
  26075. }
  26076. else {
  26077. vertex1 = path1[i];
  26078. vertex2 = path2[i];
  26079. }
  26080. vectlg = vertex2.subtract(vertex1).length();
  26081. dist = vectlg + vTotalDistance[i];
  26082. vs[i].push(dist);
  26083. vTotalDistance[i] = dist;
  26084. }
  26085. if (closeArray) {
  26086. path1 = pathArray[p];
  26087. path2 = pathArray[0];
  26088. vectlg = path2[i].subtract(path1[i]).length();
  26089. dist = vectlg + vTotalDistance[i];
  26090. vTotalDistance[i] = dist;
  26091. }
  26092. }
  26093. // uvs
  26094. var u;
  26095. var v;
  26096. for (p = 0; p < pathArray.length; p++) {
  26097. for (i = 0; i < minlg + closePathCorr; i++) {
  26098. u = us[p][i] / uTotalDistance[p];
  26099. v = vs[i][p] / vTotalDistance[i];
  26100. uvs.push(u, v);
  26101. }
  26102. }
  26103. // indices
  26104. p = 0; // path index
  26105. var pi = 0; // positions array index
  26106. var l1 = lg[p] - 1; // path1 length
  26107. var l2 = lg[p + 1] - 1; // path2 length
  26108. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26109. var shft = idx[1] - idx[0]; // shift
  26110. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26111. while (pi <= min && p < path1nb) {
  26112. // 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
  26113. indices.push(pi, pi + shft, pi + 1);
  26114. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26115. pi += 1;
  26116. if (pi === min) {
  26117. p++;
  26118. if (p === lg.length - 1) {
  26119. shft = idx[0] - idx[p];
  26120. l1 = lg[p] - 1;
  26121. l2 = lg[0] - 1;
  26122. }
  26123. else {
  26124. shft = idx[p + 1] - idx[p];
  26125. l1 = lg[p] - 1;
  26126. l2 = lg[p + 1] - 1;
  26127. }
  26128. pi = idx[p];
  26129. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26130. }
  26131. }
  26132. // normals
  26133. VertexData.ComputeNormals(positions, indices, normals);
  26134. if (closePath) {
  26135. var indexFirst = 0;
  26136. var indexLast = 0;
  26137. for (p = 0; p < pathArray.length; p++) {
  26138. indexFirst = idx[p] * 3;
  26139. if (p + 1 < pathArray.length) {
  26140. indexLast = (idx[p + 1] - 1) * 3;
  26141. }
  26142. else {
  26143. indexLast = normals.length - 3;
  26144. }
  26145. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26146. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26147. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26148. normals[indexLast] = normals[indexFirst];
  26149. normals[indexLast + 1] = normals[indexFirst + 1];
  26150. normals[indexLast + 2] = normals[indexFirst + 2];
  26151. }
  26152. }
  26153. // sides
  26154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26155. // Result
  26156. var vertexData = new VertexData();
  26157. vertexData.indices = indices;
  26158. vertexData.positions = positions;
  26159. vertexData.normals = normals;
  26160. vertexData.uvs = uvs;
  26161. if (closePath) {
  26162. vertexData._idx = idx;
  26163. }
  26164. return vertexData;
  26165. };
  26166. VertexData.CreateBox = function (size, sideOrientation) {
  26167. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26168. var normalsSource = [
  26169. new BABYLON.Vector3(0, 0, 1),
  26170. new BABYLON.Vector3(0, 0, -1),
  26171. new BABYLON.Vector3(1, 0, 0),
  26172. new BABYLON.Vector3(-1, 0, 0),
  26173. new BABYLON.Vector3(0, 1, 0),
  26174. new BABYLON.Vector3(0, -1, 0)
  26175. ];
  26176. var indices = [];
  26177. var positions = [];
  26178. var normals = [];
  26179. var uvs = [];
  26180. size = size || 1;
  26181. // Create each face in turn.
  26182. for (var index = 0; index < normalsSource.length; index++) {
  26183. var normal = normalsSource[index];
  26184. // Get two vectors perpendicular to the face normal and to each other.
  26185. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26186. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26187. // Six indices (two triangles) per face.
  26188. var verticesLength = positions.length / 3;
  26189. indices.push(verticesLength);
  26190. indices.push(verticesLength + 1);
  26191. indices.push(verticesLength + 2);
  26192. indices.push(verticesLength);
  26193. indices.push(verticesLength + 2);
  26194. indices.push(verticesLength + 3);
  26195. // Four vertices per face.
  26196. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  26197. positions.push(vertex.x, vertex.y, vertex.z);
  26198. normals.push(normal.x, normal.y, normal.z);
  26199. uvs.push(1.0, 1.0);
  26200. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  26201. positions.push(vertex.x, vertex.y, vertex.z);
  26202. normals.push(normal.x, normal.y, normal.z);
  26203. uvs.push(0.0, 1.0);
  26204. vertex = normal.add(side1).add(side2).scale(size / 2);
  26205. positions.push(vertex.x, vertex.y, vertex.z);
  26206. normals.push(normal.x, normal.y, normal.z);
  26207. uvs.push(0.0, 0.0);
  26208. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  26209. positions.push(vertex.x, vertex.y, vertex.z);
  26210. normals.push(normal.x, normal.y, normal.z);
  26211. uvs.push(1.0, 0.0);
  26212. }
  26213. // sides
  26214. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26215. // Result
  26216. var vertexData = new VertexData();
  26217. vertexData.indices = indices;
  26218. vertexData.positions = positions;
  26219. vertexData.normals = normals;
  26220. vertexData.uvs = uvs;
  26221. return vertexData;
  26222. };
  26223. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  26224. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26225. segments = segments || 32;
  26226. diameter = diameter || 1;
  26227. var radius = diameter / 2;
  26228. var totalZRotationSteps = 2 + segments;
  26229. var totalYRotationSteps = 2 * totalZRotationSteps;
  26230. var indices = [];
  26231. var positions = [];
  26232. var normals = [];
  26233. var uvs = [];
  26234. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26235. var normalizedZ = zRotationStep / totalZRotationSteps;
  26236. var angleZ = (normalizedZ * Math.PI);
  26237. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26238. var normalizedY = yRotationStep / totalYRotationSteps;
  26239. var angleY = normalizedY * Math.PI * 2;
  26240. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26241. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26242. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26243. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26244. var vertex = complete.scale(radius);
  26245. var normal = BABYLON.Vector3.Normalize(vertex);
  26246. positions.push(vertex.x, vertex.y, vertex.z);
  26247. normals.push(normal.x, normal.y, normal.z);
  26248. uvs.push(normalizedZ, normalizedY);
  26249. }
  26250. if (zRotationStep > 0) {
  26251. var verticesCount = positions.length / 3;
  26252. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26253. indices.push((firstIndex));
  26254. indices.push((firstIndex + 1));
  26255. indices.push(firstIndex + totalYRotationSteps + 1);
  26256. indices.push((firstIndex + totalYRotationSteps + 1));
  26257. indices.push((firstIndex + 1));
  26258. indices.push((firstIndex + totalYRotationSteps + 2));
  26259. }
  26260. }
  26261. }
  26262. // Sides
  26263. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26264. // Result
  26265. var vertexData = new VertexData();
  26266. vertexData.indices = indices;
  26267. vertexData.positions = positions;
  26268. vertexData.normals = normals;
  26269. vertexData.uvs = uvs;
  26270. return vertexData;
  26271. };
  26272. // Cylinder and cone (made using ribbons)
  26273. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26274. if (subdivisions === void 0) { subdivisions = 1; }
  26275. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26276. // setup tube creation parameters
  26277. var path = [];
  26278. for (var i = 0; i <= subdivisions; i++) {
  26279. path.push(new BABYLON.Vector3(0, height * (-0.5 + i / subdivisions), 0));
  26280. }
  26281. // this is what defines the radius along the cylinder
  26282. var radiusFunction = function (i, distance) {
  26283. return (diameterBottom + (diameterTop - diameterBottom) * distance / height) / 2;
  26284. };
  26285. // shortcut to 3d path data
  26286. var path3D = new BABYLON.Path3D(path);
  26287. var tangents = path3D.getTangents();
  26288. var normals = path3D.getNormals();
  26289. var distances = path3D.getDistances();
  26290. // let's build the array of paths (rings)
  26291. var pathArray = [];
  26292. var ringVertex;
  26293. var angle;
  26294. var angle_step = Math.PI * 2 / tessellation;
  26295. var distance = 0;
  26296. for (var i = 0; i <= subdivisions; i++) {
  26297. pathArray[i] = [];
  26298. for (var j = 0; j < tessellation; j++) {
  26299. angle = j * angle_step;
  26300. ringVertex = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26301. ringVertex.scaleInPlace(radiusFunction(i, distances[i])).addInPlace(path[i]);
  26302. pathArray[i].push(ringVertex);
  26303. }
  26304. }
  26305. // create ribbon based on computed paths (& close seam)
  26306. var vertexdata = VertexData.CreateRibbon(pathArray, false, true, 0, sideOrientation);
  26307. var createCylinderCap = function (isTop) {
  26308. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26309. if (radius === 0) {
  26310. return;
  26311. }
  26312. var vbase = vertexdata.positions.length / 3;
  26313. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26314. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26315. // Positions, normals & uvs
  26316. var angle;
  26317. var circleVector;
  26318. for (var i = 0; i < tessellation; i++) {
  26319. angle = Math.PI * 2 * i / tessellation;
  26320. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26321. var position = circleVector.scale(radius).add(offset);
  26322. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26323. vertexdata.positions.push(position.x, position.y, position.z);
  26324. vertexdata.normals.push(0, isTop ? 1 : -1, 0);
  26325. vertexdata.uvs.push(textureCoordinate.x, textureCoordinate.y);
  26326. }
  26327. // Indices
  26328. for (i = 0; i < tessellation - 2; i++) {
  26329. if (!isTop) {
  26330. vertexdata.indices.push(vbase);
  26331. vertexdata.indices.push(vbase + (i + 1) % tessellation);
  26332. vertexdata.indices.push(vbase + (i + 2) % tessellation);
  26333. }
  26334. else {
  26335. vertexdata.indices.push(vbase);
  26336. vertexdata.indices.push(vbase + (i + 2) % tessellation);
  26337. vertexdata.indices.push(vbase + (i + 1) % tessellation);
  26338. }
  26339. }
  26340. };
  26341. // add caps to geometry
  26342. createCylinderCap(true);
  26343. createCylinderCap(false);
  26344. return vertexdata;
  26345. };
  26346. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26347. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26348. var indices = [];
  26349. var positions = [];
  26350. var normals = [];
  26351. var uvs = [];
  26352. diameter = diameter || 1;
  26353. thickness = thickness || 0.5;
  26354. tessellation = tessellation || 16;
  26355. var stride = tessellation + 1;
  26356. for (var i = 0; i <= tessellation; i++) {
  26357. var u = i / tessellation;
  26358. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26359. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26360. for (var j = 0; j <= tessellation; j++) {
  26361. var v = 1 - j / tessellation;
  26362. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26363. var dx = Math.cos(innerAngle);
  26364. var dy = Math.sin(innerAngle);
  26365. // Create a vertex.
  26366. var normal = new BABYLON.Vector3(dx, dy, 0);
  26367. var position = normal.scale(thickness / 2);
  26368. var textureCoordinate = new BABYLON.Vector2(u, v);
  26369. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26370. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26371. positions.push(position.x, position.y, position.z);
  26372. normals.push(normal.x, normal.y, normal.z);
  26373. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26374. // And create indices for two triangles.
  26375. var nextI = (i + 1) % stride;
  26376. var nextJ = (j + 1) % stride;
  26377. indices.push(i * stride + j);
  26378. indices.push(i * stride + nextJ);
  26379. indices.push(nextI * stride + j);
  26380. indices.push(i * stride + nextJ);
  26381. indices.push(nextI * stride + nextJ);
  26382. indices.push(nextI * stride + j);
  26383. }
  26384. }
  26385. // Sides
  26386. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26387. // Result
  26388. var vertexData = new VertexData();
  26389. vertexData.indices = indices;
  26390. vertexData.positions = positions;
  26391. vertexData.normals = normals;
  26392. vertexData.uvs = uvs;
  26393. return vertexData;
  26394. };
  26395. VertexData.CreateLines = function (points) {
  26396. var indices = [];
  26397. var positions = [];
  26398. for (var index = 0; index < points.length; index++) {
  26399. positions.push(points[index].x, points[index].y, points[index].z);
  26400. if (index > 0) {
  26401. indices.push(index - 1);
  26402. indices.push(index);
  26403. }
  26404. }
  26405. // Result
  26406. var vertexData = new VertexData();
  26407. vertexData.indices = indices;
  26408. vertexData.positions = positions;
  26409. return vertexData;
  26410. };
  26411. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26412. dashSize = dashSize || 3;
  26413. gapSize = gapSize || 1;
  26414. dashNb = dashNb || 200;
  26415. var positions = new Array();
  26416. var indices = new Array();
  26417. var curvect = BABYLON.Vector3.Zero();
  26418. var lg = 0;
  26419. var nb = 0;
  26420. var shft = 0;
  26421. var dashshft = 0;
  26422. var curshft = 0;
  26423. var idx = 0;
  26424. var i = 0;
  26425. for (i = 0; i < points.length - 1; i++) {
  26426. points[i + 1].subtractToRef(points[i], curvect);
  26427. lg += curvect.length();
  26428. }
  26429. shft = lg / dashNb;
  26430. dashshft = dashSize * shft / (dashSize + gapSize);
  26431. for (i = 0; i < points.length - 1; i++) {
  26432. points[i + 1].subtractToRef(points[i], curvect);
  26433. nb = Math.floor(curvect.length() / shft);
  26434. curvect.normalize();
  26435. for (var j = 0; j < nb; j++) {
  26436. curshft = shft * j;
  26437. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26438. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26439. indices.push(idx, idx + 1);
  26440. idx += 2;
  26441. }
  26442. }
  26443. // Result
  26444. var vertexData = new VertexData();
  26445. vertexData.positions = positions;
  26446. vertexData.indices = indices;
  26447. return vertexData;
  26448. };
  26449. VertexData.CreateGround = function (width, height, subdivisions) {
  26450. var indices = [];
  26451. var positions = [];
  26452. var normals = [];
  26453. var uvs = [];
  26454. var row, col;
  26455. width = width || 1;
  26456. height = height || 1;
  26457. subdivisions = subdivisions || 1;
  26458. for (row = 0; row <= subdivisions; row++) {
  26459. for (col = 0; col <= subdivisions; col++) {
  26460. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26461. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26462. positions.push(position.x, position.y, position.z);
  26463. normals.push(normal.x, normal.y, normal.z);
  26464. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26465. }
  26466. }
  26467. for (row = 0; row < subdivisions; row++) {
  26468. for (col = 0; col < subdivisions; col++) {
  26469. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26470. indices.push(col + 1 + row * (subdivisions + 1));
  26471. indices.push(col + row * (subdivisions + 1));
  26472. indices.push(col + (row + 1) * (subdivisions + 1));
  26473. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26474. indices.push(col + row * (subdivisions + 1));
  26475. }
  26476. }
  26477. // Result
  26478. var vertexData = new VertexData();
  26479. vertexData.indices = indices;
  26480. vertexData.positions = positions;
  26481. vertexData.normals = normals;
  26482. vertexData.uvs = uvs;
  26483. return vertexData;
  26484. };
  26485. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26486. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26487. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26488. var indices = [];
  26489. var positions = [];
  26490. var normals = [];
  26491. var uvs = [];
  26492. var row, col, tileRow, tileCol;
  26493. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26494. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26495. precision.w = (precision.w < 1) ? 1 : precision.w;
  26496. precision.h = (precision.h < 1) ? 1 : precision.h;
  26497. var tileSize = {
  26498. 'w': (xmax - xmin) / subdivisions.w,
  26499. 'h': (zmax - zmin) / subdivisions.h
  26500. };
  26501. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26502. // Indices
  26503. var base = positions.length / 3;
  26504. var rowLength = precision.w + 1;
  26505. for (row = 0; row < precision.h; row++) {
  26506. for (col = 0; col < precision.w; col++) {
  26507. var square = [
  26508. base + col + row * rowLength,
  26509. base + (col + 1) + row * rowLength,
  26510. base + (col + 1) + (row + 1) * rowLength,
  26511. base + col + (row + 1) * rowLength
  26512. ];
  26513. indices.push(square[1]);
  26514. indices.push(square[2]);
  26515. indices.push(square[3]);
  26516. indices.push(square[0]);
  26517. indices.push(square[1]);
  26518. indices.push(square[3]);
  26519. }
  26520. }
  26521. // Position, normals and uvs
  26522. var position = BABYLON.Vector3.Zero();
  26523. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26524. for (row = 0; row <= precision.h; row++) {
  26525. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26526. for (col = 0; col <= precision.w; col++) {
  26527. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26528. position.y = 0;
  26529. positions.push(position.x, position.y, position.z);
  26530. normals.push(normal.x, normal.y, normal.z);
  26531. uvs.push(col / precision.w, row / precision.h);
  26532. }
  26533. }
  26534. }
  26535. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26536. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26537. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26538. }
  26539. }
  26540. // Result
  26541. var vertexData = new VertexData();
  26542. vertexData.indices = indices;
  26543. vertexData.positions = positions;
  26544. vertexData.normals = normals;
  26545. vertexData.uvs = uvs;
  26546. return vertexData;
  26547. };
  26548. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26549. var indices = [];
  26550. var positions = [];
  26551. var normals = [];
  26552. var uvs = [];
  26553. var row, col;
  26554. // Vertices
  26555. for (row = 0; row <= subdivisions; row++) {
  26556. for (col = 0; col <= subdivisions; col++) {
  26557. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26558. // Compute height
  26559. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26560. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26561. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26562. var r = buffer[pos] / 255.0;
  26563. var g = buffer[pos + 1] / 255.0;
  26564. var b = buffer[pos + 2] / 255.0;
  26565. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26566. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26567. // Add vertex
  26568. positions.push(position.x, position.y, position.z);
  26569. normals.push(0, 0, 0);
  26570. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26571. }
  26572. }
  26573. // Indices
  26574. for (row = 0; row < subdivisions; row++) {
  26575. for (col = 0; col < subdivisions; col++) {
  26576. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26577. indices.push(col + 1 + row * (subdivisions + 1));
  26578. indices.push(col + row * (subdivisions + 1));
  26579. indices.push(col + (row + 1) * (subdivisions + 1));
  26580. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26581. indices.push(col + row * (subdivisions + 1));
  26582. }
  26583. }
  26584. // Normals
  26585. VertexData.ComputeNormals(positions, indices, normals);
  26586. // Result
  26587. var vertexData = new VertexData();
  26588. vertexData.indices = indices;
  26589. vertexData.positions = positions;
  26590. vertexData.normals = normals;
  26591. vertexData.uvs = uvs;
  26592. return vertexData;
  26593. };
  26594. VertexData.CreatePlane = function (size, sideOrientation) {
  26595. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26596. var indices = [];
  26597. var positions = [];
  26598. var normals = [];
  26599. var uvs = [];
  26600. size = size || 1;
  26601. // Vertices
  26602. var halfSize = size / 2.0;
  26603. positions.push(-halfSize, -halfSize, 0);
  26604. normals.push(0, 0, -1.0);
  26605. uvs.push(0.0, 0.0);
  26606. positions.push(halfSize, -halfSize, 0);
  26607. normals.push(0, 0, -1.0);
  26608. uvs.push(1.0, 0.0);
  26609. positions.push(halfSize, halfSize, 0);
  26610. normals.push(0, 0, -1.0);
  26611. uvs.push(1.0, 1.0);
  26612. positions.push(-halfSize, halfSize, 0);
  26613. normals.push(0, 0, -1.0);
  26614. uvs.push(0.0, 1.0);
  26615. // Indices
  26616. indices.push(0);
  26617. indices.push(1);
  26618. indices.push(2);
  26619. indices.push(0);
  26620. indices.push(2);
  26621. indices.push(3);
  26622. // Sides
  26623. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26624. // Result
  26625. var vertexData = new VertexData();
  26626. vertexData.indices = indices;
  26627. vertexData.positions = positions;
  26628. vertexData.normals = normals;
  26629. vertexData.uvs = uvs;
  26630. return vertexData;
  26631. };
  26632. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26633. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26634. var positions = [];
  26635. var indices = [];
  26636. var normals = [];
  26637. var uvs = [];
  26638. // positions and uvs
  26639. positions.push(0, 0, 0); // disc center first
  26640. uvs.push(0.5, 0.5);
  26641. var step = Math.PI * 2 / tessellation;
  26642. for (var a = 0; a < Math.PI * 2; a += step) {
  26643. var x = Math.cos(a);
  26644. var y = Math.sin(a);
  26645. var u = (x + 1) / 2;
  26646. var v = (1 - y) / 2;
  26647. positions.push(radius * x, radius * y, 0);
  26648. uvs.push(u, v);
  26649. }
  26650. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26651. uvs.push(uvs[2], uvs[3]);
  26652. //indices
  26653. var vertexNb = positions.length / 3;
  26654. for (var i = 1; i < vertexNb - 1; i++) {
  26655. indices.push(i + 1, 0, i);
  26656. }
  26657. // result
  26658. VertexData.ComputeNormals(positions, indices, normals);
  26659. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26660. var vertexData = new VertexData();
  26661. vertexData.indices = indices;
  26662. vertexData.positions = positions;
  26663. vertexData.normals = normals;
  26664. vertexData.uvs = uvs;
  26665. return vertexData;
  26666. };
  26667. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26668. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26669. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26670. var indices = [];
  26671. var positions = [];
  26672. var normals = [];
  26673. var uvs = [];
  26674. radius = radius || 2;
  26675. tube = tube || 0.5;
  26676. radialSegments = radialSegments || 32;
  26677. tubularSegments = tubularSegments || 32;
  26678. p = p || 2;
  26679. q = q || 3;
  26680. // Helper
  26681. var getPos = function (angle) {
  26682. var cu = Math.cos(angle);
  26683. var su = Math.sin(angle);
  26684. var quOverP = q / p * angle;
  26685. var cs = Math.cos(quOverP);
  26686. var tx = radius * (2 + cs) * 0.5 * cu;
  26687. var ty = radius * (2 + cs) * su * 0.5;
  26688. var tz = radius * Math.sin(quOverP) * 0.5;
  26689. return new BABYLON.Vector3(tx, ty, tz);
  26690. };
  26691. // Vertices
  26692. for (var i = 0; i <= radialSegments; i++) {
  26693. var modI = i % radialSegments;
  26694. var u = modI / radialSegments * 2 * p * Math.PI;
  26695. var p1 = getPos(u);
  26696. var p2 = getPos(u + 0.01);
  26697. var tang = p2.subtract(p1);
  26698. var n = p2.add(p1);
  26699. var bitan = BABYLON.Vector3.Cross(tang, n);
  26700. n = BABYLON.Vector3.Cross(bitan, tang);
  26701. bitan.normalize();
  26702. n.normalize();
  26703. for (var j = 0; j < tubularSegments; j++) {
  26704. var modJ = j % tubularSegments;
  26705. var v = modJ / tubularSegments * 2 * Math.PI;
  26706. var cx = -tube * Math.cos(v);
  26707. var cy = tube * Math.sin(v);
  26708. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26709. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26710. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26711. uvs.push(i / radialSegments);
  26712. uvs.push(j / tubularSegments);
  26713. }
  26714. }
  26715. for (i = 0; i < radialSegments; i++) {
  26716. for (j = 0; j < tubularSegments; j++) {
  26717. var jNext = (j + 1) % tubularSegments;
  26718. var a = i * tubularSegments + j;
  26719. var b = (i + 1) * tubularSegments + j;
  26720. var c = (i + 1) * tubularSegments + jNext;
  26721. var d = i * tubularSegments + jNext;
  26722. indices.push(d);
  26723. indices.push(b);
  26724. indices.push(a);
  26725. indices.push(d);
  26726. indices.push(c);
  26727. indices.push(b);
  26728. }
  26729. }
  26730. // Normals
  26731. VertexData.ComputeNormals(positions, indices, normals);
  26732. // Sides
  26733. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26734. // Result
  26735. var vertexData = new VertexData();
  26736. vertexData.indices = indices;
  26737. vertexData.positions = positions;
  26738. vertexData.normals = normals;
  26739. vertexData.uvs = uvs;
  26740. return vertexData;
  26741. };
  26742. // Tools
  26743. /**
  26744. * @param {any} - positions (number[] or Float32Array)
  26745. * @param {any} - indices (number[] or Uint16Array)
  26746. * @param {any} - normals (number[] or Float32Array)
  26747. */
  26748. VertexData.ComputeNormals = function (positions, indices, normals) {
  26749. var index = 0;
  26750. // temp Vector3
  26751. var p1 = BABYLON.Vector3.Zero();
  26752. var p2 = BABYLON.Vector3.Zero();
  26753. var p3 = BABYLON.Vector3.Zero();
  26754. var p1p2 = BABYLON.Vector3.Zero();
  26755. var p3p2 = BABYLON.Vector3.Zero();
  26756. var faceNormal = BABYLON.Vector3.Zero();
  26757. var vertexNormali1 = BABYLON.Vector3.Zero();
  26758. var vertexNormali2 = BABYLON.Vector3.Zero();
  26759. var vertexNormali3 = BABYLON.Vector3.Zero();
  26760. // indice triplet = 1 face
  26761. var nbFaces = indices.length / 3;
  26762. for (index = 0; index < nbFaces; index++) {
  26763. var i1 = indices[index * 3];
  26764. var i2 = indices[index * 3 + 1];
  26765. var i3 = indices[index * 3 + 2];
  26766. // setting the temp V3
  26767. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  26768. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  26769. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  26770. p1.subtractToRef(p2, p1p2);
  26771. p3.subtractToRef(p2, p3p2);
  26772. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  26773. faceNormal.normalize();
  26774. // All intermediate results are stored in the normals array :
  26775. // get the normals at i1, i2 and i3 indexes
  26776. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  26777. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  26778. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  26779. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  26780. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  26781. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  26782. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  26783. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  26784. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  26785. // make intermediate vectors3 from normals values
  26786. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  26787. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  26788. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  26789. // add the current face normals to these intermediate vectors3
  26790. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  26791. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  26792. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  26793. // store back intermediate vectors3 into the normals array
  26794. normals[i1 * 3] = vertexNormali1.x;
  26795. normals[i1 * 3 + 1] = vertexNormali1.y;
  26796. normals[i1 * 3 + 2] = vertexNormali1.z;
  26797. normals[i2 * 3] = vertexNormali2.x;
  26798. normals[i2 * 3 + 1] = vertexNormali2.y;
  26799. normals[i2 * 3 + 2] = vertexNormali2.z;
  26800. normals[i3 * 3] = vertexNormali3.x;
  26801. normals[i3 * 3 + 1] = vertexNormali3.y;
  26802. normals[i3 * 3 + 2] = vertexNormali3.z;
  26803. }
  26804. // last normalization
  26805. for (index = 0; index < normals.length / 3; index++) {
  26806. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  26807. vertexNormali1.normalize();
  26808. normals[index * 3] = vertexNormali1.x;
  26809. normals[index * 3 + 1] = vertexNormali1.y;
  26810. normals[index * 3 + 2] = vertexNormali1.z;
  26811. }
  26812. };
  26813. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26814. var li = indices.length;
  26815. var ln = normals.length;
  26816. var i;
  26817. var n;
  26818. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26819. switch (sideOrientation) {
  26820. case BABYLON.Mesh.FRONTSIDE:
  26821. // nothing changed
  26822. break;
  26823. case BABYLON.Mesh.BACKSIDE:
  26824. var tmp;
  26825. // indices
  26826. for (i = 0; i < li; i += 3) {
  26827. tmp = indices[i];
  26828. indices[i] = indices[i + 2];
  26829. indices[i + 2] = tmp;
  26830. }
  26831. // normals
  26832. for (n = 0; n < ln; n++) {
  26833. normals[n] = -normals[n];
  26834. }
  26835. break;
  26836. case BABYLON.Mesh.DOUBLESIDE:
  26837. // positions
  26838. var lp = positions.length;
  26839. var l = lp / 3;
  26840. for (var p = 0; p < lp; p++) {
  26841. positions[lp + p] = positions[p];
  26842. }
  26843. // indices
  26844. for (i = 0; i < li; i += 3) {
  26845. indices[i + li] = indices[i + 2] + l;
  26846. indices[i + 1 + li] = indices[i + 1] + l;
  26847. indices[i + 2 + li] = indices[i] + l;
  26848. }
  26849. // normals
  26850. for (n = 0; n < ln; n++) {
  26851. normals[ln + n] = -normals[n];
  26852. }
  26853. // uvs
  26854. var lu = uvs.length;
  26855. for (var u = 0; u < lu; u++) {
  26856. uvs[u + lu] = uvs[u];
  26857. }
  26858. break;
  26859. }
  26860. };
  26861. return VertexData;
  26862. })();
  26863. BABYLON.VertexData = VertexData;
  26864. })(BABYLON || (BABYLON = {}));
  26865. var BABYLON;
  26866. (function (BABYLON) {
  26867. var AnaglyphPostProcess = (function (_super) {
  26868. __extends(AnaglyphPostProcess, _super);
  26869. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26870. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  26871. }
  26872. return AnaglyphPostProcess;
  26873. })(BABYLON.PostProcess);
  26874. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  26875. })(BABYLON || (BABYLON = {}));
  26876. var BABYLON;
  26877. (function (BABYLON) {
  26878. var Tags = (function () {
  26879. function Tags() {
  26880. }
  26881. Tags.EnableFor = function (obj) {
  26882. obj._tags = obj._tags || {};
  26883. obj.hasTags = function () {
  26884. return Tags.HasTags(obj);
  26885. };
  26886. obj.addTags = function (tagsString) {
  26887. return Tags.AddTagsTo(obj, tagsString);
  26888. };
  26889. obj.removeTags = function (tagsString) {
  26890. return Tags.RemoveTagsFrom(obj, tagsString);
  26891. };
  26892. obj.matchesTagsQuery = function (tagsQuery) {
  26893. return Tags.MatchesQuery(obj, tagsQuery);
  26894. };
  26895. };
  26896. Tags.DisableFor = function (obj) {
  26897. delete obj._tags;
  26898. delete obj.hasTags;
  26899. delete obj.addTags;
  26900. delete obj.removeTags;
  26901. delete obj.matchesTagsQuery;
  26902. };
  26903. Tags.HasTags = function (obj) {
  26904. if (!obj._tags) {
  26905. return false;
  26906. }
  26907. return !BABYLON.Tools.IsEmpty(obj._tags);
  26908. };
  26909. Tags.GetTags = function (obj) {
  26910. if (!obj._tags) {
  26911. return null;
  26912. }
  26913. return obj._tags;
  26914. };
  26915. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26916. // a tag cannot start with '||', '&&', and '!'
  26917. // it cannot contain whitespaces
  26918. Tags.AddTagsTo = function (obj, tagsString) {
  26919. if (!tagsString) {
  26920. return;
  26921. }
  26922. var tags = tagsString.split(" ");
  26923. for (var t in tags) {
  26924. Tags._AddTagTo(obj, tags[t]);
  26925. }
  26926. };
  26927. Tags._AddTagTo = function (obj, tag) {
  26928. tag = tag.trim();
  26929. if (tag === "" || tag === "true" || tag === "false") {
  26930. return;
  26931. }
  26932. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26933. return;
  26934. }
  26935. Tags.EnableFor(obj);
  26936. obj._tags[tag] = true;
  26937. };
  26938. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26939. if (!Tags.HasTags(obj)) {
  26940. return;
  26941. }
  26942. var tags = tagsString.split(" ");
  26943. for (var t in tags) {
  26944. Tags._RemoveTagFrom(obj, tags[t]);
  26945. }
  26946. };
  26947. Tags._RemoveTagFrom = function (obj, tag) {
  26948. delete obj._tags[tag];
  26949. };
  26950. Tags.MatchesQuery = function (obj, tagsQuery) {
  26951. if (tagsQuery === undefined) {
  26952. return true;
  26953. }
  26954. if (tagsQuery === "") {
  26955. return Tags.HasTags(obj);
  26956. }
  26957. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26958. };
  26959. return Tags;
  26960. })();
  26961. BABYLON.Tags = Tags;
  26962. })(BABYLON || (BABYLON = {}));
  26963. var BABYLON;
  26964. (function (BABYLON) {
  26965. var Internals;
  26966. (function (Internals) {
  26967. var AndOrNotEvaluator = (function () {
  26968. function AndOrNotEvaluator() {
  26969. }
  26970. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26971. if (!query.match(/\([^\(\)]*\)/g)) {
  26972. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26973. }
  26974. else {
  26975. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26976. // remove parenthesis
  26977. r = r.slice(1, r.length - 1);
  26978. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26979. });
  26980. }
  26981. if (query === "true") {
  26982. return true;
  26983. }
  26984. if (query === "false") {
  26985. return false;
  26986. }
  26987. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26988. };
  26989. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26990. evaluateCallback = evaluateCallback || (function (r) {
  26991. return r === "true" ? true : false;
  26992. });
  26993. var result;
  26994. var or = parenthesisContent.split("||");
  26995. for (var i in or) {
  26996. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26997. var and = ori.split("&&");
  26998. if (and.length > 1) {
  26999. for (var j = 0; j < and.length; ++j) {
  27000. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27001. if (andj !== "true" && andj !== "false") {
  27002. if (andj[0] === "!") {
  27003. result = !evaluateCallback(andj.substring(1));
  27004. }
  27005. else {
  27006. result = evaluateCallback(andj);
  27007. }
  27008. }
  27009. else {
  27010. result = andj === "true" ? true : false;
  27011. }
  27012. if (!result) {
  27013. ori = "false";
  27014. break;
  27015. }
  27016. }
  27017. }
  27018. if (result || ori === "true") {
  27019. result = true;
  27020. break;
  27021. }
  27022. // result equals false (or undefined)
  27023. if (ori !== "true" && ori !== "false") {
  27024. if (ori[0] === "!") {
  27025. result = !evaluateCallback(ori.substring(1));
  27026. }
  27027. else {
  27028. result = evaluateCallback(ori);
  27029. }
  27030. }
  27031. else {
  27032. result = ori === "true" ? true : false;
  27033. }
  27034. }
  27035. // the whole parenthesis scope is replaced by 'true' or 'false'
  27036. return result ? "true" : "false";
  27037. };
  27038. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27039. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27040. // remove whitespaces
  27041. r = r.replace(/[\s]/g, function () { return ""; });
  27042. return r.length % 2 ? "!" : "";
  27043. });
  27044. booleanString = booleanString.trim();
  27045. if (booleanString === "!true") {
  27046. booleanString = "false";
  27047. }
  27048. else if (booleanString === "!false") {
  27049. booleanString = "true";
  27050. }
  27051. return booleanString;
  27052. };
  27053. return AndOrNotEvaluator;
  27054. })();
  27055. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27056. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27057. })(BABYLON || (BABYLON = {}));
  27058. var BABYLON;
  27059. (function (BABYLON) {
  27060. var PostProcessRenderPass = (function () {
  27061. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27062. this._enabled = true;
  27063. this._refCount = 0;
  27064. this._name = name;
  27065. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27066. this.setRenderList(renderList);
  27067. this._renderTexture.onBeforeRender = beforeRender;
  27068. this._renderTexture.onAfterRender = afterRender;
  27069. this._scene = scene;
  27070. this._renderList = renderList;
  27071. }
  27072. // private
  27073. PostProcessRenderPass.prototype._incRefCount = function () {
  27074. if (this._refCount === 0) {
  27075. this._scene.customRenderTargets.push(this._renderTexture);
  27076. }
  27077. return ++this._refCount;
  27078. };
  27079. PostProcessRenderPass.prototype._decRefCount = function () {
  27080. this._refCount--;
  27081. if (this._refCount <= 0) {
  27082. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27083. }
  27084. return this._refCount;
  27085. };
  27086. PostProcessRenderPass.prototype._update = function () {
  27087. this.setRenderList(this._renderList);
  27088. };
  27089. // public
  27090. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27091. this._renderTexture.renderList = renderList;
  27092. };
  27093. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27094. return this._renderTexture;
  27095. };
  27096. return PostProcessRenderPass;
  27097. })();
  27098. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27099. })(BABYLON || (BABYLON = {}));
  27100. var BABYLON;
  27101. (function (BABYLON) {
  27102. var PostProcessRenderEffect = (function () {
  27103. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27104. this._engine = engine;
  27105. this._name = name;
  27106. this._singleInstance = singleInstance || true;
  27107. this._getPostProcess = getPostProcess;
  27108. this._cameras = [];
  27109. this._indicesForCamera = [];
  27110. this._postProcesses = {};
  27111. this._renderPasses = {};
  27112. this._renderEffectAsPasses = {};
  27113. }
  27114. PostProcessRenderEffect.prototype._update = function () {
  27115. for (var renderPassName in this._renderPasses) {
  27116. this._renderPasses[renderPassName]._update();
  27117. }
  27118. };
  27119. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27120. this._renderPasses[renderPass._name] = renderPass;
  27121. this._linkParameters();
  27122. };
  27123. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27124. delete this._renderPasses[renderPass._name];
  27125. this._linkParameters();
  27126. };
  27127. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27128. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27129. this._linkParameters();
  27130. };
  27131. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27132. for (var renderPassName in this._renderPasses) {
  27133. if (renderPassName === passName) {
  27134. return this._renderPasses[passName];
  27135. }
  27136. }
  27137. };
  27138. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27139. this._renderPasses = {};
  27140. this._linkParameters();
  27141. };
  27142. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27143. var cameraKey;
  27144. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27145. for (var i = 0; i < _cam.length; i++) {
  27146. var camera = _cam[i];
  27147. var cameraName = camera.name;
  27148. if (this._singleInstance) {
  27149. cameraKey = 0;
  27150. }
  27151. else {
  27152. cameraKey = cameraName;
  27153. }
  27154. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27155. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27156. if (!this._indicesForCamera[cameraName]) {
  27157. this._indicesForCamera[cameraName] = [];
  27158. }
  27159. this._indicesForCamera[cameraName].push(index);
  27160. if (this._cameras.indexOf(camera) === -1) {
  27161. this._cameras[cameraName] = camera;
  27162. }
  27163. for (var passName in this._renderPasses) {
  27164. this._renderPasses[passName]._incRefCount();
  27165. }
  27166. }
  27167. this._linkParameters();
  27168. };
  27169. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27170. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27171. for (var i = 0; i < _cam.length; i++) {
  27172. var camera = _cam[i];
  27173. var cameraName = camera.name;
  27174. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27175. var index = this._cameras.indexOf(cameraName);
  27176. this._indicesForCamera.splice(index, 1);
  27177. this._cameras.splice(index, 1);
  27178. for (var passName in this._renderPasses) {
  27179. this._renderPasses[passName]._decRefCount();
  27180. }
  27181. }
  27182. };
  27183. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27184. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27185. for (var i = 0; i < _cam.length; i++) {
  27186. var camera = _cam[i];
  27187. var cameraName = camera.name;
  27188. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27189. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27190. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27191. }
  27192. }
  27193. for (var passName in this._renderPasses) {
  27194. this._renderPasses[passName]._incRefCount();
  27195. }
  27196. }
  27197. };
  27198. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27199. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27200. for (var i = 0; i < _cam.length; i++) {
  27201. var camera = _cam[i];
  27202. var cameraName = camera.Name;
  27203. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27204. for (var passName in this._renderPasses) {
  27205. this._renderPasses[passName]._decRefCount();
  27206. }
  27207. }
  27208. };
  27209. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27210. if (this._singleInstance) {
  27211. return this._postProcesses[0];
  27212. }
  27213. else {
  27214. return this._postProcesses[camera.name];
  27215. }
  27216. };
  27217. PostProcessRenderEffect.prototype._linkParameters = function () {
  27218. var _this = this;
  27219. for (var index in this._postProcesses) {
  27220. if (this.applyParameters) {
  27221. this.applyParameters(this._postProcesses[index]);
  27222. }
  27223. this._postProcesses[index].onBeforeRender = function (effect) {
  27224. _this._linkTextures(effect);
  27225. };
  27226. }
  27227. };
  27228. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27229. for (var renderPassName in this._renderPasses) {
  27230. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27231. }
  27232. for (var renderEffectName in this._renderEffectAsPasses) {
  27233. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27234. }
  27235. };
  27236. return PostProcessRenderEffect;
  27237. })();
  27238. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27239. })(BABYLON || (BABYLON = {}));
  27240. var BABYLON;
  27241. (function (BABYLON) {
  27242. var PostProcessRenderPipeline = (function () {
  27243. function PostProcessRenderPipeline(engine, name) {
  27244. this._engine = engine;
  27245. this._name = name;
  27246. this._renderEffects = {};
  27247. this._renderEffectsForIsolatedPass = {};
  27248. this._cameras = [];
  27249. }
  27250. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27251. this._renderEffects[renderEffect._name] = renderEffect;
  27252. };
  27253. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27254. var renderEffects = this._renderEffects[renderEffectName];
  27255. if (!renderEffects) {
  27256. return;
  27257. }
  27258. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27259. };
  27260. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27261. var renderEffects = this._renderEffects[renderEffectName];
  27262. if (!renderEffects) {
  27263. return;
  27264. }
  27265. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27266. };
  27267. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27268. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27269. var indicesToDelete = [];
  27270. for (var i = 0; i < _cam.length; i++) {
  27271. var camera = _cam[i];
  27272. var cameraName = camera.name;
  27273. if (this._cameras.indexOf(camera) === -1) {
  27274. this._cameras[cameraName] = camera;
  27275. }
  27276. else if (unique) {
  27277. indicesToDelete.push(i);
  27278. }
  27279. }
  27280. for (var i = 0; i < indicesToDelete.length; i++) {
  27281. cameras.splice(indicesToDelete[i], 1);
  27282. }
  27283. for (var renderEffectName in this._renderEffects) {
  27284. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27285. }
  27286. };
  27287. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27288. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27289. for (var renderEffectName in this._renderEffects) {
  27290. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27291. }
  27292. for (var i = 0; i < _cam.length; i++) {
  27293. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27294. }
  27295. };
  27296. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27297. var _this = this;
  27298. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27299. var pass = null;
  27300. for (var renderEffectName in this._renderEffects) {
  27301. pass = this._renderEffects[renderEffectName].getPass(passName);
  27302. if (pass != null) {
  27303. break;
  27304. }
  27305. }
  27306. if (pass === null) {
  27307. return;
  27308. }
  27309. for (var renderEffectName in this._renderEffects) {
  27310. this._renderEffects[renderEffectName]._disable(_cam);
  27311. }
  27312. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27313. for (var i = 0; i < _cam.length; i++) {
  27314. var camera = _cam[i];
  27315. var cameraName = camera.name;
  27316. 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); });
  27317. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27318. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27319. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27320. }
  27321. };
  27322. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27323. var _this = this;
  27324. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27325. for (var i = 0; i < _cam.length; i++) {
  27326. var camera = _cam[i];
  27327. var cameraName = camera.name;
  27328. 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); });
  27329. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27330. }
  27331. for (var renderEffectName in this._renderEffects) {
  27332. this._renderEffects[renderEffectName]._enable(_cam);
  27333. }
  27334. };
  27335. PostProcessRenderPipeline.prototype._update = function () {
  27336. for (var renderEffectName in this._renderEffects) {
  27337. this._renderEffects[renderEffectName]._update();
  27338. }
  27339. for (var i = 0; i < this._cameras.length; i++) {
  27340. var cameraName = this._cameras[i].name;
  27341. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27342. this._renderEffectsForIsolatedPass[cameraName]._update();
  27343. }
  27344. }
  27345. };
  27346. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27347. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27348. return PostProcessRenderPipeline;
  27349. })();
  27350. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27351. })(BABYLON || (BABYLON = {}));
  27352. var BABYLON;
  27353. (function (BABYLON) {
  27354. var PostProcessRenderPipelineManager = (function () {
  27355. function PostProcessRenderPipelineManager() {
  27356. this._renderPipelines = {};
  27357. }
  27358. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27359. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27360. };
  27361. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27362. var renderPipeline = this._renderPipelines[renderPipelineName];
  27363. if (!renderPipeline) {
  27364. return;
  27365. }
  27366. renderPipeline._attachCameras(cameras, unique);
  27367. };
  27368. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27369. var renderPipeline = this._renderPipelines[renderPipelineName];
  27370. if (!renderPipeline) {
  27371. return;
  27372. }
  27373. renderPipeline._detachCameras(cameras);
  27374. };
  27375. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27376. var renderPipeline = this._renderPipelines[renderPipelineName];
  27377. if (!renderPipeline) {
  27378. return;
  27379. }
  27380. renderPipeline._enableEffect(renderEffectName, cameras);
  27381. };
  27382. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27383. var renderPipeline = this._renderPipelines[renderPipelineName];
  27384. if (!renderPipeline) {
  27385. return;
  27386. }
  27387. renderPipeline._disableEffect(renderEffectName, cameras);
  27388. };
  27389. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27390. var renderPipeline = this._renderPipelines[renderPipelineName];
  27391. if (!renderPipeline) {
  27392. return;
  27393. }
  27394. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27395. };
  27396. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27397. var renderPipeline = this._renderPipelines[renderPipelineName];
  27398. if (!renderPipeline) {
  27399. return;
  27400. }
  27401. renderPipeline._disableDisplayOnlyPass(cameras);
  27402. };
  27403. PostProcessRenderPipelineManager.prototype.update = function () {
  27404. for (var renderPipelineName in this._renderPipelines) {
  27405. this._renderPipelines[renderPipelineName]._update();
  27406. }
  27407. };
  27408. return PostProcessRenderPipelineManager;
  27409. })();
  27410. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27411. })(BABYLON || (BABYLON = {}));
  27412. var BABYLON;
  27413. (function (BABYLON) {
  27414. var DisplayPassPostProcess = (function (_super) {
  27415. __extends(DisplayPassPostProcess, _super);
  27416. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27417. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27418. }
  27419. return DisplayPassPostProcess;
  27420. })(BABYLON.PostProcess);
  27421. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27422. })(BABYLON || (BABYLON = {}));
  27423. var BABYLON;
  27424. (function (BABYLON) {
  27425. var BoundingBoxRenderer = (function () {
  27426. function BoundingBoxRenderer(scene) {
  27427. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27428. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27429. this.showBackLines = true;
  27430. this.renderList = new BABYLON.SmartArray(32);
  27431. this._scene = scene;
  27432. }
  27433. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27434. if (this._colorShader) {
  27435. return;
  27436. }
  27437. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27438. attributes: ["position"],
  27439. uniforms: ["worldViewProjection", "color"]
  27440. });
  27441. var engine = this._scene.getEngine();
  27442. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27443. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27444. 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]);
  27445. };
  27446. BoundingBoxRenderer.prototype.reset = function () {
  27447. this.renderList.reset();
  27448. };
  27449. BoundingBoxRenderer.prototype.render = function () {
  27450. if (this.renderList.length === 0) {
  27451. return;
  27452. }
  27453. this._prepareRessources();
  27454. if (!this._colorShader.isReady()) {
  27455. return;
  27456. }
  27457. var engine = this._scene.getEngine();
  27458. engine.setDepthWrite(false);
  27459. this._colorShader._preBind();
  27460. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27461. var boundingBox = this.renderList.data[boundingBoxIndex];
  27462. var min = boundingBox.minimum;
  27463. var max = boundingBox.maximum;
  27464. var diff = max.subtract(min);
  27465. var median = min.add(diff.scale(0.5));
  27466. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27467. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27468. .multiply(boundingBox.getWorldMatrix());
  27469. // VBOs
  27470. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27471. if (this.showBackLines) {
  27472. // Back
  27473. engine.setDepthFunctionToGreaterOrEqual();
  27474. this._scene.resetCachedMaterial();
  27475. this._colorShader.setColor4("color", this.backColor.toColor4());
  27476. this._colorShader.bind(worldMatrix);
  27477. // Draw order
  27478. engine.draw(false, 0, 24);
  27479. }
  27480. // Front
  27481. engine.setDepthFunctionToLess();
  27482. this._scene.resetCachedMaterial();
  27483. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27484. this._colorShader.bind(worldMatrix);
  27485. // Draw order
  27486. engine.draw(false, 0, 24);
  27487. }
  27488. this._colorShader.unbind();
  27489. engine.setDepthFunctionToLessOrEqual();
  27490. engine.setDepthWrite(true);
  27491. };
  27492. BoundingBoxRenderer.prototype.dispose = function () {
  27493. if (!this._colorShader) {
  27494. return;
  27495. }
  27496. this._colorShader.dispose();
  27497. this._vb.dispose();
  27498. this._scene.getEngine()._releaseBuffer(this._ib);
  27499. };
  27500. return BoundingBoxRenderer;
  27501. })();
  27502. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27503. })(BABYLON || (BABYLON = {}));
  27504. var BABYLON;
  27505. (function (BABYLON) {
  27506. var Condition = (function () {
  27507. function Condition(actionManager) {
  27508. this._actionManager = actionManager;
  27509. }
  27510. Condition.prototype.isValid = function () {
  27511. return true;
  27512. };
  27513. Condition.prototype._getProperty = function (propertyPath) {
  27514. return this._actionManager._getProperty(propertyPath);
  27515. };
  27516. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27517. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27518. };
  27519. return Condition;
  27520. })();
  27521. BABYLON.Condition = Condition;
  27522. var ValueCondition = (function (_super) {
  27523. __extends(ValueCondition, _super);
  27524. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27525. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27526. _super.call(this, actionManager);
  27527. this.propertyPath = propertyPath;
  27528. this.value = value;
  27529. this.operator = operator;
  27530. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27531. this._property = this._getProperty(this.propertyPath);
  27532. }
  27533. Object.defineProperty(ValueCondition, "IsEqual", {
  27534. get: function () {
  27535. return ValueCondition._IsEqual;
  27536. },
  27537. enumerable: true,
  27538. configurable: true
  27539. });
  27540. Object.defineProperty(ValueCondition, "IsDifferent", {
  27541. get: function () {
  27542. return ValueCondition._IsDifferent;
  27543. },
  27544. enumerable: true,
  27545. configurable: true
  27546. });
  27547. Object.defineProperty(ValueCondition, "IsGreater", {
  27548. get: function () {
  27549. return ValueCondition._IsGreater;
  27550. },
  27551. enumerable: true,
  27552. configurable: true
  27553. });
  27554. Object.defineProperty(ValueCondition, "IsLesser", {
  27555. get: function () {
  27556. return ValueCondition._IsLesser;
  27557. },
  27558. enumerable: true,
  27559. configurable: true
  27560. });
  27561. // Methods
  27562. ValueCondition.prototype.isValid = function () {
  27563. switch (this.operator) {
  27564. case ValueCondition.IsGreater:
  27565. return this._target[this._property] > this.value;
  27566. case ValueCondition.IsLesser:
  27567. return this._target[this._property] < this.value;
  27568. case ValueCondition.IsEqual:
  27569. case ValueCondition.IsDifferent:
  27570. var check;
  27571. if (this.value.equals) {
  27572. check = this.value.equals(this._target[this._property]);
  27573. }
  27574. else {
  27575. check = this.value === this._target[this._property];
  27576. }
  27577. return this.operator === ValueCondition.IsEqual ? check : !check;
  27578. }
  27579. return false;
  27580. };
  27581. // Statics
  27582. ValueCondition._IsEqual = 0;
  27583. ValueCondition._IsDifferent = 1;
  27584. ValueCondition._IsGreater = 2;
  27585. ValueCondition._IsLesser = 3;
  27586. return ValueCondition;
  27587. })(Condition);
  27588. BABYLON.ValueCondition = ValueCondition;
  27589. var PredicateCondition = (function (_super) {
  27590. __extends(PredicateCondition, _super);
  27591. function PredicateCondition(actionManager, predicate) {
  27592. _super.call(this, actionManager);
  27593. this.predicate = predicate;
  27594. }
  27595. PredicateCondition.prototype.isValid = function () {
  27596. return this.predicate();
  27597. };
  27598. return PredicateCondition;
  27599. })(Condition);
  27600. BABYLON.PredicateCondition = PredicateCondition;
  27601. var StateCondition = (function (_super) {
  27602. __extends(StateCondition, _super);
  27603. function StateCondition(actionManager, target, value) {
  27604. _super.call(this, actionManager);
  27605. this.value = value;
  27606. this._target = target;
  27607. }
  27608. // Methods
  27609. StateCondition.prototype.isValid = function () {
  27610. return this._target.state === this.value;
  27611. };
  27612. return StateCondition;
  27613. })(Condition);
  27614. BABYLON.StateCondition = StateCondition;
  27615. })(BABYLON || (BABYLON = {}));
  27616. var BABYLON;
  27617. (function (BABYLON) {
  27618. var Action = (function () {
  27619. function Action(triggerOptions, condition) {
  27620. this.triggerOptions = triggerOptions;
  27621. if (triggerOptions.parameter) {
  27622. this.trigger = triggerOptions.trigger;
  27623. this._triggerParameter = triggerOptions.parameter;
  27624. }
  27625. else {
  27626. this.trigger = triggerOptions;
  27627. }
  27628. this._nextActiveAction = this;
  27629. this._condition = condition;
  27630. }
  27631. // Methods
  27632. Action.prototype._prepare = function () {
  27633. };
  27634. Action.prototype.getTriggerParameter = function () {
  27635. return this._triggerParameter;
  27636. };
  27637. Action.prototype._executeCurrent = function (evt) {
  27638. if (this._nextActiveAction._condition) {
  27639. var condition = this._nextActiveAction._condition;
  27640. var currentRenderId = this._actionManager.getScene().getRenderId();
  27641. // We cache the current evaluation for the current frame
  27642. if (condition._evaluationId === currentRenderId) {
  27643. if (!condition._currentResult) {
  27644. return;
  27645. }
  27646. }
  27647. else {
  27648. condition._evaluationId = currentRenderId;
  27649. if (!condition.isValid()) {
  27650. condition._currentResult = false;
  27651. return;
  27652. }
  27653. condition._currentResult = true;
  27654. }
  27655. }
  27656. this._nextActiveAction.execute(evt);
  27657. if (this._nextActiveAction._child) {
  27658. if (!this._nextActiveAction._child._actionManager) {
  27659. this._nextActiveAction._child._actionManager = this._actionManager;
  27660. }
  27661. this._nextActiveAction = this._nextActiveAction._child;
  27662. }
  27663. else {
  27664. this._nextActiveAction = this;
  27665. }
  27666. };
  27667. Action.prototype.execute = function (evt) {
  27668. };
  27669. Action.prototype.then = function (action) {
  27670. this._child = action;
  27671. action._actionManager = this._actionManager;
  27672. action._prepare();
  27673. return action;
  27674. };
  27675. Action.prototype._getProperty = function (propertyPath) {
  27676. return this._actionManager._getProperty(propertyPath);
  27677. };
  27678. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27679. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27680. };
  27681. return Action;
  27682. })();
  27683. BABYLON.Action = Action;
  27684. })(BABYLON || (BABYLON = {}));
  27685. var BABYLON;
  27686. (function (BABYLON) {
  27687. /**
  27688. * ActionEvent is the event beint sent when an action is triggered.
  27689. */
  27690. var ActionEvent = (function () {
  27691. /**
  27692. * @constructor
  27693. * @param source The mesh that triggered the action.
  27694. * @param pointerX the X mouse cursor position at the time of the event
  27695. * @param pointerY the Y mouse cursor position at the time of the event
  27696. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27697. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27698. */
  27699. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27700. this.source = source;
  27701. this.pointerX = pointerX;
  27702. this.pointerY = pointerY;
  27703. this.meshUnderPointer = meshUnderPointer;
  27704. this.sourceEvent = sourceEvent;
  27705. this.additionalData = additionalData;
  27706. }
  27707. /**
  27708. * Helper function to auto-create an ActionEvent from a source mesh.
  27709. * @param source the source mesh that triggered the event
  27710. * @param evt {Event} The original (browser) event
  27711. */
  27712. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27713. var scene = source.getScene();
  27714. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27715. };
  27716. /**
  27717. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27718. * @param scene the scene where the event occurred
  27719. * @param evt {Event} The original (browser) event
  27720. */
  27721. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27722. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27723. };
  27724. return ActionEvent;
  27725. })();
  27726. BABYLON.ActionEvent = ActionEvent;
  27727. /**
  27728. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27729. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27730. */
  27731. var ActionManager = (function () {
  27732. function ActionManager(scene) {
  27733. // Members
  27734. this.actions = new Array();
  27735. this._scene = scene;
  27736. scene._actionManagers.push(this);
  27737. }
  27738. Object.defineProperty(ActionManager, "NothingTrigger", {
  27739. get: function () {
  27740. return ActionManager._NothingTrigger;
  27741. },
  27742. enumerable: true,
  27743. configurable: true
  27744. });
  27745. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27746. get: function () {
  27747. return ActionManager._OnPickTrigger;
  27748. },
  27749. enumerable: true,
  27750. configurable: true
  27751. });
  27752. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27753. get: function () {
  27754. return ActionManager._OnLeftPickTrigger;
  27755. },
  27756. enumerable: true,
  27757. configurable: true
  27758. });
  27759. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27760. get: function () {
  27761. return ActionManager._OnRightPickTrigger;
  27762. },
  27763. enumerable: true,
  27764. configurable: true
  27765. });
  27766. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27767. get: function () {
  27768. return ActionManager._OnCenterPickTrigger;
  27769. },
  27770. enumerable: true,
  27771. configurable: true
  27772. });
  27773. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27774. get: function () {
  27775. return ActionManager._OnPointerOverTrigger;
  27776. },
  27777. enumerable: true,
  27778. configurable: true
  27779. });
  27780. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27781. get: function () {
  27782. return ActionManager._OnPointerOutTrigger;
  27783. },
  27784. enumerable: true,
  27785. configurable: true
  27786. });
  27787. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27788. get: function () {
  27789. return ActionManager._OnEveryFrameTrigger;
  27790. },
  27791. enumerable: true,
  27792. configurable: true
  27793. });
  27794. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27795. get: function () {
  27796. return ActionManager._OnIntersectionEnterTrigger;
  27797. },
  27798. enumerable: true,
  27799. configurable: true
  27800. });
  27801. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27802. get: function () {
  27803. return ActionManager._OnIntersectionExitTrigger;
  27804. },
  27805. enumerable: true,
  27806. configurable: true
  27807. });
  27808. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27809. get: function () {
  27810. return ActionManager._OnKeyDownTrigger;
  27811. },
  27812. enumerable: true,
  27813. configurable: true
  27814. });
  27815. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27816. get: function () {
  27817. return ActionManager._OnKeyUpTrigger;
  27818. },
  27819. enumerable: true,
  27820. configurable: true
  27821. });
  27822. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27823. get: function () {
  27824. return ActionManager._OnPickUpTrigger;
  27825. },
  27826. enumerable: true,
  27827. configurable: true
  27828. });
  27829. // Methods
  27830. ActionManager.prototype.dispose = function () {
  27831. var index = this._scene._actionManagers.indexOf(this);
  27832. if (index > -1) {
  27833. this._scene._actionManagers.splice(index, 1);
  27834. }
  27835. };
  27836. ActionManager.prototype.getScene = function () {
  27837. return this._scene;
  27838. };
  27839. /**
  27840. * Does this action manager handles actions of any of the given triggers
  27841. * @param {number[]} triggers - the triggers to be tested
  27842. * @return {boolean} whether one (or more) of the triggers is handeled
  27843. */
  27844. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27845. for (var index = 0; index < this.actions.length; index++) {
  27846. var action = this.actions[index];
  27847. if (triggers.indexOf(action.trigger) > -1) {
  27848. return true;
  27849. }
  27850. }
  27851. return false;
  27852. };
  27853. /**
  27854. * Does this action manager handles actions of a given trigger
  27855. * @param {number} trigger - the trigger to be tested
  27856. * @return {boolean} whether the trigger is handeled
  27857. */
  27858. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27859. for (var index = 0; index < this.actions.length; index++) {
  27860. var action = this.actions[index];
  27861. if (action.trigger === trigger) {
  27862. return true;
  27863. }
  27864. }
  27865. return false;
  27866. };
  27867. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27868. /**
  27869. * Does this action manager has pointer triggers
  27870. * @return {boolean} whether or not it has pointer triggers
  27871. */
  27872. get: function () {
  27873. for (var index = 0; index < this.actions.length; index++) {
  27874. var action = this.actions[index];
  27875. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27876. return true;
  27877. }
  27878. if (action.trigger == ActionManager._OnPickUpTrigger) {
  27879. return true;
  27880. }
  27881. }
  27882. return false;
  27883. },
  27884. enumerable: true,
  27885. configurable: true
  27886. });
  27887. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27888. /**
  27889. * Does this action manager has pick triggers
  27890. * @return {boolean} whether or not it has pick triggers
  27891. */
  27892. get: function () {
  27893. for (var index = 0; index < this.actions.length; index++) {
  27894. var action = this.actions[index];
  27895. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  27896. return true;
  27897. }
  27898. }
  27899. return false;
  27900. },
  27901. enumerable: true,
  27902. configurable: true
  27903. });
  27904. /**
  27905. * Registers an action to this action manager
  27906. * @param {BABYLON.Action} action - the action to be registered
  27907. * @return {BABYLON.Action} the action amended (prepared) after registration
  27908. */
  27909. ActionManager.prototype.registerAction = function (action) {
  27910. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27911. if (this.getScene().actionManager !== this) {
  27912. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27913. return null;
  27914. }
  27915. }
  27916. this.actions.push(action);
  27917. action._actionManager = this;
  27918. action._prepare();
  27919. return action;
  27920. };
  27921. /**
  27922. * Process a specific trigger
  27923. * @param {number} trigger - the trigger to process
  27924. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27925. */
  27926. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27927. for (var index = 0; index < this.actions.length; index++) {
  27928. var action = this.actions[index];
  27929. if (action.trigger === trigger) {
  27930. if (trigger === ActionManager.OnKeyUpTrigger
  27931. || trigger === ActionManager.OnKeyDownTrigger) {
  27932. var parameter = action.getTriggerParameter();
  27933. if (parameter) {
  27934. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27935. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27936. if (actualkey !== parameter.toLowerCase()) {
  27937. continue;
  27938. }
  27939. }
  27940. }
  27941. action._executeCurrent(evt);
  27942. }
  27943. }
  27944. };
  27945. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27946. var properties = propertyPath.split(".");
  27947. for (var index = 0; index < properties.length - 1; index++) {
  27948. target = target[properties[index]];
  27949. }
  27950. return target;
  27951. };
  27952. ActionManager.prototype._getProperty = function (propertyPath) {
  27953. var properties = propertyPath.split(".");
  27954. return properties[properties.length - 1];
  27955. };
  27956. // Statics
  27957. ActionManager._NothingTrigger = 0;
  27958. ActionManager._OnPickTrigger = 1;
  27959. ActionManager._OnLeftPickTrigger = 2;
  27960. ActionManager._OnRightPickTrigger = 3;
  27961. ActionManager._OnCenterPickTrigger = 4;
  27962. ActionManager._OnPointerOverTrigger = 5;
  27963. ActionManager._OnPointerOutTrigger = 6;
  27964. ActionManager._OnEveryFrameTrigger = 7;
  27965. ActionManager._OnIntersectionEnterTrigger = 8;
  27966. ActionManager._OnIntersectionExitTrigger = 9;
  27967. ActionManager._OnKeyDownTrigger = 10;
  27968. ActionManager._OnKeyUpTrigger = 11;
  27969. ActionManager._OnPickUpTrigger = 12;
  27970. return ActionManager;
  27971. })();
  27972. BABYLON.ActionManager = ActionManager;
  27973. })(BABYLON || (BABYLON = {}));
  27974. var BABYLON;
  27975. (function (BABYLON) {
  27976. var InterpolateValueAction = (function (_super) {
  27977. __extends(InterpolateValueAction, _super);
  27978. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  27979. if (duration === void 0) { duration = 1000; }
  27980. _super.call(this, triggerOptions, condition);
  27981. this.propertyPath = propertyPath;
  27982. this.value = value;
  27983. this.duration = duration;
  27984. this.stopOtherAnimations = stopOtherAnimations;
  27985. this._target = target;
  27986. }
  27987. InterpolateValueAction.prototype._prepare = function () {
  27988. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27989. this._property = this._getProperty(this.propertyPath);
  27990. };
  27991. InterpolateValueAction.prototype.execute = function () {
  27992. var scene = this._actionManager.getScene();
  27993. var keys = [
  27994. {
  27995. frame: 0,
  27996. value: this._target[this._property]
  27997. }, {
  27998. frame: 100,
  27999. value: this.value
  28000. }
  28001. ];
  28002. var dataType;
  28003. if (typeof this.value === "number") {
  28004. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28005. }
  28006. else if (this.value instanceof BABYLON.Color3) {
  28007. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28008. }
  28009. else if (this.value instanceof BABYLON.Vector3) {
  28010. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28011. }
  28012. else if (this.value instanceof BABYLON.Matrix) {
  28013. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28014. }
  28015. else if (this.value instanceof BABYLON.Quaternion) {
  28016. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28017. }
  28018. else {
  28019. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28020. return;
  28021. }
  28022. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28023. animation.setKeys(keys);
  28024. if (this.stopOtherAnimations) {
  28025. scene.stopAnimation(this._target);
  28026. }
  28027. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28028. };
  28029. return InterpolateValueAction;
  28030. })(BABYLON.Action);
  28031. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28032. })(BABYLON || (BABYLON = {}));
  28033. var BABYLON;
  28034. (function (BABYLON) {
  28035. var SwitchBooleanAction = (function (_super) {
  28036. __extends(SwitchBooleanAction, _super);
  28037. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28038. _super.call(this, triggerOptions, condition);
  28039. this.propertyPath = propertyPath;
  28040. this._target = target;
  28041. }
  28042. SwitchBooleanAction.prototype._prepare = function () {
  28043. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28044. this._property = this._getProperty(this.propertyPath);
  28045. };
  28046. SwitchBooleanAction.prototype.execute = function () {
  28047. this._target[this._property] = !this._target[this._property];
  28048. };
  28049. return SwitchBooleanAction;
  28050. })(BABYLON.Action);
  28051. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28052. var SetStateAction = (function (_super) {
  28053. __extends(SetStateAction, _super);
  28054. function SetStateAction(triggerOptions, target, value, condition) {
  28055. _super.call(this, triggerOptions, condition);
  28056. this.value = value;
  28057. this._target = target;
  28058. }
  28059. SetStateAction.prototype.execute = function () {
  28060. this._target.state = this.value;
  28061. };
  28062. return SetStateAction;
  28063. })(BABYLON.Action);
  28064. BABYLON.SetStateAction = SetStateAction;
  28065. var SetValueAction = (function (_super) {
  28066. __extends(SetValueAction, _super);
  28067. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28068. _super.call(this, triggerOptions, condition);
  28069. this.propertyPath = propertyPath;
  28070. this.value = value;
  28071. this._target = target;
  28072. }
  28073. SetValueAction.prototype._prepare = function () {
  28074. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28075. this._property = this._getProperty(this.propertyPath);
  28076. };
  28077. SetValueAction.prototype.execute = function () {
  28078. this._target[this._property] = this.value;
  28079. };
  28080. return SetValueAction;
  28081. })(BABYLON.Action);
  28082. BABYLON.SetValueAction = SetValueAction;
  28083. var IncrementValueAction = (function (_super) {
  28084. __extends(IncrementValueAction, _super);
  28085. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28086. _super.call(this, triggerOptions, condition);
  28087. this.propertyPath = propertyPath;
  28088. this.value = value;
  28089. this._target = target;
  28090. }
  28091. IncrementValueAction.prototype._prepare = function () {
  28092. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28093. this._property = this._getProperty(this.propertyPath);
  28094. if (typeof this._target[this._property] !== "number") {
  28095. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28096. }
  28097. };
  28098. IncrementValueAction.prototype.execute = function () {
  28099. this._target[this._property] += this.value;
  28100. };
  28101. return IncrementValueAction;
  28102. })(BABYLON.Action);
  28103. BABYLON.IncrementValueAction = IncrementValueAction;
  28104. var PlayAnimationAction = (function (_super) {
  28105. __extends(PlayAnimationAction, _super);
  28106. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28107. _super.call(this, triggerOptions, condition);
  28108. this.from = from;
  28109. this.to = to;
  28110. this.loop = loop;
  28111. this._target = target;
  28112. }
  28113. PlayAnimationAction.prototype._prepare = function () {
  28114. };
  28115. PlayAnimationAction.prototype.execute = function () {
  28116. var scene = this._actionManager.getScene();
  28117. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28118. };
  28119. return PlayAnimationAction;
  28120. })(BABYLON.Action);
  28121. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28122. var StopAnimationAction = (function (_super) {
  28123. __extends(StopAnimationAction, _super);
  28124. function StopAnimationAction(triggerOptions, target, condition) {
  28125. _super.call(this, triggerOptions, condition);
  28126. this._target = target;
  28127. }
  28128. StopAnimationAction.prototype._prepare = function () {
  28129. };
  28130. StopAnimationAction.prototype.execute = function () {
  28131. var scene = this._actionManager.getScene();
  28132. scene.stopAnimation(this._target);
  28133. };
  28134. return StopAnimationAction;
  28135. })(BABYLON.Action);
  28136. BABYLON.StopAnimationAction = StopAnimationAction;
  28137. var DoNothingAction = (function (_super) {
  28138. __extends(DoNothingAction, _super);
  28139. function DoNothingAction(triggerOptions, condition) {
  28140. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28141. _super.call(this, triggerOptions, condition);
  28142. }
  28143. DoNothingAction.prototype.execute = function () {
  28144. };
  28145. return DoNothingAction;
  28146. })(BABYLON.Action);
  28147. BABYLON.DoNothingAction = DoNothingAction;
  28148. var CombineAction = (function (_super) {
  28149. __extends(CombineAction, _super);
  28150. function CombineAction(triggerOptions, children, condition) {
  28151. _super.call(this, triggerOptions, condition);
  28152. this.children = children;
  28153. }
  28154. CombineAction.prototype._prepare = function () {
  28155. for (var index = 0; index < this.children.length; index++) {
  28156. this.children[index]._actionManager = this._actionManager;
  28157. this.children[index]._prepare();
  28158. }
  28159. };
  28160. CombineAction.prototype.execute = function (evt) {
  28161. for (var index = 0; index < this.children.length; index++) {
  28162. this.children[index].execute(evt);
  28163. }
  28164. };
  28165. return CombineAction;
  28166. })(BABYLON.Action);
  28167. BABYLON.CombineAction = CombineAction;
  28168. var ExecuteCodeAction = (function (_super) {
  28169. __extends(ExecuteCodeAction, _super);
  28170. function ExecuteCodeAction(triggerOptions, func, condition) {
  28171. _super.call(this, triggerOptions, condition);
  28172. this.func = func;
  28173. }
  28174. ExecuteCodeAction.prototype.execute = function (evt) {
  28175. this.func(evt);
  28176. };
  28177. return ExecuteCodeAction;
  28178. })(BABYLON.Action);
  28179. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28180. var SetParentAction = (function (_super) {
  28181. __extends(SetParentAction, _super);
  28182. function SetParentAction(triggerOptions, target, parent, condition) {
  28183. _super.call(this, triggerOptions, condition);
  28184. this._target = target;
  28185. this._parent = parent;
  28186. }
  28187. SetParentAction.prototype._prepare = function () {
  28188. };
  28189. SetParentAction.prototype.execute = function () {
  28190. if (this._target.parent === this._parent) {
  28191. return;
  28192. }
  28193. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28194. invertParentWorldMatrix.invert();
  28195. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28196. this._target.parent = this._parent;
  28197. };
  28198. return SetParentAction;
  28199. })(BABYLON.Action);
  28200. BABYLON.SetParentAction = SetParentAction;
  28201. var PlaySoundAction = (function (_super) {
  28202. __extends(PlaySoundAction, _super);
  28203. function PlaySoundAction(triggerOptions, sound, condition) {
  28204. _super.call(this, triggerOptions, condition);
  28205. this._sound = sound;
  28206. }
  28207. PlaySoundAction.prototype._prepare = function () {
  28208. };
  28209. PlaySoundAction.prototype.execute = function () {
  28210. if (this._sound !== undefined)
  28211. this._sound.play();
  28212. };
  28213. return PlaySoundAction;
  28214. })(BABYLON.Action);
  28215. BABYLON.PlaySoundAction = PlaySoundAction;
  28216. var StopSoundAction = (function (_super) {
  28217. __extends(StopSoundAction, _super);
  28218. function StopSoundAction(triggerOptions, sound, condition) {
  28219. _super.call(this, triggerOptions, condition);
  28220. this._sound = sound;
  28221. }
  28222. StopSoundAction.prototype._prepare = function () {
  28223. };
  28224. StopSoundAction.prototype.execute = function () {
  28225. if (this._sound !== undefined)
  28226. this._sound.stop();
  28227. };
  28228. return StopSoundAction;
  28229. })(BABYLON.Action);
  28230. BABYLON.StopSoundAction = StopSoundAction;
  28231. })(BABYLON || (BABYLON = {}));
  28232. var BABYLON;
  28233. (function (BABYLON) {
  28234. var Geometry = (function () {
  28235. function Geometry(id, scene, vertexData, updatable, mesh) {
  28236. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28237. this._totalVertices = 0;
  28238. this._indices = [];
  28239. this._isDisposed = false;
  28240. this.id = id;
  28241. this._engine = scene.getEngine();
  28242. this._meshes = [];
  28243. this._scene = scene;
  28244. // vertexData
  28245. if (vertexData) {
  28246. this.setAllVerticesData(vertexData, updatable);
  28247. }
  28248. else {
  28249. this._totalVertices = 0;
  28250. this._indices = [];
  28251. }
  28252. // applyToMesh
  28253. if (mesh) {
  28254. this.applyToMesh(mesh);
  28255. mesh.computeWorldMatrix(true);
  28256. }
  28257. }
  28258. Geometry.prototype.getScene = function () {
  28259. return this._scene;
  28260. };
  28261. Geometry.prototype.getEngine = function () {
  28262. return this._engine;
  28263. };
  28264. Geometry.prototype.isReady = function () {
  28265. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28266. };
  28267. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28268. vertexData.applyToGeometry(this, updatable);
  28269. this.notifyUpdate();
  28270. };
  28271. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28272. this._vertexBuffers = this._vertexBuffers || {};
  28273. if (this._vertexBuffers[kind]) {
  28274. this._vertexBuffers[kind].dispose();
  28275. }
  28276. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28277. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28278. stride = this._vertexBuffers[kind].getStrideSize();
  28279. this._totalVertices = data.length / stride;
  28280. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28281. var meshes = this._meshes;
  28282. var numOfMeshes = meshes.length;
  28283. for (var index = 0; index < numOfMeshes; index++) {
  28284. var mesh = meshes[index];
  28285. mesh._resetPointsArrayCache();
  28286. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28287. mesh._createGlobalSubMesh();
  28288. mesh.computeWorldMatrix(true);
  28289. }
  28290. }
  28291. this.notifyUpdate(kind);
  28292. };
  28293. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28294. var vertexBuffer = this.getVertexBuffer(kind);
  28295. if (!vertexBuffer) {
  28296. return;
  28297. }
  28298. vertexBuffer.updateDirectly(data, offset);
  28299. this.notifyUpdate(kind);
  28300. };
  28301. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28302. var vertexBuffer = this.getVertexBuffer(kind);
  28303. if (!vertexBuffer) {
  28304. return;
  28305. }
  28306. vertexBuffer.update(data);
  28307. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28308. var extend;
  28309. var stride = vertexBuffer.getStrideSize();
  28310. this._totalVertices = data.length / stride;
  28311. if (updateExtends) {
  28312. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28313. }
  28314. var meshes = this._meshes;
  28315. var numOfMeshes = meshes.length;
  28316. for (var index = 0; index < numOfMeshes; index++) {
  28317. var mesh = meshes[index];
  28318. mesh._resetPointsArrayCache();
  28319. if (updateExtends) {
  28320. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28321. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28322. var subMesh = mesh.subMeshes[subIndex];
  28323. subMesh.refreshBoundingInfo();
  28324. }
  28325. }
  28326. }
  28327. }
  28328. this.notifyUpdate(kind);
  28329. };
  28330. Geometry.prototype.getTotalVertices = function () {
  28331. if (!this.isReady()) {
  28332. return 0;
  28333. }
  28334. return this._totalVertices;
  28335. };
  28336. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28337. var vertexBuffer = this.getVertexBuffer(kind);
  28338. if (!vertexBuffer) {
  28339. return null;
  28340. }
  28341. var orig = vertexBuffer.getData();
  28342. if (!copyWhenShared || this._meshes.length === 1) {
  28343. return orig;
  28344. }
  28345. else {
  28346. var len = orig.length;
  28347. var copy = [];
  28348. for (var i = 0; i < len; i++) {
  28349. copy.push(orig[i]);
  28350. }
  28351. return copy;
  28352. }
  28353. };
  28354. Geometry.prototype.getVertexBuffer = function (kind) {
  28355. if (!this.isReady()) {
  28356. return null;
  28357. }
  28358. return this._vertexBuffers[kind];
  28359. };
  28360. Geometry.prototype.getVertexBuffers = function () {
  28361. if (!this.isReady()) {
  28362. return null;
  28363. }
  28364. return this._vertexBuffers;
  28365. };
  28366. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28367. if (!this._vertexBuffers) {
  28368. if (this._delayInfo) {
  28369. return this._delayInfo.indexOf(kind) !== -1;
  28370. }
  28371. return false;
  28372. }
  28373. return this._vertexBuffers[kind] !== undefined;
  28374. };
  28375. Geometry.prototype.getVerticesDataKinds = function () {
  28376. var result = [];
  28377. if (!this._vertexBuffers && this._delayInfo) {
  28378. for (var kind in this._delayInfo) {
  28379. result.push(kind);
  28380. }
  28381. }
  28382. else {
  28383. for (kind in this._vertexBuffers) {
  28384. result.push(kind);
  28385. }
  28386. }
  28387. return result;
  28388. };
  28389. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28390. if (this._indexBuffer) {
  28391. this._engine._releaseBuffer(this._indexBuffer);
  28392. }
  28393. this._indices = indices;
  28394. if (this._meshes.length !== 0 && this._indices) {
  28395. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28396. }
  28397. if (totalVertices !== undefined) {
  28398. this._totalVertices = totalVertices;
  28399. }
  28400. var meshes = this._meshes;
  28401. var numOfMeshes = meshes.length;
  28402. for (var index = 0; index < numOfMeshes; index++) {
  28403. meshes[index]._createGlobalSubMesh();
  28404. }
  28405. this.notifyUpdate();
  28406. };
  28407. Geometry.prototype.getTotalIndices = function () {
  28408. if (!this.isReady()) {
  28409. return 0;
  28410. }
  28411. return this._indices.length;
  28412. };
  28413. Geometry.prototype.getIndices = function (copyWhenShared) {
  28414. if (!this.isReady()) {
  28415. return null;
  28416. }
  28417. var orig = this._indices;
  28418. if (!copyWhenShared || this._meshes.length === 1) {
  28419. return orig;
  28420. }
  28421. else {
  28422. var len = orig.length;
  28423. var copy = [];
  28424. for (var i = 0; i < len; i++) {
  28425. copy.push(orig[i]);
  28426. }
  28427. return copy;
  28428. }
  28429. };
  28430. Geometry.prototype.getIndexBuffer = function () {
  28431. if (!this.isReady()) {
  28432. return null;
  28433. }
  28434. return this._indexBuffer;
  28435. };
  28436. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28437. var meshes = this._meshes;
  28438. var index = meshes.indexOf(mesh);
  28439. if (index === -1) {
  28440. return;
  28441. }
  28442. for (var kind in this._vertexBuffers) {
  28443. this._vertexBuffers[kind].dispose();
  28444. }
  28445. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28446. this._indexBuffer = null;
  28447. }
  28448. meshes.splice(index, 1);
  28449. mesh._geometry = null;
  28450. if (meshes.length === 0 && shouldDispose) {
  28451. this.dispose();
  28452. }
  28453. };
  28454. Geometry.prototype.applyToMesh = function (mesh) {
  28455. if (mesh._geometry === this) {
  28456. return;
  28457. }
  28458. var previousGeometry = mesh._geometry;
  28459. if (previousGeometry) {
  28460. previousGeometry.releaseForMesh(mesh);
  28461. }
  28462. var meshes = this._meshes;
  28463. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28464. mesh._geometry = this;
  28465. this._scene.pushGeometry(this);
  28466. meshes.push(mesh);
  28467. if (this.isReady()) {
  28468. this._applyToMesh(mesh);
  28469. }
  28470. else {
  28471. mesh._boundingInfo = this._boundingInfo;
  28472. }
  28473. };
  28474. Geometry.prototype._applyToMesh = function (mesh) {
  28475. var numOfMeshes = this._meshes.length;
  28476. // vertexBuffers
  28477. for (var kind in this._vertexBuffers) {
  28478. if (numOfMeshes === 1) {
  28479. this._vertexBuffers[kind].create();
  28480. }
  28481. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28482. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28483. mesh._resetPointsArrayCache();
  28484. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28485. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28486. mesh._createGlobalSubMesh();
  28487. //bounding info was just created again, world matrix should be applied again.
  28488. mesh._updateBoundingInfo();
  28489. }
  28490. }
  28491. // indexBuffer
  28492. if (numOfMeshes === 1 && this._indices) {
  28493. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28494. }
  28495. if (this._indexBuffer) {
  28496. this._indexBuffer.references = numOfMeshes;
  28497. }
  28498. };
  28499. Geometry.prototype.notifyUpdate = function (kind) {
  28500. if (this.onGeometryUpdated) {
  28501. this.onGeometryUpdated(this, kind);
  28502. }
  28503. };
  28504. Geometry.prototype.load = function (scene, onLoaded) {
  28505. var _this = this;
  28506. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28507. return;
  28508. }
  28509. if (this.isReady()) {
  28510. if (onLoaded) {
  28511. onLoaded();
  28512. }
  28513. return;
  28514. }
  28515. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28516. scene._addPendingData(this);
  28517. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28518. _this._delayLoadingFunction(JSON.parse(data), _this);
  28519. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28520. _this._delayInfo = [];
  28521. scene._removePendingData(_this);
  28522. var meshes = _this._meshes;
  28523. var numOfMeshes = meshes.length;
  28524. for (var index = 0; index < numOfMeshes; index++) {
  28525. _this._applyToMesh(meshes[index]);
  28526. }
  28527. if (onLoaded) {
  28528. onLoaded();
  28529. }
  28530. }, function () { }, scene.database);
  28531. };
  28532. Geometry.prototype.isDisposed = function () {
  28533. return this._isDisposed;
  28534. };
  28535. Geometry.prototype.dispose = function () {
  28536. var meshes = this._meshes;
  28537. var numOfMeshes = meshes.length;
  28538. var index;
  28539. for (index = 0; index < numOfMeshes; index++) {
  28540. this.releaseForMesh(meshes[index]);
  28541. }
  28542. this._meshes = [];
  28543. for (var kind in this._vertexBuffers) {
  28544. this._vertexBuffers[kind].dispose();
  28545. }
  28546. this._vertexBuffers = [];
  28547. this._totalVertices = 0;
  28548. if (this._indexBuffer) {
  28549. this._engine._releaseBuffer(this._indexBuffer);
  28550. }
  28551. this._indexBuffer = null;
  28552. this._indices = [];
  28553. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28554. this.delayLoadingFile = null;
  28555. this._delayLoadingFunction = null;
  28556. this._delayInfo = [];
  28557. this._boundingInfo = null; // todo: .dispose()
  28558. this._scene.removeGeometry(this);
  28559. this._isDisposed = true;
  28560. };
  28561. Geometry.prototype.copy = function (id) {
  28562. var vertexData = new BABYLON.VertexData();
  28563. vertexData.indices = [];
  28564. var indices = this.getIndices();
  28565. for (var index = 0; index < indices.length; index++) {
  28566. vertexData.indices.push(indices[index]);
  28567. }
  28568. var updatable = false;
  28569. var stopChecking = false;
  28570. for (var kind in this._vertexBuffers) {
  28571. // using slice() to make a copy of the array and not just reference it
  28572. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28573. if (!stopChecking) {
  28574. updatable = this.getVertexBuffer(kind).isUpdatable();
  28575. stopChecking = !updatable;
  28576. }
  28577. }
  28578. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28579. geometry.delayLoadState = this.delayLoadState;
  28580. geometry.delayLoadingFile = this.delayLoadingFile;
  28581. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28582. for (kind in this._delayInfo) {
  28583. geometry._delayInfo = geometry._delayInfo || [];
  28584. geometry._delayInfo.push(kind);
  28585. }
  28586. // Bounding info
  28587. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28588. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28589. return geometry;
  28590. };
  28591. // Statics
  28592. Geometry.ExtractFromMesh = function (mesh, id) {
  28593. var geometry = mesh._geometry;
  28594. if (!geometry) {
  28595. return null;
  28596. }
  28597. return geometry.copy(id);
  28598. };
  28599. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28600. // be aware Math.random() could cause collisions
  28601. Geometry.RandomId = function () {
  28602. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28603. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28604. return v.toString(16);
  28605. });
  28606. };
  28607. return Geometry;
  28608. })();
  28609. BABYLON.Geometry = Geometry;
  28610. /////// Primitives //////////////////////////////////////////////
  28611. var Geometry;
  28612. (function (Geometry) {
  28613. var Primitives;
  28614. (function (Primitives) {
  28615. /// Abstract class
  28616. var _Primitive = (function (_super) {
  28617. __extends(_Primitive, _super);
  28618. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28619. this._beingRegenerated = true;
  28620. this._canBeRegenerated = canBeRegenerated;
  28621. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28622. this._beingRegenerated = false;
  28623. }
  28624. _Primitive.prototype.canBeRegenerated = function () {
  28625. return this._canBeRegenerated;
  28626. };
  28627. _Primitive.prototype.regenerate = function () {
  28628. if (!this._canBeRegenerated) {
  28629. return;
  28630. }
  28631. this._beingRegenerated = true;
  28632. this.setAllVerticesData(this._regenerateVertexData(), false);
  28633. this._beingRegenerated = false;
  28634. };
  28635. _Primitive.prototype.asNewGeometry = function (id) {
  28636. return _super.prototype.copy.call(this, id);
  28637. };
  28638. // overrides
  28639. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28640. if (!this._beingRegenerated) {
  28641. return;
  28642. }
  28643. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28644. };
  28645. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28646. if (!this._beingRegenerated) {
  28647. return;
  28648. }
  28649. _super.prototype.setVerticesData.call(this, kind, data, false);
  28650. };
  28651. // to override
  28652. // protected
  28653. _Primitive.prototype._regenerateVertexData = function () {
  28654. throw new Error("Abstract method");
  28655. };
  28656. _Primitive.prototype.copy = function (id) {
  28657. throw new Error("Must be overriden in sub-classes.");
  28658. };
  28659. return _Primitive;
  28660. })(Geometry);
  28661. Primitives._Primitive = _Primitive;
  28662. var Ribbon = (function (_super) {
  28663. __extends(Ribbon, _super);
  28664. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28665. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28666. this.pathArray = pathArray;
  28667. this.closeArray = closeArray;
  28668. this.closePath = closePath;
  28669. this.offset = offset;
  28670. this.side = side;
  28671. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28672. }
  28673. Ribbon.prototype._regenerateVertexData = function () {
  28674. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28675. };
  28676. Ribbon.prototype.copy = function (id) {
  28677. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28678. };
  28679. return Ribbon;
  28680. })(_Primitive);
  28681. Primitives.Ribbon = Ribbon;
  28682. var Box = (function (_super) {
  28683. __extends(Box, _super);
  28684. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28685. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28686. this.size = size;
  28687. this.side = side;
  28688. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28689. }
  28690. Box.prototype._regenerateVertexData = function () {
  28691. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28692. };
  28693. Box.prototype.copy = function (id) {
  28694. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28695. };
  28696. return Box;
  28697. })(_Primitive);
  28698. Primitives.Box = Box;
  28699. var Sphere = (function (_super) {
  28700. __extends(Sphere, _super);
  28701. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28702. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28703. this.segments = segments;
  28704. this.diameter = diameter;
  28705. this.side = side;
  28706. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28707. }
  28708. Sphere.prototype._regenerateVertexData = function () {
  28709. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  28710. };
  28711. Sphere.prototype.copy = function (id) {
  28712. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28713. };
  28714. return Sphere;
  28715. })(_Primitive);
  28716. Primitives.Sphere = Sphere;
  28717. var Cylinder = (function (_super) {
  28718. __extends(Cylinder, _super);
  28719. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28720. if (subdivisions === void 0) { subdivisions = 1; }
  28721. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28722. this.height = height;
  28723. this.diameterTop = diameterTop;
  28724. this.diameterBottom = diameterBottom;
  28725. this.tessellation = tessellation;
  28726. this.subdivisions = subdivisions;
  28727. this.side = side;
  28728. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28729. }
  28730. Cylinder.prototype._regenerateVertexData = function () {
  28731. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  28732. };
  28733. Cylinder.prototype.copy = function (id) {
  28734. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28735. };
  28736. return Cylinder;
  28737. })(_Primitive);
  28738. Primitives.Cylinder = Cylinder;
  28739. var Torus = (function (_super) {
  28740. __extends(Torus, _super);
  28741. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28742. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28743. this.diameter = diameter;
  28744. this.thickness = thickness;
  28745. this.tessellation = tessellation;
  28746. this.side = side;
  28747. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28748. }
  28749. Torus.prototype._regenerateVertexData = function () {
  28750. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  28751. };
  28752. Torus.prototype.copy = function (id) {
  28753. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28754. };
  28755. return Torus;
  28756. })(_Primitive);
  28757. Primitives.Torus = Torus;
  28758. var Ground = (function (_super) {
  28759. __extends(Ground, _super);
  28760. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28761. this.width = width;
  28762. this.height = height;
  28763. this.subdivisions = subdivisions;
  28764. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28765. }
  28766. Ground.prototype._regenerateVertexData = function () {
  28767. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  28768. };
  28769. Ground.prototype.copy = function (id) {
  28770. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28771. };
  28772. return Ground;
  28773. })(_Primitive);
  28774. Primitives.Ground = Ground;
  28775. var TiledGround = (function (_super) {
  28776. __extends(TiledGround, _super);
  28777. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28778. this.xmin = xmin;
  28779. this.zmin = zmin;
  28780. this.xmax = xmax;
  28781. this.zmax = zmax;
  28782. this.subdivisions = subdivisions;
  28783. this.precision = precision;
  28784. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28785. }
  28786. TiledGround.prototype._regenerateVertexData = function () {
  28787. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  28788. };
  28789. TiledGround.prototype.copy = function (id) {
  28790. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28791. };
  28792. return TiledGround;
  28793. })(_Primitive);
  28794. Primitives.TiledGround = TiledGround;
  28795. var Plane = (function (_super) {
  28796. __extends(Plane, _super);
  28797. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28798. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28799. this.size = size;
  28800. this.side = side;
  28801. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28802. }
  28803. Plane.prototype._regenerateVertexData = function () {
  28804. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  28805. };
  28806. Plane.prototype.copy = function (id) {
  28807. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28808. };
  28809. return Plane;
  28810. })(_Primitive);
  28811. Primitives.Plane = Plane;
  28812. var TorusKnot = (function (_super) {
  28813. __extends(TorusKnot, _super);
  28814. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28815. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28816. this.radius = radius;
  28817. this.tube = tube;
  28818. this.radialSegments = radialSegments;
  28819. this.tubularSegments = tubularSegments;
  28820. this.p = p;
  28821. this.q = q;
  28822. this.side = side;
  28823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28824. }
  28825. TorusKnot.prototype._regenerateVertexData = function () {
  28826. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  28827. };
  28828. TorusKnot.prototype.copy = function (id) {
  28829. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28830. };
  28831. return TorusKnot;
  28832. })(_Primitive);
  28833. Primitives.TorusKnot = TorusKnot;
  28834. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28835. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28836. })(BABYLON || (BABYLON = {}));
  28837. var BABYLON;
  28838. (function (BABYLON) {
  28839. var GroundMesh = (function (_super) {
  28840. __extends(GroundMesh, _super);
  28841. function GroundMesh(name, scene) {
  28842. _super.call(this, name, scene);
  28843. this.generateOctree = false;
  28844. this._worldInverse = new BABYLON.Matrix();
  28845. }
  28846. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28847. get: function () {
  28848. return this._subdivisions;
  28849. },
  28850. enumerable: true,
  28851. configurable: true
  28852. });
  28853. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28854. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28855. this._subdivisions = chunksCount;
  28856. this.subdivide(this._subdivisions);
  28857. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28858. };
  28859. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28860. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28861. this.getWorldMatrix().invertToRef(this._worldInverse);
  28862. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28863. var pickInfo = this.intersects(ray);
  28864. if (pickInfo.hit) {
  28865. return pickInfo.pickedPoint.y;
  28866. }
  28867. return 0;
  28868. };
  28869. return GroundMesh;
  28870. })(BABYLON.Mesh);
  28871. BABYLON.GroundMesh = GroundMesh;
  28872. })(BABYLON || (BABYLON = {}));
  28873. var BABYLON;
  28874. (function (BABYLON) {
  28875. var LinesMesh = (function (_super) {
  28876. __extends(LinesMesh, _super);
  28877. function LinesMesh(name, scene, updatable) {
  28878. if (updatable === void 0) { updatable = false; }
  28879. _super.call(this, name, scene);
  28880. this.color = new BABYLON.Color3(1, 1, 1);
  28881. this.alpha = 1;
  28882. this._indices = new Array();
  28883. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28884. attributes: ["position"],
  28885. uniforms: ["worldViewProjection", "color"],
  28886. needAlphaBlending: true
  28887. });
  28888. }
  28889. Object.defineProperty(LinesMesh.prototype, "material", {
  28890. get: function () {
  28891. return this._colorShader;
  28892. },
  28893. enumerable: true,
  28894. configurable: true
  28895. });
  28896. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28897. get: function () {
  28898. return false;
  28899. },
  28900. enumerable: true,
  28901. configurable: true
  28902. });
  28903. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28904. get: function () {
  28905. return false;
  28906. },
  28907. enumerable: true,
  28908. configurable: true
  28909. });
  28910. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28911. var engine = this.getScene().getEngine();
  28912. var indexToBind = this._geometry.getIndexBuffer();
  28913. // VBOs
  28914. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28915. // Color
  28916. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28917. };
  28918. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28919. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28920. return;
  28921. }
  28922. var engine = this.getScene().getEngine();
  28923. // Draw order
  28924. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28925. };
  28926. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28927. return null;
  28928. };
  28929. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28930. this._colorShader.dispose();
  28931. _super.prototype.dispose.call(this, doNotRecurse);
  28932. };
  28933. return LinesMesh;
  28934. })(BABYLON.Mesh);
  28935. BABYLON.LinesMesh = LinesMesh;
  28936. })(BABYLON || (BABYLON = {}));
  28937. var BABYLON;
  28938. (function (BABYLON) {
  28939. var OutlineRenderer = (function () {
  28940. function OutlineRenderer(scene) {
  28941. this._scene = scene;
  28942. }
  28943. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  28944. var _this = this;
  28945. if (useOverlay === void 0) { useOverlay = false; }
  28946. var scene = this._scene;
  28947. var engine = this._scene.getEngine();
  28948. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28949. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  28950. return;
  28951. }
  28952. var mesh = subMesh.getRenderingMesh();
  28953. var material = subMesh.getMaterial();
  28954. engine.enableEffect(this._effect);
  28955. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  28956. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  28957. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28958. // Bones
  28959. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  28960. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28961. }
  28962. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  28963. // Alpha test
  28964. if (material && material.needAlphaTesting()) {
  28965. var alphaTexture = material.getAlphaTestTexture();
  28966. this._effect.setTexture("diffuseSampler", alphaTexture);
  28967. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28968. }
  28969. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  28970. };
  28971. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  28972. var defines = [];
  28973. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  28974. var mesh = subMesh.getMesh();
  28975. var material = subMesh.getMaterial();
  28976. // Alpha test
  28977. if (material && material.needAlphaTesting()) {
  28978. defines.push("#define ALPHATEST");
  28979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28980. attribs.push(BABYLON.VertexBuffer.UVKind);
  28981. defines.push("#define UV1");
  28982. }
  28983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28985. defines.push("#define UV2");
  28986. }
  28987. }
  28988. // Bones
  28989. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  28990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28992. defines.push("#define BONES");
  28993. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28994. }
  28995. // Instances
  28996. if (useInstances) {
  28997. defines.push("#define INSTANCES");
  28998. attribs.push("world0");
  28999. attribs.push("world1");
  29000. attribs.push("world2");
  29001. attribs.push("world3");
  29002. }
  29003. // Get correct effect
  29004. var join = defines.join("\n");
  29005. if (this._cachedDefines !== join) {
  29006. this._cachedDefines = join;
  29007. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29008. }
  29009. return this._effect.isReady();
  29010. };
  29011. return OutlineRenderer;
  29012. })();
  29013. BABYLON.OutlineRenderer = OutlineRenderer;
  29014. })(BABYLON || (BABYLON = {}));
  29015. var BABYLON;
  29016. (function (BABYLON) {
  29017. var MeshAssetTask = (function () {
  29018. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29019. this.name = name;
  29020. this.meshesNames = meshesNames;
  29021. this.rootUrl = rootUrl;
  29022. this.sceneFilename = sceneFilename;
  29023. this.isCompleted = false;
  29024. }
  29025. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29026. var _this = this;
  29027. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29028. _this.loadedMeshes = meshes;
  29029. _this.loadedParticleSystems = particleSystems;
  29030. _this.loadedSkeletons = skeletons;
  29031. _this.isCompleted = true;
  29032. if (_this.onSuccess) {
  29033. _this.onSuccess(_this);
  29034. }
  29035. onSuccess();
  29036. }, null, function () {
  29037. if (_this.onError) {
  29038. _this.onError(_this);
  29039. }
  29040. onError();
  29041. });
  29042. };
  29043. return MeshAssetTask;
  29044. })();
  29045. BABYLON.MeshAssetTask = MeshAssetTask;
  29046. var TextFileAssetTask = (function () {
  29047. function TextFileAssetTask(name, url) {
  29048. this.name = name;
  29049. this.url = url;
  29050. this.isCompleted = false;
  29051. }
  29052. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29053. var _this = this;
  29054. BABYLON.Tools.LoadFile(this.url, function (data) {
  29055. _this.text = data;
  29056. _this.isCompleted = true;
  29057. if (_this.onSuccess) {
  29058. _this.onSuccess(_this);
  29059. }
  29060. onSuccess();
  29061. }, null, scene.database, false, function () {
  29062. if (_this.onError) {
  29063. _this.onError(_this);
  29064. }
  29065. onError();
  29066. });
  29067. };
  29068. return TextFileAssetTask;
  29069. })();
  29070. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29071. var BinaryFileAssetTask = (function () {
  29072. function BinaryFileAssetTask(name, url) {
  29073. this.name = name;
  29074. this.url = url;
  29075. this.isCompleted = false;
  29076. }
  29077. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29078. var _this = this;
  29079. BABYLON.Tools.LoadFile(this.url, function (data) {
  29080. _this.data = data;
  29081. _this.isCompleted = true;
  29082. if (_this.onSuccess) {
  29083. _this.onSuccess(_this);
  29084. }
  29085. onSuccess();
  29086. }, null, scene.database, true, function () {
  29087. if (_this.onError) {
  29088. _this.onError(_this);
  29089. }
  29090. onError();
  29091. });
  29092. };
  29093. return BinaryFileAssetTask;
  29094. })();
  29095. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29096. var ImageAssetTask = (function () {
  29097. function ImageAssetTask(name, url) {
  29098. this.name = name;
  29099. this.url = url;
  29100. this.isCompleted = false;
  29101. }
  29102. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29103. var _this = this;
  29104. var img = new Image();
  29105. img.onload = function () {
  29106. _this.image = img;
  29107. _this.isCompleted = true;
  29108. if (_this.onSuccess) {
  29109. _this.onSuccess(_this);
  29110. }
  29111. onSuccess();
  29112. };
  29113. img.onerror = function () {
  29114. if (_this.onError) {
  29115. _this.onError(_this);
  29116. }
  29117. onError();
  29118. };
  29119. img.src = this.url;
  29120. };
  29121. return ImageAssetTask;
  29122. })();
  29123. BABYLON.ImageAssetTask = ImageAssetTask;
  29124. var TextureAssetTask = (function () {
  29125. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29126. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29127. this.name = name;
  29128. this.url = url;
  29129. this.noMipmap = noMipmap;
  29130. this.invertY = invertY;
  29131. this.samplingMode = samplingMode;
  29132. this.isCompleted = false;
  29133. }
  29134. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29135. var _this = this;
  29136. var onload = function () {
  29137. _this.isCompleted = true;
  29138. if (_this.onSuccess) {
  29139. _this.onSuccess(_this);
  29140. }
  29141. onSuccess();
  29142. };
  29143. var onerror = function () {
  29144. if (_this.onError) {
  29145. _this.onError(_this);
  29146. }
  29147. onError();
  29148. };
  29149. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29150. };
  29151. return TextureAssetTask;
  29152. })();
  29153. BABYLON.TextureAssetTask = TextureAssetTask;
  29154. var AssetsManager = (function () {
  29155. function AssetsManager(scene) {
  29156. this._tasks = new Array();
  29157. this._waitingTasksCount = 0;
  29158. this.useDefaultLoadingScreen = true;
  29159. this._scene = scene;
  29160. }
  29161. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29162. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29163. this._tasks.push(task);
  29164. return task;
  29165. };
  29166. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29167. var task = new TextFileAssetTask(taskName, url);
  29168. this._tasks.push(task);
  29169. return task;
  29170. };
  29171. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29172. var task = new BinaryFileAssetTask(taskName, url);
  29173. this._tasks.push(task);
  29174. return task;
  29175. };
  29176. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29177. var task = new ImageAssetTask(taskName, url);
  29178. this._tasks.push(task);
  29179. return task;
  29180. };
  29181. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29183. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29184. this._tasks.push(task);
  29185. return task;
  29186. };
  29187. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29188. this._waitingTasksCount--;
  29189. if (this._waitingTasksCount === 0) {
  29190. if (this.onFinish) {
  29191. this.onFinish(this._tasks);
  29192. }
  29193. this._scene.getEngine().hideLoadingUI();
  29194. }
  29195. };
  29196. AssetsManager.prototype._runTask = function (task) {
  29197. var _this = this;
  29198. task.run(this._scene, function () {
  29199. if (_this.onTaskSuccess) {
  29200. _this.onTaskSuccess(task);
  29201. }
  29202. _this._decreaseWaitingTasksCount();
  29203. }, function () {
  29204. if (_this.onTaskError) {
  29205. _this.onTaskError(task);
  29206. }
  29207. _this._decreaseWaitingTasksCount();
  29208. });
  29209. };
  29210. AssetsManager.prototype.reset = function () {
  29211. this._tasks = new Array();
  29212. return this;
  29213. };
  29214. AssetsManager.prototype.load = function () {
  29215. this._waitingTasksCount = this._tasks.length;
  29216. if (this._waitingTasksCount === 0) {
  29217. if (this.onFinish) {
  29218. this.onFinish(this._tasks);
  29219. }
  29220. return this;
  29221. }
  29222. if (this.useDefaultLoadingScreen) {
  29223. this._scene.getEngine().displayLoadingUI();
  29224. }
  29225. for (var index = 0; index < this._tasks.length; index++) {
  29226. var task = this._tasks[index];
  29227. this._runTask(task);
  29228. }
  29229. return this;
  29230. };
  29231. return AssetsManager;
  29232. })();
  29233. BABYLON.AssetsManager = AssetsManager;
  29234. })(BABYLON || (BABYLON = {}));
  29235. var BABYLON;
  29236. (function (BABYLON) {
  29237. var VRDeviceOrientationFreeCamera = (function (_super) {
  29238. __extends(VRDeviceOrientationFreeCamera, _super);
  29239. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29240. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29241. _super.call(this, name, position, scene);
  29242. this._alpha = 0;
  29243. this._beta = 0;
  29244. this._gamma = 0;
  29245. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29246. metrics.compensateDistorsion = compensateDistorsion;
  29247. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29248. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29249. }
  29250. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29251. this._alpha = +evt.alpha | 0;
  29252. this._beta = +evt.beta | 0;
  29253. this._gamma = +evt.gamma | 0;
  29254. if (this._gamma < 0) {
  29255. this._gamma = 90 + this._gamma;
  29256. }
  29257. else {
  29258. // Incline it in the correct angle.
  29259. this._gamma = 270 - this._gamma;
  29260. }
  29261. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29262. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29263. this.rotation.z = this._beta / 180.0 * Math.PI;
  29264. };
  29265. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29266. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29267. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29268. };
  29269. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29270. _super.prototype.detachControl.call(this, element);
  29271. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29272. };
  29273. return VRDeviceOrientationFreeCamera;
  29274. })(BABYLON.FreeCamera);
  29275. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29276. })(BABYLON || (BABYLON = {}));
  29277. var BABYLON;
  29278. (function (BABYLON) {
  29279. var WebVRFreeCamera = (function (_super) {
  29280. __extends(WebVRFreeCamera, _super);
  29281. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29282. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29283. _super.call(this, name, position, scene);
  29284. this._hmdDevice = null;
  29285. this._sensorDevice = null;
  29286. this._cacheState = null;
  29287. this._cacheQuaternion = new BABYLON.Quaternion();
  29288. this._cacheRotation = BABYLON.Vector3.Zero();
  29289. this._vrEnabled = false;
  29290. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29291. metrics.compensateDistorsion = compensateDistorsion;
  29292. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29293. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29294. }
  29295. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29296. var size = devices.length;
  29297. var i = 0;
  29298. // Reset devices.
  29299. this._sensorDevice = null;
  29300. this._hmdDevice = null;
  29301. // Search for a HmdDevice.
  29302. while (i < size && this._hmdDevice === null) {
  29303. if (devices[i] instanceof HMDVRDevice) {
  29304. this._hmdDevice = devices[i];
  29305. }
  29306. i++;
  29307. }
  29308. i = 0;
  29309. while (i < size && this._sensorDevice === null) {
  29310. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29311. this._sensorDevice = devices[i];
  29312. }
  29313. i++;
  29314. }
  29315. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29316. };
  29317. WebVRFreeCamera.prototype._checkInputs = function () {
  29318. if (this._vrEnabled) {
  29319. this._cacheState = this._sensorDevice.getState();
  29320. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29321. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29322. this.rotation.x = -this._cacheRotation.z;
  29323. this.rotation.y = -this._cacheRotation.y;
  29324. this.rotation.z = this._cacheRotation.x;
  29325. }
  29326. _super.prototype._checkInputs.call(this);
  29327. };
  29328. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29329. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29330. if (navigator.getVRDevices) {
  29331. navigator.getVRDevices().then(this._getWebVRDevices);
  29332. }
  29333. else if (navigator.mozGetVRDevices) {
  29334. navigator.mozGetVRDevices(this._getWebVRDevices);
  29335. }
  29336. };
  29337. WebVRFreeCamera.prototype.detachControl = function (element) {
  29338. _super.prototype.detachControl.call(this, element);
  29339. this._vrEnabled = false;
  29340. };
  29341. return WebVRFreeCamera;
  29342. })(BABYLON.FreeCamera);
  29343. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29344. })(BABYLON || (BABYLON = {}));
  29345. var BABYLON;
  29346. (function (BABYLON) {
  29347. // Standard optimizations
  29348. var SceneOptimization = (function () {
  29349. function SceneOptimization(priority) {
  29350. if (priority === void 0) { priority = 0; }
  29351. this.priority = priority;
  29352. this.apply = function (scene) {
  29353. return true; // Return true if everything that can be done was applied
  29354. };
  29355. }
  29356. return SceneOptimization;
  29357. })();
  29358. BABYLON.SceneOptimization = SceneOptimization;
  29359. var TextureOptimization = (function (_super) {
  29360. __extends(TextureOptimization, _super);
  29361. function TextureOptimization(priority, maximumSize) {
  29362. var _this = this;
  29363. if (priority === void 0) { priority = 0; }
  29364. if (maximumSize === void 0) { maximumSize = 1024; }
  29365. _super.call(this, priority);
  29366. this.priority = priority;
  29367. this.maximumSize = maximumSize;
  29368. this.apply = function (scene) {
  29369. var allDone = true;
  29370. for (var index = 0; index < scene.textures.length; index++) {
  29371. var texture = scene.textures[index];
  29372. if (!texture.canRescale) {
  29373. continue;
  29374. }
  29375. var currentSize = texture.getSize();
  29376. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29377. if (maxDimension > _this.maximumSize) {
  29378. texture.scale(0.5);
  29379. allDone = false;
  29380. }
  29381. }
  29382. return allDone;
  29383. };
  29384. }
  29385. return TextureOptimization;
  29386. })(SceneOptimization);
  29387. BABYLON.TextureOptimization = TextureOptimization;
  29388. var HardwareScalingOptimization = (function (_super) {
  29389. __extends(HardwareScalingOptimization, _super);
  29390. function HardwareScalingOptimization(priority, maximumScale) {
  29391. var _this = this;
  29392. if (priority === void 0) { priority = 0; }
  29393. if (maximumScale === void 0) { maximumScale = 2; }
  29394. _super.call(this, priority);
  29395. this.priority = priority;
  29396. this.maximumScale = maximumScale;
  29397. this._currentScale = 1;
  29398. this.apply = function (scene) {
  29399. _this._currentScale++;
  29400. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29401. return _this._currentScale >= _this.maximumScale;
  29402. };
  29403. }
  29404. return HardwareScalingOptimization;
  29405. })(SceneOptimization);
  29406. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29407. var ShadowsOptimization = (function (_super) {
  29408. __extends(ShadowsOptimization, _super);
  29409. function ShadowsOptimization() {
  29410. _super.apply(this, arguments);
  29411. this.apply = function (scene) {
  29412. scene.shadowsEnabled = false;
  29413. return true;
  29414. };
  29415. }
  29416. return ShadowsOptimization;
  29417. })(SceneOptimization);
  29418. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29419. var PostProcessesOptimization = (function (_super) {
  29420. __extends(PostProcessesOptimization, _super);
  29421. function PostProcessesOptimization() {
  29422. _super.apply(this, arguments);
  29423. this.apply = function (scene) {
  29424. scene.postProcessesEnabled = false;
  29425. return true;
  29426. };
  29427. }
  29428. return PostProcessesOptimization;
  29429. })(SceneOptimization);
  29430. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29431. var LensFlaresOptimization = (function (_super) {
  29432. __extends(LensFlaresOptimization, _super);
  29433. function LensFlaresOptimization() {
  29434. _super.apply(this, arguments);
  29435. this.apply = function (scene) {
  29436. scene.lensFlaresEnabled = false;
  29437. return true;
  29438. };
  29439. }
  29440. return LensFlaresOptimization;
  29441. })(SceneOptimization);
  29442. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29443. var ParticlesOptimization = (function (_super) {
  29444. __extends(ParticlesOptimization, _super);
  29445. function ParticlesOptimization() {
  29446. _super.apply(this, arguments);
  29447. this.apply = function (scene) {
  29448. scene.particlesEnabled = false;
  29449. return true;
  29450. };
  29451. }
  29452. return ParticlesOptimization;
  29453. })(SceneOptimization);
  29454. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29455. var RenderTargetsOptimization = (function (_super) {
  29456. __extends(RenderTargetsOptimization, _super);
  29457. function RenderTargetsOptimization() {
  29458. _super.apply(this, arguments);
  29459. this.apply = function (scene) {
  29460. scene.renderTargetsEnabled = false;
  29461. return true;
  29462. };
  29463. }
  29464. return RenderTargetsOptimization;
  29465. })(SceneOptimization);
  29466. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29467. var MergeMeshesOptimization = (function (_super) {
  29468. __extends(MergeMeshesOptimization, _super);
  29469. function MergeMeshesOptimization() {
  29470. var _this = this;
  29471. _super.apply(this, arguments);
  29472. this._canBeMerged = function (abstractMesh) {
  29473. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29474. return false;
  29475. }
  29476. var mesh = abstractMesh;
  29477. if (!mesh.isVisible || !mesh.isEnabled()) {
  29478. return false;
  29479. }
  29480. if (mesh.instances.length > 0) {
  29481. return false;
  29482. }
  29483. if (mesh.skeleton || mesh.hasLODLevels) {
  29484. return false;
  29485. }
  29486. return true;
  29487. };
  29488. this.apply = function (scene, updateSelectionTree) {
  29489. var globalPool = scene.meshes.slice(0);
  29490. var globalLength = globalPool.length;
  29491. for (var index = 0; index < globalLength; index++) {
  29492. var currentPool = new Array();
  29493. var current = globalPool[index];
  29494. // Checks
  29495. if (!_this._canBeMerged(current)) {
  29496. continue;
  29497. }
  29498. currentPool.push(current);
  29499. // Find compatible meshes
  29500. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29501. var otherMesh = globalPool[subIndex];
  29502. if (!_this._canBeMerged(otherMesh)) {
  29503. continue;
  29504. }
  29505. if (otherMesh.material !== current.material) {
  29506. continue;
  29507. }
  29508. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29509. continue;
  29510. }
  29511. currentPool.push(otherMesh);
  29512. globalLength--;
  29513. globalPool.splice(subIndex, 1);
  29514. subIndex--;
  29515. }
  29516. if (currentPool.length < 2) {
  29517. continue;
  29518. }
  29519. // Merge meshes
  29520. BABYLON.Mesh.MergeMeshes(currentPool);
  29521. }
  29522. if (updateSelectionTree != undefined) {
  29523. if (updateSelectionTree) {
  29524. scene.createOrUpdateSelectionOctree();
  29525. }
  29526. }
  29527. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29528. scene.createOrUpdateSelectionOctree();
  29529. }
  29530. return true;
  29531. };
  29532. }
  29533. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29534. get: function () {
  29535. return MergeMeshesOptimization._UpdateSelectionTree;
  29536. },
  29537. set: function (value) {
  29538. MergeMeshesOptimization._UpdateSelectionTree = value;
  29539. },
  29540. enumerable: true,
  29541. configurable: true
  29542. });
  29543. MergeMeshesOptimization._UpdateSelectionTree = false;
  29544. return MergeMeshesOptimization;
  29545. })(SceneOptimization);
  29546. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29547. // Options
  29548. var SceneOptimizerOptions = (function () {
  29549. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29550. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29551. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29552. this.targetFrameRate = targetFrameRate;
  29553. this.trackerDuration = trackerDuration;
  29554. this.optimizations = new Array();
  29555. }
  29556. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29557. var result = new SceneOptimizerOptions(targetFrameRate);
  29558. var priority = 0;
  29559. result.optimizations.push(new MergeMeshesOptimization(priority));
  29560. result.optimizations.push(new ShadowsOptimization(priority));
  29561. result.optimizations.push(new LensFlaresOptimization(priority));
  29562. // Next priority
  29563. priority++;
  29564. result.optimizations.push(new PostProcessesOptimization(priority));
  29565. result.optimizations.push(new ParticlesOptimization(priority));
  29566. // Next priority
  29567. priority++;
  29568. result.optimizations.push(new TextureOptimization(priority, 1024));
  29569. return result;
  29570. };
  29571. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29572. var result = new SceneOptimizerOptions(targetFrameRate);
  29573. var priority = 0;
  29574. result.optimizations.push(new MergeMeshesOptimization(priority));
  29575. result.optimizations.push(new ShadowsOptimization(priority));
  29576. result.optimizations.push(new LensFlaresOptimization(priority));
  29577. // Next priority
  29578. priority++;
  29579. result.optimizations.push(new PostProcessesOptimization(priority));
  29580. result.optimizations.push(new ParticlesOptimization(priority));
  29581. // Next priority
  29582. priority++;
  29583. result.optimizations.push(new TextureOptimization(priority, 512));
  29584. // Next priority
  29585. priority++;
  29586. result.optimizations.push(new RenderTargetsOptimization(priority));
  29587. // Next priority
  29588. priority++;
  29589. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29590. return result;
  29591. };
  29592. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29593. var result = new SceneOptimizerOptions(targetFrameRate);
  29594. var priority = 0;
  29595. result.optimizations.push(new MergeMeshesOptimization(priority));
  29596. result.optimizations.push(new ShadowsOptimization(priority));
  29597. result.optimizations.push(new LensFlaresOptimization(priority));
  29598. // Next priority
  29599. priority++;
  29600. result.optimizations.push(new PostProcessesOptimization(priority));
  29601. result.optimizations.push(new ParticlesOptimization(priority));
  29602. // Next priority
  29603. priority++;
  29604. result.optimizations.push(new TextureOptimization(priority, 256));
  29605. // Next priority
  29606. priority++;
  29607. result.optimizations.push(new RenderTargetsOptimization(priority));
  29608. // Next priority
  29609. priority++;
  29610. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29611. return result;
  29612. };
  29613. return SceneOptimizerOptions;
  29614. })();
  29615. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29616. // Scene optimizer tool
  29617. var SceneOptimizer = (function () {
  29618. function SceneOptimizer() {
  29619. }
  29620. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29621. // TODO: add an epsilon
  29622. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29623. if (onSuccess) {
  29624. onSuccess();
  29625. }
  29626. return;
  29627. }
  29628. // Apply current level of optimizations
  29629. var allDone = true;
  29630. var noOptimizationApplied = true;
  29631. for (var index = 0; index < options.optimizations.length; index++) {
  29632. var optimization = options.optimizations[index];
  29633. if (optimization.priority === currentPriorityLevel) {
  29634. noOptimizationApplied = false;
  29635. allDone = allDone && optimization.apply(scene);
  29636. }
  29637. }
  29638. // If no optimization was applied, this is a failure :(
  29639. if (noOptimizationApplied) {
  29640. if (onFailure) {
  29641. onFailure();
  29642. }
  29643. return;
  29644. }
  29645. // If all optimizations were done, move to next level
  29646. if (allDone) {
  29647. currentPriorityLevel++;
  29648. }
  29649. // Let's the system running for a specific amount of time before checking FPS
  29650. scene.executeWhenReady(function () {
  29651. setTimeout(function () {
  29652. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29653. }, options.trackerDuration);
  29654. });
  29655. };
  29656. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29657. if (!options) {
  29658. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29659. }
  29660. // Let's the system running for a specific amount of time before checking FPS
  29661. scene.executeWhenReady(function () {
  29662. setTimeout(function () {
  29663. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29664. }, options.trackerDuration);
  29665. });
  29666. };
  29667. return SceneOptimizer;
  29668. })();
  29669. BABYLON.SceneOptimizer = SceneOptimizer;
  29670. })(BABYLON || (BABYLON = {}));
  29671. var BABYLON;
  29672. (function (BABYLON) {
  29673. var Internals;
  29674. (function (Internals) {
  29675. var MeshLODLevel = (function () {
  29676. function MeshLODLevel(distance, mesh) {
  29677. this.distance = distance;
  29678. this.mesh = mesh;
  29679. }
  29680. return MeshLODLevel;
  29681. })();
  29682. Internals.MeshLODLevel = MeshLODLevel;
  29683. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29684. })(BABYLON || (BABYLON = {}));
  29685. var BABYLON;
  29686. (function (BABYLON) {
  29687. var AudioEngine = (function () {
  29688. function AudioEngine() {
  29689. this._audioContext = null;
  29690. this._audioContextInitialized = false;
  29691. this.canUseWebAudio = false;
  29692. this.WarnedWebAudioUnsupported = false;
  29693. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29694. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29695. this.canUseWebAudio = true;
  29696. }
  29697. }
  29698. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29699. get: function () {
  29700. if (!this._audioContextInitialized) {
  29701. this._initializeAudioContext();
  29702. }
  29703. return this._audioContext;
  29704. },
  29705. enumerable: true,
  29706. configurable: true
  29707. });
  29708. AudioEngine.prototype._initializeAudioContext = function () {
  29709. try {
  29710. if (this.canUseWebAudio) {
  29711. this._audioContext = new AudioContext();
  29712. // create a global volume gain node
  29713. this.masterGain = this._audioContext.createGain();
  29714. this.masterGain.gain.value = 1;
  29715. this.masterGain.connect(this._audioContext.destination);
  29716. this._audioContextInitialized = true;
  29717. }
  29718. }
  29719. catch (e) {
  29720. this.canUseWebAudio = false;
  29721. BABYLON.Tools.Error("Web Audio: " + e.message);
  29722. }
  29723. };
  29724. AudioEngine.prototype.dispose = function () {
  29725. if (this.canUseWebAudio && this._audioContextInitialized) {
  29726. if (this._connectedAnalyser) {
  29727. this._connectedAnalyser.stopDebugCanvas();
  29728. this._connectedAnalyser.dispose();
  29729. this.masterGain.disconnect();
  29730. this.masterGain.connect(this._audioContext.destination);
  29731. this._connectedAnalyser = null;
  29732. }
  29733. this.masterGain.gain.value = 1;
  29734. }
  29735. this.WarnedWebAudioUnsupported = false;
  29736. };
  29737. AudioEngine.prototype.getGlobalVolume = function () {
  29738. if (this.canUseWebAudio && this._audioContextInitialized) {
  29739. return this.masterGain.gain.value;
  29740. }
  29741. else {
  29742. return -1;
  29743. }
  29744. };
  29745. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29746. if (this.canUseWebAudio && this._audioContextInitialized) {
  29747. this.masterGain.gain.value = newVolume;
  29748. }
  29749. };
  29750. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29751. if (this._connectedAnalyser) {
  29752. this._connectedAnalyser.stopDebugCanvas();
  29753. }
  29754. if (this.canUseWebAudio && this._audioContextInitialized) {
  29755. this._connectedAnalyser = analyser;
  29756. this.masterGain.disconnect();
  29757. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29758. }
  29759. };
  29760. return AudioEngine;
  29761. })();
  29762. BABYLON.AudioEngine = AudioEngine;
  29763. })(BABYLON || (BABYLON = {}));
  29764. var BABYLON;
  29765. (function (BABYLON) {
  29766. var Sound = (function () {
  29767. /**
  29768. * Create a sound and attach it to a scene
  29769. * @param name Name of your sound
  29770. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29771. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29772. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29773. */
  29774. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29775. var _this = this;
  29776. this.autoplay = false;
  29777. this.loop = false;
  29778. this.useCustomAttenuation = false;
  29779. this.spatialSound = false;
  29780. this.refDistance = 1;
  29781. this.rolloffFactor = 1;
  29782. this.maxDistance = 100;
  29783. this.distanceModel = "linear";
  29784. this._panningModel = "equalpower";
  29785. this._playbackRate = 1;
  29786. this._startTime = 0;
  29787. this._startOffset = 0;
  29788. this._position = BABYLON.Vector3.Zero();
  29789. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29790. this._volume = 1;
  29791. this._isLoaded = false;
  29792. this._isReadyToPlay = false;
  29793. this.isPlaying = false;
  29794. this.isPaused = false;
  29795. this._isDirectional = false;
  29796. // Used if you'd like to create a directional sound.
  29797. // If not set, the sound will be omnidirectional
  29798. this._coneInnerAngle = 360;
  29799. this._coneOuterAngle = 360;
  29800. this._coneOuterGain = 0;
  29801. this.name = name;
  29802. this._scene = scene;
  29803. this._readyToPlayCallback = readyToPlayCallback;
  29804. // Default custom attenuation function is a linear attenuation
  29805. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29806. if (currentDistance < maxDistance) {
  29807. return currentVolume * (1 - currentDistance / maxDistance);
  29808. }
  29809. else {
  29810. return 0;
  29811. }
  29812. };
  29813. if (options) {
  29814. this.autoplay = options.autoplay || false;
  29815. this.loop = options.loop || false;
  29816. // if volume === 0, we need another way to check this option
  29817. if (options.volume !== undefined) {
  29818. this._volume = options.volume;
  29819. }
  29820. this.spatialSound = options.spatialSound || false;
  29821. this.maxDistance = options.maxDistance || 100;
  29822. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29823. this.rolloffFactor = options.rolloffFactor || 1;
  29824. this.refDistance = options.refDistance || 1;
  29825. this.distanceModel = options.distanceModel || "linear";
  29826. this._playbackRate = options.playbackRate || 1;
  29827. }
  29828. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29829. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29830. this._soundGain.gain.value = this._volume;
  29831. this._inputAudioNode = this._soundGain;
  29832. this._ouputAudioNode = this._soundGain;
  29833. if (this.spatialSound) {
  29834. this._createSpatialParameters();
  29835. }
  29836. this._scene.mainSoundTrack.AddSound(this);
  29837. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29838. if (urlOrArrayBuffer) {
  29839. // If it's an URL
  29840. if (typeof (urlOrArrayBuffer) === "string") {
  29841. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29842. }
  29843. else {
  29844. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29845. this._soundLoaded(urlOrArrayBuffer);
  29846. }
  29847. else {
  29848. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29849. }
  29850. }
  29851. }
  29852. }
  29853. else {
  29854. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29855. this._scene.mainSoundTrack.AddSound(this);
  29856. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29857. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29858. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29859. }
  29860. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29861. if (this._readyToPlayCallback) {
  29862. window.setTimeout(function () {
  29863. _this._readyToPlayCallback();
  29864. }, 1000);
  29865. }
  29866. }
  29867. }
  29868. Sound.prototype.dispose = function () {
  29869. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29870. if (this.isPlaying) {
  29871. this.stop();
  29872. }
  29873. this._isReadyToPlay = false;
  29874. if (this.soundTrackId === -1) {
  29875. this._scene.mainSoundTrack.RemoveSound(this);
  29876. }
  29877. else {
  29878. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29879. }
  29880. if (this._soundGain) {
  29881. this._soundGain.disconnect();
  29882. this._soundGain = null;
  29883. }
  29884. if (this._soundPanner) {
  29885. this._soundPanner.disconnect();
  29886. this._soundPanner = null;
  29887. }
  29888. if (this._soundSource) {
  29889. this._soundSource.disconnect();
  29890. this._soundSource = null;
  29891. }
  29892. this._audioBuffer = null;
  29893. if (this._connectedMesh) {
  29894. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29895. this._connectedMesh = null;
  29896. }
  29897. }
  29898. };
  29899. Sound.prototype._soundLoaded = function (audioData) {
  29900. var _this = this;
  29901. this._isLoaded = true;
  29902. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29903. _this._audioBuffer = buffer;
  29904. _this._isReadyToPlay = true;
  29905. if (_this.autoplay) {
  29906. _this.play();
  29907. }
  29908. if (_this._readyToPlayCallback) {
  29909. _this._readyToPlayCallback();
  29910. }
  29911. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  29912. };
  29913. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29914. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29915. this._audioBuffer = audioBuffer;
  29916. this._isReadyToPlay = true;
  29917. }
  29918. };
  29919. Sound.prototype.updateOptions = function (options) {
  29920. if (options) {
  29921. this.loop = options.loop || this.loop;
  29922. this.maxDistance = options.maxDistance || this.maxDistance;
  29923. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29924. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29925. this.refDistance = options.refDistance || this.refDistance;
  29926. this.distanceModel = options.distanceModel || this.distanceModel;
  29927. this._playbackRate = options.playbackRate || this._playbackRate;
  29928. this._updateSpatialParameters();
  29929. if (this.isPlaying) {
  29930. this._soundSource.playbackRate.value = this._playbackRate;
  29931. }
  29932. }
  29933. };
  29934. Sound.prototype._createSpatialParameters = function () {
  29935. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29936. if (this._scene.headphone) {
  29937. this._panningModel = "HRTF";
  29938. }
  29939. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29940. this._updateSpatialParameters();
  29941. this._soundPanner.connect(this._ouputAudioNode);
  29942. this._inputAudioNode = this._soundPanner;
  29943. }
  29944. };
  29945. Sound.prototype._updateSpatialParameters = function () {
  29946. if (this.spatialSound) {
  29947. if (this.useCustomAttenuation) {
  29948. // Tricks to disable in a way embedded Web Audio attenuation
  29949. this._soundPanner.distanceModel = "linear";
  29950. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29951. this._soundPanner.refDistance = 1;
  29952. this._soundPanner.rolloffFactor = 1;
  29953. this._soundPanner.panningModel = this._panningModel;
  29954. }
  29955. else {
  29956. this._soundPanner.distanceModel = this.distanceModel;
  29957. this._soundPanner.maxDistance = this.maxDistance;
  29958. this._soundPanner.refDistance = this.refDistance;
  29959. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29960. this._soundPanner.panningModel = this._panningModel;
  29961. }
  29962. }
  29963. };
  29964. Sound.prototype.switchPanningModelToHRTF = function () {
  29965. this._panningModel = "HRTF";
  29966. this._switchPanningModel();
  29967. };
  29968. Sound.prototype.switchPanningModelToEqualPower = function () {
  29969. this._panningModel = "equalpower";
  29970. this._switchPanningModel();
  29971. };
  29972. Sound.prototype._switchPanningModel = function () {
  29973. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29974. this._soundPanner.panningModel = this._panningModel;
  29975. }
  29976. };
  29977. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29978. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29979. this._ouputAudioNode.disconnect();
  29980. this._ouputAudioNode.connect(soundTrackAudioNode);
  29981. }
  29982. };
  29983. /**
  29984. * Transform this sound into a directional source
  29985. * @param coneInnerAngle Size of the inner cone in degree
  29986. * @param coneOuterAngle Size of the outer cone in degree
  29987. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29988. */
  29989. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29990. if (coneOuterAngle < coneInnerAngle) {
  29991. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29992. return;
  29993. }
  29994. this._coneInnerAngle = coneInnerAngle;
  29995. this._coneOuterAngle = coneOuterAngle;
  29996. this._coneOuterGain = coneOuterGain;
  29997. this._isDirectional = true;
  29998. if (this.isPlaying && this.loop) {
  29999. this.stop();
  30000. this.play();
  30001. }
  30002. };
  30003. Sound.prototype.setPosition = function (newPosition) {
  30004. this._position = newPosition;
  30005. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30006. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30007. }
  30008. };
  30009. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30010. this._localDirection = newLocalDirection;
  30011. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30012. this._updateDirection();
  30013. }
  30014. };
  30015. Sound.prototype._updateDirection = function () {
  30016. var mat = this._connectedMesh.getWorldMatrix();
  30017. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30018. direction.normalize();
  30019. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30020. };
  30021. Sound.prototype.updateDistanceFromListener = function () {
  30022. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30023. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30024. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30025. }
  30026. };
  30027. Sound.prototype.setAttenuationFunction = function (callback) {
  30028. this._customAttenuationFunction = callback;
  30029. };
  30030. /**
  30031. * Play the sound
  30032. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30033. */
  30034. Sound.prototype.play = function (time) {
  30035. var _this = this;
  30036. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30037. try {
  30038. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30039. if (!this._soundSource) {
  30040. if (this.spatialSound) {
  30041. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30042. if (this._isDirectional) {
  30043. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30044. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30045. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30046. if (this._connectedMesh) {
  30047. this._updateDirection();
  30048. }
  30049. else {
  30050. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30051. }
  30052. }
  30053. }
  30054. }
  30055. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30056. this._soundSource.buffer = this._audioBuffer;
  30057. this._soundSource.connect(this._inputAudioNode);
  30058. this._soundSource.loop = this.loop;
  30059. this._soundSource.playbackRate.value = this._playbackRate;
  30060. this._startTime = startTime;
  30061. this._soundSource.onended = function () { _this._onended(); };
  30062. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30063. this.isPlaying = true;
  30064. this.isPaused = false;
  30065. }
  30066. catch (ex) {
  30067. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30068. }
  30069. }
  30070. };
  30071. Sound.prototype._onended = function () {
  30072. this.isPlaying = false;
  30073. if (this.onended) {
  30074. this.onended();
  30075. }
  30076. };
  30077. /**
  30078. * Stop the sound
  30079. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30080. */
  30081. Sound.prototype.stop = function (time) {
  30082. if (this.isPlaying) {
  30083. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30084. this._soundSource.stop(stopTime);
  30085. this.isPlaying = false;
  30086. }
  30087. };
  30088. Sound.prototype.pause = function () {
  30089. if (this.isPlaying) {
  30090. this.stop(0);
  30091. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30092. this.isPaused = true;
  30093. }
  30094. };
  30095. Sound.prototype.setVolume = function (newVolume, time) {
  30096. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30097. if (time) {
  30098. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30099. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30100. }
  30101. else {
  30102. this._soundGain.gain.value = newVolume;
  30103. }
  30104. }
  30105. this._volume = newVolume;
  30106. };
  30107. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30108. this._playbackRate = newPlaybackRate;
  30109. if (this.isPlaying) {
  30110. this._soundSource.playbackRate.value = this._playbackRate;
  30111. }
  30112. };
  30113. Sound.prototype.getVolume = function () {
  30114. return this._volume;
  30115. };
  30116. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30117. var _this = this;
  30118. this._connectedMesh = meshToConnectTo;
  30119. if (!this.spatialSound) {
  30120. this.spatialSound = true;
  30121. this._createSpatialParameters();
  30122. if (this.isPlaying && this.loop) {
  30123. this.stop();
  30124. this.play();
  30125. }
  30126. }
  30127. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30128. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30129. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30130. };
  30131. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30132. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30133. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30134. this._updateDirection();
  30135. }
  30136. };
  30137. return Sound;
  30138. })();
  30139. BABYLON.Sound = Sound;
  30140. })(BABYLON || (BABYLON = {}));
  30141. var BABYLON;
  30142. (function (BABYLON) {
  30143. var SoundTrack = (function () {
  30144. function SoundTrack(scene, options) {
  30145. this.id = -1;
  30146. this._isMainTrack = false;
  30147. this._scene = scene;
  30148. this._audioEngine = BABYLON.Engine.audioEngine;
  30149. this.soundCollection = new Array();
  30150. if (this._audioEngine.canUseWebAudio) {
  30151. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30152. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30153. if (options) {
  30154. if (options.volume) {
  30155. this._outputAudioNode.gain.value = options.volume;
  30156. }
  30157. if (options.mainTrack) {
  30158. this._isMainTrack = options.mainTrack;
  30159. }
  30160. }
  30161. }
  30162. if (!this._isMainTrack) {
  30163. this._scene.soundTracks.push(this);
  30164. this.id = this._scene.soundTracks.length - 1;
  30165. }
  30166. }
  30167. SoundTrack.prototype.dispose = function () {
  30168. if (this._audioEngine.canUseWebAudio) {
  30169. if (this._connectedAnalyser) {
  30170. this._connectedAnalyser.stopDebugCanvas();
  30171. }
  30172. while (this.soundCollection.length) {
  30173. this.soundCollection[0].dispose();
  30174. }
  30175. if (this._outputAudioNode) {
  30176. this._outputAudioNode.disconnect();
  30177. }
  30178. this._outputAudioNode = null;
  30179. }
  30180. };
  30181. SoundTrack.prototype.AddSound = function (sound) {
  30182. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30183. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30184. }
  30185. if (sound.soundTrackId) {
  30186. if (sound.soundTrackId === -1) {
  30187. this._scene.mainSoundTrack.RemoveSound(sound);
  30188. }
  30189. else {
  30190. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30191. }
  30192. }
  30193. this.soundCollection.push(sound);
  30194. sound.soundTrackId = this.id;
  30195. };
  30196. SoundTrack.prototype.RemoveSound = function (sound) {
  30197. var index = this.soundCollection.indexOf(sound);
  30198. if (index !== -1) {
  30199. this.soundCollection.splice(index, 1);
  30200. }
  30201. };
  30202. SoundTrack.prototype.setVolume = function (newVolume) {
  30203. if (this._audioEngine.canUseWebAudio) {
  30204. this._outputAudioNode.gain.value = newVolume;
  30205. }
  30206. };
  30207. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30208. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30209. for (var i = 0; i < this.soundCollection.length; i++) {
  30210. this.soundCollection[i].switchPanningModelToHRTF();
  30211. }
  30212. }
  30213. };
  30214. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30215. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30216. for (var i = 0; i < this.soundCollection.length; i++) {
  30217. this.soundCollection[i].switchPanningModelToEqualPower();
  30218. }
  30219. }
  30220. };
  30221. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30222. if (this._connectedAnalyser) {
  30223. this._connectedAnalyser.stopDebugCanvas();
  30224. }
  30225. this._connectedAnalyser = analyser;
  30226. if (this._audioEngine.canUseWebAudio) {
  30227. this._outputAudioNode.disconnect();
  30228. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30229. }
  30230. };
  30231. return SoundTrack;
  30232. })();
  30233. BABYLON.SoundTrack = SoundTrack;
  30234. })(BABYLON || (BABYLON = {}));
  30235. var BABYLON;
  30236. (function (BABYLON) {
  30237. var DebugLayer = (function () {
  30238. function DebugLayer(scene) {
  30239. var _this = this;
  30240. this._transformationMatrix = BABYLON.Matrix.Identity();
  30241. this._enabled = false;
  30242. this._labelsEnabled = false;
  30243. this._displayStatistics = true;
  30244. this._displayTree = false;
  30245. this._displayLogs = false;
  30246. this._identityMatrix = BABYLON.Matrix.Identity();
  30247. this.axisRatio = 0.02;
  30248. this.accentColor = "orange";
  30249. this._scene = scene;
  30250. this._syncPositions = function () {
  30251. var engine = _this._scene.getEngine();
  30252. var canvasRect = engine.getRenderingCanvasClientRect();
  30253. if (_this._showUI) {
  30254. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30255. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30256. _this._statsDiv.style.width = "400px";
  30257. _this._statsDiv.style.height = "auto";
  30258. _this._statsSubsetDiv.style.maxHeight = "240px";
  30259. _this._optionsDiv.style.left = "0px";
  30260. _this._optionsDiv.style.top = "10px";
  30261. _this._optionsDiv.style.width = "200px";
  30262. _this._optionsDiv.style.height = "auto";
  30263. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30264. _this._logDiv.style.left = "0px";
  30265. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30266. _this._logDiv.style.width = "600px";
  30267. _this._logDiv.style.height = "160px";
  30268. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30269. _this._treeDiv.style.top = "10px";
  30270. _this._treeDiv.style.width = "300px";
  30271. _this._treeDiv.style.height = "auto";
  30272. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30273. }
  30274. _this._globalDiv.style.left = canvasRect.left + "px";
  30275. _this._globalDiv.style.top = canvasRect.top + "px";
  30276. _this._drawingCanvas.style.left = "0px";
  30277. _this._drawingCanvas.style.top = "0px";
  30278. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30279. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30280. var devicePixelRatio = window.devicePixelRatio || 1;
  30281. var context = _this._drawingContext;
  30282. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30283. context.mozBackingStorePixelRatio ||
  30284. context.msBackingStorePixelRatio ||
  30285. context.oBackingStorePixelRatio ||
  30286. context.backingStorePixelRatio || 1;
  30287. _this._ratio = devicePixelRatio / backingStoreRatio;
  30288. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30289. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30290. };
  30291. this._onCanvasClick = function (evt) {
  30292. _this._clickPosition = {
  30293. x: evt.clientX * _this._ratio,
  30294. y: evt.clientY * _this._ratio
  30295. };
  30296. };
  30297. this._syncUI = function () {
  30298. if (_this._showUI) {
  30299. if (_this._displayStatistics) {
  30300. _this._displayStats();
  30301. _this._statsDiv.style.display = "";
  30302. }
  30303. else {
  30304. _this._statsDiv.style.display = "none";
  30305. }
  30306. if (_this._displayLogs) {
  30307. _this._logDiv.style.display = "";
  30308. }
  30309. else {
  30310. _this._logDiv.style.display = "none";
  30311. }
  30312. if (_this._displayTree) {
  30313. _this._treeDiv.style.display = "";
  30314. if (_this._needToRefreshMeshesTree) {
  30315. _this._needToRefreshMeshesTree = false;
  30316. _this._refreshMeshesTreeContent();
  30317. }
  30318. }
  30319. else {
  30320. _this._treeDiv.style.display = "none";
  30321. }
  30322. }
  30323. };
  30324. this._syncData = function () {
  30325. if (_this._labelsEnabled || !_this._showUI) {
  30326. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30327. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30328. var engine = _this._scene.getEngine();
  30329. var viewport = _this._camera.viewport;
  30330. var globalViewport = viewport.toGlobal(engine);
  30331. // Meshes
  30332. var meshes = _this._camera.getActiveMeshes();
  30333. for (var index = 0; index < meshes.length; index++) {
  30334. var mesh = meshes.data[index];
  30335. var position = mesh.getBoundingInfo().boundingSphere.center;
  30336. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30337. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30338. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30339. }
  30340. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30341. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30342. }
  30343. }
  30344. // Cameras
  30345. var cameras = _this._scene.cameras;
  30346. for (index = 0; index < cameras.length; index++) {
  30347. var camera = cameras[index];
  30348. if (camera === _this._camera) {
  30349. continue;
  30350. }
  30351. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30352. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30353. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30354. _this._camera.detachControl(engine.getRenderingCanvas());
  30355. _this._camera = camera;
  30356. _this._camera.attachControl(engine.getRenderingCanvas());
  30357. }, function () { return "purple"; });
  30358. }
  30359. }
  30360. // Lights
  30361. var lights = _this._scene.lights;
  30362. for (index = 0; index < lights.length; index++) {
  30363. var light = lights[index];
  30364. if (light.position) {
  30365. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30366. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30367. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30368. light.setEnabled(!light.isEnabled());
  30369. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30370. }
  30371. }
  30372. }
  30373. }
  30374. _this._clickPosition = undefined;
  30375. };
  30376. }
  30377. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30378. while (this._treeSubsetDiv.hasChildNodes()) {
  30379. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30380. }
  30381. // Add meshes
  30382. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30383. sortedArray.sort(function (a, b) {
  30384. if (a.name === b.name) {
  30385. return 0;
  30386. }
  30387. return (a.name > b.name) ? 1 : -1;
  30388. });
  30389. for (var index = 0; index < sortedArray.length; index++) {
  30390. var mesh = sortedArray[index];
  30391. if (!mesh.isEnabled()) {
  30392. continue;
  30393. }
  30394. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30395. m.isVisible = element.checked;
  30396. }, mesh);
  30397. }
  30398. };
  30399. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30400. this._drawingContext.beginPath();
  30401. this._drawingContext.moveTo(zero.x, zero.y);
  30402. this._drawingContext.lineTo(unit.x, unit.y);
  30403. this._drawingContext.strokeStyle = color;
  30404. this._drawingContext.lineWidth = 4;
  30405. this._drawingContext.stroke();
  30406. this._drawingContext.font = "normal 14px Segoe UI";
  30407. this._drawingContext.fillStyle = color;
  30408. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30409. };
  30410. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30411. var position = mesh.getBoundingInfo().boundingSphere.center;
  30412. var worldMatrix = mesh.getWorldMatrix();
  30413. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30414. var unit = (unprojectedVector.subtract(position)).length();
  30415. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30416. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30417. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30418. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30419. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30420. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30421. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30422. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30423. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30424. };
  30425. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30426. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30427. this._drawingContext.font = "normal 12px Segoe UI";
  30428. var textMetrics = this._drawingContext.measureText(text);
  30429. var centerX = projectedPosition.x - textMetrics.width / 2;
  30430. var centerY = projectedPosition.y;
  30431. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30432. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30433. onClick();
  30434. }
  30435. this._drawingContext.beginPath();
  30436. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30437. this._drawingContext.fillStyle = getFillStyle();
  30438. this._drawingContext.globalAlpha = 0.5;
  30439. this._drawingContext.fill();
  30440. this._drawingContext.globalAlpha = 1.0;
  30441. this._drawingContext.strokeStyle = '#FFFFFF';
  30442. this._drawingContext.lineWidth = 1;
  30443. this._drawingContext.stroke();
  30444. this._drawingContext.fillStyle = "#FFFFFF";
  30445. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30446. this._drawingContext.beginPath();
  30447. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30448. this._drawingContext.fill();
  30449. }
  30450. };
  30451. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30452. if (!this._clickPosition) {
  30453. return false;
  30454. }
  30455. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30456. return false;
  30457. }
  30458. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30459. return false;
  30460. }
  30461. return true;
  30462. };
  30463. DebugLayer.prototype.isVisible = function () {
  30464. return this._enabled;
  30465. };
  30466. DebugLayer.prototype.hide = function () {
  30467. if (!this._enabled) {
  30468. return;
  30469. }
  30470. this._enabled = false;
  30471. var engine = this._scene.getEngine();
  30472. this._scene.unregisterBeforeRender(this._syncData);
  30473. this._scene.unregisterAfterRender(this._syncUI);
  30474. document.body.removeChild(this._globalDiv);
  30475. window.removeEventListener("resize", this._syncPositions);
  30476. this._scene.forceShowBoundingBoxes = false;
  30477. this._scene.forceWireframe = false;
  30478. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30479. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30480. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30481. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30482. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30483. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30484. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30485. this._scene.shadowsEnabled = true;
  30486. this._scene.particlesEnabled = true;
  30487. this._scene.postProcessesEnabled = true;
  30488. this._scene.collisionsEnabled = true;
  30489. this._scene.lightsEnabled = true;
  30490. this._scene.texturesEnabled = true;
  30491. this._scene.lensFlaresEnabled = true;
  30492. this._scene.proceduralTexturesEnabled = true;
  30493. this._scene.renderTargetsEnabled = true;
  30494. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30495. };
  30496. DebugLayer.prototype.show = function (showUI, camera) {
  30497. if (showUI === void 0) { showUI = true; }
  30498. if (camera === void 0) { camera = null; }
  30499. if (this._enabled) {
  30500. return;
  30501. }
  30502. this._enabled = true;
  30503. if (camera) {
  30504. this._camera = camera;
  30505. }
  30506. else {
  30507. this._camera = this._scene.activeCamera;
  30508. }
  30509. this._showUI = showUI;
  30510. var engine = this._scene.getEngine();
  30511. this._globalDiv = document.createElement("div");
  30512. document.body.appendChild(this._globalDiv);
  30513. this._generateDOMelements();
  30514. window.addEventListener("resize", this._syncPositions);
  30515. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30516. this._syncPositions();
  30517. this._scene.registerBeforeRender(this._syncData);
  30518. this._scene.registerAfterRender(this._syncUI);
  30519. };
  30520. DebugLayer.prototype._clearLabels = function () {
  30521. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30522. for (var index = 0; index < this._scene.meshes.length; index++) {
  30523. var mesh = this._scene.meshes[index];
  30524. mesh.renderOverlay = false;
  30525. }
  30526. };
  30527. DebugLayer.prototype._generateheader = function (root, text) {
  30528. var header = document.createElement("div");
  30529. header.innerHTML = text + "&nbsp;";
  30530. header.style.textAlign = "right";
  30531. header.style.width = "100%";
  30532. header.style.color = "white";
  30533. header.style.backgroundColor = "Black";
  30534. header.style.padding = "5px 5px 4px 0px";
  30535. header.style.marginLeft = "-5px";
  30536. header.style.fontWeight = "bold";
  30537. root.appendChild(header);
  30538. };
  30539. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30540. var label = document.createElement("label");
  30541. label.innerHTML = title;
  30542. label.style.color = color;
  30543. root.appendChild(label);
  30544. root.appendChild(document.createElement("br"));
  30545. };
  30546. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30547. if (tag === void 0) { tag = null; }
  30548. var label = document.createElement("label");
  30549. var boundingBoxesCheckbox = document.createElement("input");
  30550. boundingBoxesCheckbox.type = "checkbox";
  30551. boundingBoxesCheckbox.checked = initialState;
  30552. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30553. task(evt.target, tag);
  30554. });
  30555. label.appendChild(boundingBoxesCheckbox);
  30556. var container = document.createElement("span");
  30557. var leftPart = document.createElement("span");
  30558. var rightPart = document.createElement("span");
  30559. rightPart.style.cssFloat = "right";
  30560. leftPart.innerHTML = leftTitle;
  30561. rightPart.innerHTML = rightTitle;
  30562. rightPart.style.fontSize = "12px";
  30563. rightPart.style.maxWidth = "200px";
  30564. container.appendChild(leftPart);
  30565. container.appendChild(rightPart);
  30566. label.appendChild(container);
  30567. root.appendChild(label);
  30568. root.appendChild(document.createElement("br"));
  30569. };
  30570. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30571. if (tag === void 0) { tag = null; }
  30572. var label = document.createElement("label");
  30573. var checkBox = document.createElement("input");
  30574. checkBox.type = "checkbox";
  30575. checkBox.checked = initialState;
  30576. checkBox.addEventListener("change", function (evt) {
  30577. task(evt.target, tag);
  30578. });
  30579. label.appendChild(checkBox);
  30580. label.appendChild(document.createTextNode(title));
  30581. root.appendChild(label);
  30582. root.appendChild(document.createElement("br"));
  30583. };
  30584. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30585. if (tag === void 0) { tag = null; }
  30586. var button = document.createElement("button");
  30587. button.innerHTML = title;
  30588. button.style.height = "24px";
  30589. button.style.color = "#444444";
  30590. button.style.border = "1px solid white";
  30591. button.className = "debugLayerButton";
  30592. button.addEventListener("click", function (evt) {
  30593. task(evt.target, tag);
  30594. });
  30595. root.appendChild(button);
  30596. root.appendChild(document.createElement("br"));
  30597. };
  30598. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30599. if (tag === void 0) { tag = null; }
  30600. var label = document.createElement("label");
  30601. var boundingBoxesRadio = document.createElement("input");
  30602. boundingBoxesRadio.type = "radio";
  30603. boundingBoxesRadio.name = name;
  30604. boundingBoxesRadio.checked = initialState;
  30605. boundingBoxesRadio.addEventListener("change", function (evt) {
  30606. task(evt.target, tag);
  30607. });
  30608. label.appendChild(boundingBoxesRadio);
  30609. label.appendChild(document.createTextNode(title));
  30610. root.appendChild(label);
  30611. root.appendChild(document.createElement("br"));
  30612. };
  30613. DebugLayer.prototype._generateDOMelements = function () {
  30614. var _this = this;
  30615. this._globalDiv.id = "DebugLayer";
  30616. this._globalDiv.style.position = "absolute";
  30617. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30618. this._globalDiv.style.fontSize = "14px";
  30619. this._globalDiv.style.color = "white";
  30620. // Drawing canvas
  30621. this._drawingCanvas = document.createElement("canvas");
  30622. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30623. this._drawingCanvas.style.position = "absolute";
  30624. this._drawingCanvas.style.pointerEvents = "none";
  30625. this._drawingContext = this._drawingCanvas.getContext("2d");
  30626. this._globalDiv.appendChild(this._drawingCanvas);
  30627. if (this._showUI) {
  30628. var background = "rgba(128, 128, 128, 0.4)";
  30629. var border = "rgb(180, 180, 180) solid 1px";
  30630. // Stats
  30631. this._statsDiv = document.createElement("div");
  30632. this._statsDiv.id = "DebugLayerStats";
  30633. this._statsDiv.style.border = border;
  30634. this._statsDiv.style.position = "absolute";
  30635. this._statsDiv.style.background = background;
  30636. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30637. this._generateheader(this._statsDiv, "STATISTICS");
  30638. this._statsSubsetDiv = document.createElement("div");
  30639. this._statsSubsetDiv.style.paddingTop = "5px";
  30640. this._statsSubsetDiv.style.paddingBottom = "5px";
  30641. this._statsSubsetDiv.style.overflowY = "auto";
  30642. this._statsDiv.appendChild(this._statsSubsetDiv);
  30643. // Tree
  30644. this._treeDiv = document.createElement("div");
  30645. this._treeDiv.id = "DebugLayerTree";
  30646. this._treeDiv.style.border = border;
  30647. this._treeDiv.style.position = "absolute";
  30648. this._treeDiv.style.background = background;
  30649. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30650. this._treeDiv.style.display = "none";
  30651. this._generateheader(this._treeDiv, "MESHES TREE");
  30652. this._treeSubsetDiv = document.createElement("div");
  30653. this._treeSubsetDiv.style.paddingTop = "5px";
  30654. this._treeSubsetDiv.style.paddingRight = "5px";
  30655. this._treeSubsetDiv.style.overflowY = "auto";
  30656. this._treeSubsetDiv.style.maxHeight = "300px";
  30657. this._treeDiv.appendChild(this._treeSubsetDiv);
  30658. this._needToRefreshMeshesTree = true;
  30659. // Logs
  30660. this._logDiv = document.createElement("div");
  30661. this._logDiv.style.border = border;
  30662. this._logDiv.id = "DebugLayerLogs";
  30663. this._logDiv.style.position = "absolute";
  30664. this._logDiv.style.background = background;
  30665. this._logDiv.style.padding = "0px 0px 0px 5px";
  30666. this._logDiv.style.display = "none";
  30667. this._generateheader(this._logDiv, "LOGS");
  30668. this._logSubsetDiv = document.createElement("div");
  30669. this._logSubsetDiv.style.height = "127px";
  30670. this._logSubsetDiv.style.paddingTop = "5px";
  30671. this._logSubsetDiv.style.overflowY = "auto";
  30672. this._logSubsetDiv.style.fontSize = "12px";
  30673. this._logSubsetDiv.style.fontFamily = "consolas";
  30674. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30675. this._logDiv.appendChild(this._logSubsetDiv);
  30676. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30677. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30678. };
  30679. // Options
  30680. this._optionsDiv = document.createElement("div");
  30681. this._optionsDiv.id = "DebugLayerOptions";
  30682. this._optionsDiv.style.border = border;
  30683. this._optionsDiv.style.position = "absolute";
  30684. this._optionsDiv.style.background = background;
  30685. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30686. this._optionsDiv.style.overflowY = "auto";
  30687. this._generateheader(this._optionsDiv, "OPTIONS");
  30688. this._optionsSubsetDiv = document.createElement("div");
  30689. this._optionsSubsetDiv.style.paddingTop = "5px";
  30690. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30691. this._optionsSubsetDiv.style.overflowY = "auto";
  30692. this._optionsSubsetDiv.style.maxHeight = "200px";
  30693. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30694. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30695. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30696. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30697. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30698. _this._displayTree = element.checked;
  30699. _this._needToRefreshMeshesTree = true;
  30700. });
  30701. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30702. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30703. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  30704. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  30705. _this._labelsEnabled = element.checked;
  30706. if (!_this._labelsEnabled) {
  30707. _this._clearLabels();
  30708. }
  30709. });
  30710. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  30711. if (element.checked) {
  30712. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  30713. }
  30714. else {
  30715. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  30716. }
  30717. });
  30718. ;
  30719. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30720. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  30721. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  30722. if (element.checked) {
  30723. _this._scene.forceWireframe = false;
  30724. _this._scene.forcePointsCloud = false;
  30725. }
  30726. });
  30727. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  30728. if (element.checked) {
  30729. _this._scene.forceWireframe = true;
  30730. _this._scene.forcePointsCloud = false;
  30731. }
  30732. });
  30733. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  30734. if (element.checked) {
  30735. _this._scene.forceWireframe = false;
  30736. _this._scene.forcePointsCloud = true;
  30737. }
  30738. });
  30739. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30740. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  30741. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  30742. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  30743. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  30744. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  30745. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  30746. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  30747. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  30748. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  30749. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30750. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  30751. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  30752. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  30753. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  30754. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  30755. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  30756. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  30757. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  30758. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  30759. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  30760. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  30761. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  30762. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  30763. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  30764. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30765. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30766. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  30767. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  30768. if (element.checked) {
  30769. _this._scene.headphone = true;
  30770. }
  30771. });
  30772. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30773. if (element.checked) {
  30774. _this._scene.headphone = false;
  30775. }
  30776. });
  30777. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  30778. _this._scene.audioEnabled = !element.checked;
  30779. });
  30780. }
  30781. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30782. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  30783. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  30784. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30785. this._globalDiv.appendChild(this._statsDiv);
  30786. this._globalDiv.appendChild(this._logDiv);
  30787. this._globalDiv.appendChild(this._optionsDiv);
  30788. this._globalDiv.appendChild(this._treeDiv);
  30789. }
  30790. };
  30791. DebugLayer.prototype._displayStats = function () {
  30792. var scene = this._scene;
  30793. var engine = scene.getEngine();
  30794. var glInfo = engine.getGlInfo();
  30795. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  30796. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30797. + "<b>Count</b><br>"
  30798. + "Total meshes: " + scene.meshes.length + "<br>"
  30799. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  30800. + "Total materials: " + scene.materials.length + "<br>"
  30801. + "Total textures: " + scene.textures.length + "<br>"
  30802. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  30803. + "Active indices: " + scene.getActiveIndices() + "<br>"
  30804. + "Active bones: " + scene.getActiveBones() + "<br>"
  30805. + "Active particles: " + scene.getActiveParticles() + "<br>"
  30806. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  30807. + "<b>Duration</b><br>"
  30808. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  30809. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  30810. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  30811. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  30812. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  30813. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  30814. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  30815. + "</div>"
  30816. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30817. + "<b>Extensions</b><br>"
  30818. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  30819. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  30820. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  30821. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  30822. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  30823. + "<b>Caps.</b><br>"
  30824. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  30825. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  30826. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  30827. + "</div><br>"
  30828. + "<b>Info</b><br>"
  30829. + glInfo.version + "<br>"
  30830. + glInfo.renderer + "<br>";
  30831. if (this.customStatsFunction) {
  30832. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  30833. }
  30834. };
  30835. return DebugLayer;
  30836. })();
  30837. BABYLON.DebugLayer = DebugLayer;
  30838. })(BABYLON || (BABYLON = {}));
  30839. var BABYLON;
  30840. (function (BABYLON) {
  30841. var RawTexture = (function (_super) {
  30842. __extends(RawTexture, _super);
  30843. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30844. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30845. if (invertY === void 0) { invertY = false; }
  30846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30847. _super.call(this, null, scene, !generateMipMaps, invertY);
  30848. this.format = format;
  30849. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30850. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30851. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30852. }
  30853. RawTexture.prototype.update = function (data) {
  30854. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  30855. };
  30856. // Statics
  30857. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30858. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30859. if (invertY === void 0) { invertY = false; }
  30860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30861. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30862. };
  30863. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30864. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30865. if (invertY === void 0) { invertY = false; }
  30866. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30867. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30868. };
  30869. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30870. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30871. if (invertY === void 0) { invertY = false; }
  30872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30873. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30874. };
  30875. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30876. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30877. if (invertY === void 0) { invertY = false; }
  30878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30879. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  30880. };
  30881. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30882. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30883. if (invertY === void 0) { invertY = false; }
  30884. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30885. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  30886. };
  30887. return RawTexture;
  30888. })(BABYLON.Texture);
  30889. BABYLON.RawTexture = RawTexture;
  30890. })(BABYLON || (BABYLON = {}));
  30891. var BABYLON;
  30892. (function (BABYLON) {
  30893. var IndexedVector2 = (function (_super) {
  30894. __extends(IndexedVector2, _super);
  30895. function IndexedVector2(original, index) {
  30896. _super.call(this, original.x, original.y);
  30897. this.index = index;
  30898. }
  30899. return IndexedVector2;
  30900. })(BABYLON.Vector2);
  30901. var PolygonPoints = (function () {
  30902. function PolygonPoints() {
  30903. this.elements = new Array();
  30904. }
  30905. PolygonPoints.prototype.add = function (originalPoints) {
  30906. var _this = this;
  30907. var result = new Array();
  30908. originalPoints.forEach(function (point) {
  30909. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  30910. var newPoint = new IndexedVector2(point, _this.elements.length);
  30911. result.push(newPoint);
  30912. _this.elements.push(newPoint);
  30913. }
  30914. });
  30915. return result;
  30916. };
  30917. PolygonPoints.prototype.computeBounds = function () {
  30918. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30919. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30920. this.elements.forEach(function (point) {
  30921. // x
  30922. if (point.x < lmin.x) {
  30923. lmin.x = point.x;
  30924. }
  30925. else if (point.x > lmax.x) {
  30926. lmax.x = point.x;
  30927. }
  30928. // y
  30929. if (point.y < lmin.y) {
  30930. lmin.y = point.y;
  30931. }
  30932. else if (point.y > lmax.y) {
  30933. lmax.y = point.y;
  30934. }
  30935. });
  30936. return {
  30937. min: lmin,
  30938. max: lmax,
  30939. width: lmax.x - lmin.x,
  30940. height: lmax.y - lmin.y
  30941. };
  30942. };
  30943. return PolygonPoints;
  30944. })();
  30945. var Polygon = (function () {
  30946. function Polygon() {
  30947. }
  30948. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  30949. return [
  30950. new BABYLON.Vector2(xmin, ymin),
  30951. new BABYLON.Vector2(xmax, ymin),
  30952. new BABYLON.Vector2(xmax, ymax),
  30953. new BABYLON.Vector2(xmin, ymax)
  30954. ];
  30955. };
  30956. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  30957. if (cx === void 0) { cx = 0; }
  30958. if (cy === void 0) { cy = 0; }
  30959. if (numberOfSides === void 0) { numberOfSides = 32; }
  30960. var result = new Array();
  30961. var angle = 0;
  30962. var increment = (Math.PI * 2) / numberOfSides;
  30963. for (var i = 0; i < numberOfSides; i++) {
  30964. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  30965. angle -= increment;
  30966. }
  30967. return result;
  30968. };
  30969. Polygon.Parse = function (input) {
  30970. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  30971. var i, result = [];
  30972. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  30973. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  30974. }
  30975. return result;
  30976. };
  30977. Polygon.StartingAt = function (x, y) {
  30978. return BABYLON.Path2.StartingAt(x, y);
  30979. };
  30980. return Polygon;
  30981. })();
  30982. BABYLON.Polygon = Polygon;
  30983. var PolygonMeshBuilder = (function () {
  30984. function PolygonMeshBuilder(name, contours, scene) {
  30985. this._points = new PolygonPoints();
  30986. this._outlinepoints = new PolygonPoints();
  30987. this._holes = [];
  30988. if (!("poly2tri" in window)) {
  30989. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  30990. }
  30991. this._name = name;
  30992. this._scene = scene;
  30993. var points;
  30994. if (contours instanceof BABYLON.Path2) {
  30995. points = contours.getPoints();
  30996. }
  30997. else {
  30998. points = contours;
  30999. }
  31000. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31001. this._outlinepoints.add(points);
  31002. }
  31003. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31004. this._swctx.addHole(this._points.add(hole));
  31005. var holepoints = new PolygonPoints();
  31006. holepoints.add(hole);
  31007. this._holes.push(holepoints);
  31008. return this;
  31009. };
  31010. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31011. var _this = this;
  31012. if (updatable === void 0) { updatable = false; }
  31013. var result = new BABYLON.Mesh(this._name, this._scene);
  31014. var normals = [];
  31015. var positions = [];
  31016. var uvs = [];
  31017. var bounds = this._points.computeBounds();
  31018. this._points.elements.forEach(function (p) {
  31019. normals.push(0, 1.0, 0);
  31020. positions.push(p.x, 0, p.y);
  31021. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31022. });
  31023. var indices = [];
  31024. this._swctx.triangulate();
  31025. this._swctx.getTriangles().forEach(function (triangle) {
  31026. triangle.getPoints().forEach(function (point) {
  31027. indices.push(point.index);
  31028. });
  31029. });
  31030. if (depth > 0) {
  31031. var positionscount = (positions.length / 3); //get the current pointcount
  31032. this._points.elements.forEach(function (p) {
  31033. normals.push(0, -1.0, 0);
  31034. positions.push(p.x, -depth, p.y);
  31035. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31036. });
  31037. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31038. var p2;
  31039. var poscounter = 0;
  31040. this._swctx.getTriangles().forEach(function (triangle) {
  31041. triangle.getPoints().forEach(function (point) {
  31042. switch (poscounter) {
  31043. case 0:
  31044. p1 = point;
  31045. break;
  31046. case 1:
  31047. p2 = point;
  31048. break;
  31049. case 2:
  31050. indices.push(point.index + positionscount);
  31051. indices.push(p2.index + positionscount);
  31052. indices.push(p1.index + positionscount);
  31053. poscounter = -1;
  31054. break;
  31055. }
  31056. poscounter++;
  31057. //indices.push((<IndexedVector2>point).index + positionscount);
  31058. });
  31059. });
  31060. //Add the sides
  31061. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31062. this._holes.forEach(function (hole) {
  31063. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31064. });
  31065. }
  31066. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31067. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31068. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31069. result.setIndices(indices);
  31070. return result;
  31071. };
  31072. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31073. var StartIndex = positions.length / 3;
  31074. var ulength = 0;
  31075. for (var i = 0; i < points.elements.length; i++) {
  31076. var p = points.elements[i];
  31077. var p1;
  31078. if ((i + 1) > points.elements.length - 1) {
  31079. p1 = points.elements[0];
  31080. }
  31081. else {
  31082. p1 = points.elements[i + 1];
  31083. }
  31084. positions.push(p.x, 0, p.y);
  31085. positions.push(p.x, -depth, p.y);
  31086. positions.push(p1.x, 0, p1.y);
  31087. positions.push(p1.x, -depth, p1.y);
  31088. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31089. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31090. var v3 = v2.subtract(v1);
  31091. var v4 = new BABYLON.Vector3(0, 1, 0);
  31092. var vn = BABYLON.Vector3.Cross(v3, v4);
  31093. vn = vn.normalize();
  31094. uvs.push(ulength / bounds.width, 0);
  31095. uvs.push(ulength / bounds.width, 1);
  31096. ulength += v3.length();
  31097. uvs.push((ulength / bounds.width), 0);
  31098. uvs.push((ulength / bounds.width), 1);
  31099. if (!flip) {
  31100. normals.push(-vn.x, -vn.y, -vn.z);
  31101. normals.push(-vn.x, -vn.y, -vn.z);
  31102. normals.push(-vn.x, -vn.y, -vn.z);
  31103. normals.push(-vn.x, -vn.y, -vn.z);
  31104. indices.push(StartIndex);
  31105. indices.push(StartIndex + 1);
  31106. indices.push(StartIndex + 2);
  31107. indices.push(StartIndex + 1);
  31108. indices.push(StartIndex + 3);
  31109. indices.push(StartIndex + 2);
  31110. }
  31111. else {
  31112. normals.push(vn.x, vn.y, vn.z);
  31113. normals.push(vn.x, vn.y, vn.z);
  31114. normals.push(vn.x, vn.y, vn.z);
  31115. normals.push(vn.x, vn.y, vn.z);
  31116. indices.push(StartIndex);
  31117. indices.push(StartIndex + 2);
  31118. indices.push(StartIndex + 1);
  31119. indices.push(StartIndex + 1);
  31120. indices.push(StartIndex + 2);
  31121. indices.push(StartIndex + 3);
  31122. }
  31123. StartIndex += 4;
  31124. }
  31125. ;
  31126. };
  31127. return PolygonMeshBuilder;
  31128. })();
  31129. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31130. })(BABYLON || (BABYLON = {}));
  31131. var BABYLON;
  31132. (function (BABYLON) {
  31133. var SimplificationSettings = (function () {
  31134. function SimplificationSettings(quality, distance, optimizeMesh) {
  31135. this.quality = quality;
  31136. this.distance = distance;
  31137. this.optimizeMesh = optimizeMesh;
  31138. }
  31139. return SimplificationSettings;
  31140. })();
  31141. BABYLON.SimplificationSettings = SimplificationSettings;
  31142. var SimplificationQueue = (function () {
  31143. function SimplificationQueue() {
  31144. this.running = false;
  31145. this._simplificationArray = [];
  31146. }
  31147. SimplificationQueue.prototype.addTask = function (task) {
  31148. this._simplificationArray.push(task);
  31149. };
  31150. SimplificationQueue.prototype.executeNext = function () {
  31151. var task = this._simplificationArray.pop();
  31152. if (task) {
  31153. this.running = true;
  31154. this.runSimplification(task);
  31155. }
  31156. else {
  31157. this.running = false;
  31158. }
  31159. };
  31160. SimplificationQueue.prototype.runSimplification = function (task) {
  31161. var _this = this;
  31162. if (task.parallelProcessing) {
  31163. //parallel simplifier
  31164. task.settings.forEach(function (setting) {
  31165. var simplifier = _this.getSimplifier(task);
  31166. simplifier.simplify(setting, function (newMesh) {
  31167. task.mesh.addLODLevel(setting.distance, newMesh);
  31168. newMesh.isVisible = true;
  31169. //check if it is the last
  31170. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31171. //all done, run the success callback.
  31172. task.successCallback();
  31173. }
  31174. _this.executeNext();
  31175. });
  31176. });
  31177. }
  31178. else {
  31179. //single simplifier.
  31180. var simplifier = this.getSimplifier(task);
  31181. var runDecimation = function (setting, callback) {
  31182. simplifier.simplify(setting, function (newMesh) {
  31183. task.mesh.addLODLevel(setting.distance, newMesh);
  31184. newMesh.isVisible = true;
  31185. //run the next quality level
  31186. callback();
  31187. });
  31188. };
  31189. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31190. runDecimation(task.settings[loop.index], function () {
  31191. loop.executeNext();
  31192. });
  31193. }, function () {
  31194. //execution ended, run the success callback.
  31195. if (task.successCallback) {
  31196. task.successCallback();
  31197. }
  31198. _this.executeNext();
  31199. });
  31200. }
  31201. };
  31202. SimplificationQueue.prototype.getSimplifier = function (task) {
  31203. switch (task.simplificationType) {
  31204. case SimplificationType.QUADRATIC:
  31205. default:
  31206. return new QuadraticErrorSimplification(task.mesh);
  31207. }
  31208. };
  31209. return SimplificationQueue;
  31210. })();
  31211. BABYLON.SimplificationQueue = SimplificationQueue;
  31212. /**
  31213. * The implemented types of simplification.
  31214. * At the moment only Quadratic Error Decimation is implemented.
  31215. */
  31216. (function (SimplificationType) {
  31217. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31218. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31219. var SimplificationType = BABYLON.SimplificationType;
  31220. var DecimationTriangle = (function () {
  31221. function DecimationTriangle(vertices) {
  31222. this.vertices = vertices;
  31223. this.error = new Array(4);
  31224. this.deleted = false;
  31225. this.isDirty = false;
  31226. this.deletePending = false;
  31227. this.borderFactor = 0;
  31228. }
  31229. return DecimationTriangle;
  31230. })();
  31231. BABYLON.DecimationTriangle = DecimationTriangle;
  31232. var DecimationVertex = (function () {
  31233. function DecimationVertex(position, id) {
  31234. this.position = position;
  31235. this.id = id;
  31236. this.isBorder = true;
  31237. this.q = new QuadraticMatrix();
  31238. this.triangleCount = 0;
  31239. this.triangleStart = 0;
  31240. this.originalOffsets = [];
  31241. }
  31242. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31243. this.position.copyFrom(newPosition);
  31244. };
  31245. return DecimationVertex;
  31246. })();
  31247. BABYLON.DecimationVertex = DecimationVertex;
  31248. var QuadraticMatrix = (function () {
  31249. function QuadraticMatrix(data) {
  31250. this.data = new Array(10);
  31251. for (var i = 0; i < 10; ++i) {
  31252. if (data && data[i]) {
  31253. this.data[i] = data[i];
  31254. }
  31255. else {
  31256. this.data[i] = 0;
  31257. }
  31258. }
  31259. }
  31260. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31261. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31262. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31263. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31264. return det;
  31265. };
  31266. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31267. for (var i = 0; i < 10; ++i) {
  31268. this.data[i] += matrix.data[i];
  31269. }
  31270. };
  31271. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31272. for (var i = 0; i < 10; ++i) {
  31273. this.data[i] += data[i];
  31274. }
  31275. };
  31276. QuadraticMatrix.prototype.add = function (matrix) {
  31277. var m = new QuadraticMatrix();
  31278. for (var i = 0; i < 10; ++i) {
  31279. m.data[i] = this.data[i] + matrix.data[i];
  31280. }
  31281. return m;
  31282. };
  31283. QuadraticMatrix.FromData = function (a, b, c, d) {
  31284. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31285. };
  31286. //returning an array to avoid garbage collection
  31287. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31288. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31289. };
  31290. return QuadraticMatrix;
  31291. })();
  31292. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31293. var Reference = (function () {
  31294. function Reference(vertexId, triangleId) {
  31295. this.vertexId = vertexId;
  31296. this.triangleId = triangleId;
  31297. }
  31298. return Reference;
  31299. })();
  31300. BABYLON.Reference = Reference;
  31301. /**
  31302. * An implementation of the Quadratic Error simplification algorithm.
  31303. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31304. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31305. * @author RaananW
  31306. */
  31307. var QuadraticErrorSimplification = (function () {
  31308. function QuadraticErrorSimplification(_mesh) {
  31309. this._mesh = _mesh;
  31310. this.initialized = false;
  31311. this.syncIterations = 5000;
  31312. this.aggressiveness = 7;
  31313. this.decimationIterations = 100;
  31314. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31315. }
  31316. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31317. var _this = this;
  31318. this.initDecimatedMesh();
  31319. //iterating through the submeshes array, one after the other.
  31320. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31321. _this.initWithMesh(loop.index, function () {
  31322. _this.runDecimation(settings, loop.index, function () {
  31323. loop.executeNext();
  31324. });
  31325. }, settings.optimizeMesh);
  31326. }, function () {
  31327. setTimeout(function () {
  31328. successCallback(_this._reconstructedMesh);
  31329. }, 0);
  31330. });
  31331. };
  31332. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31333. var _this = this;
  31334. var gCount = 0;
  31335. triangle.vertices.forEach(function (vertex) {
  31336. var count = 0;
  31337. var vPos = vertex.position;
  31338. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31339. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31340. ++count;
  31341. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31342. ++count;
  31343. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31344. ++count;
  31345. if (count > 1) {
  31346. ++gCount;
  31347. }
  31348. ;
  31349. });
  31350. if (gCount > 1) {
  31351. console.log(triangle, gCount);
  31352. }
  31353. return gCount > 1;
  31354. };
  31355. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31356. var _this = this;
  31357. var targetCount = ~~(this.triangles.length * settings.quality);
  31358. var deletedTriangles = 0;
  31359. var triangleCount = this.triangles.length;
  31360. var iterationFunction = function (iteration, callback) {
  31361. setTimeout(function () {
  31362. if (iteration % 5 === 0) {
  31363. _this.updateMesh(iteration === 0);
  31364. }
  31365. for (var i = 0; i < _this.triangles.length; ++i) {
  31366. _this.triangles[i].isDirty = false;
  31367. }
  31368. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31369. var trianglesIterator = function (i) {
  31370. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31371. var t = _this.triangles[tIdx];
  31372. if (!t)
  31373. return;
  31374. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31375. return;
  31376. }
  31377. for (var j = 0; j < 3; ++j) {
  31378. if (t.error[j] < threshold) {
  31379. var deleted0 = [];
  31380. var deleted1 = [];
  31381. var v0 = t.vertices[j];
  31382. var v1 = t.vertices[(j + 1) % 3];
  31383. if (v0.isBorder !== v1.isBorder)
  31384. continue;
  31385. var p = BABYLON.Vector3.Zero();
  31386. var n = BABYLON.Vector3.Zero();
  31387. var uv = BABYLON.Vector2.Zero();
  31388. var color = new BABYLON.Color4(0, 0, 0, 1);
  31389. _this.calculateError(v0, v1, p, n, uv, color);
  31390. var delTr = [];
  31391. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31392. continue;
  31393. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31394. continue;
  31395. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31396. continue;
  31397. var uniqueArray = [];
  31398. delTr.forEach(function (deletedT) {
  31399. if (uniqueArray.indexOf(deletedT) === -1) {
  31400. deletedT.deletePending = true;
  31401. uniqueArray.push(deletedT);
  31402. }
  31403. });
  31404. if (uniqueArray.length % 2 != 0) {
  31405. continue;
  31406. }
  31407. v0.q = v1.q.add(v0.q);
  31408. v0.updatePosition(p);
  31409. var tStart = _this.references.length;
  31410. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31411. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31412. var tCount = _this.references.length - tStart;
  31413. if (tCount <= v0.triangleCount) {
  31414. if (tCount) {
  31415. for (var c = 0; c < tCount; c++) {
  31416. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31417. }
  31418. }
  31419. }
  31420. else {
  31421. v0.triangleStart = tStart;
  31422. }
  31423. v0.triangleCount = tCount;
  31424. break;
  31425. }
  31426. }
  31427. };
  31428. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31429. }, 0);
  31430. };
  31431. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31432. if (triangleCount - deletedTriangles <= targetCount)
  31433. loop.breakLoop();
  31434. else {
  31435. iterationFunction(loop.index, function () {
  31436. loop.executeNext();
  31437. });
  31438. }
  31439. }, function () {
  31440. setTimeout(function () {
  31441. //reconstruct this part of the mesh
  31442. _this.reconstructMesh(submeshIndex);
  31443. successCallback();
  31444. }, 0);
  31445. });
  31446. };
  31447. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31448. var _this = this;
  31449. this.vertices = [];
  31450. this.triangles = [];
  31451. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31452. var indices = this._mesh.getIndices();
  31453. var submesh = this._mesh.subMeshes[submeshIndex];
  31454. var findInVertices = function (positionToSearch) {
  31455. if (optimizeMesh) {
  31456. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31457. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31458. return _this.vertices[ii];
  31459. }
  31460. }
  31461. }
  31462. return null;
  31463. };
  31464. var vertexReferences = [];
  31465. var vertexInit = function (i) {
  31466. var offset = i + submesh.verticesStart;
  31467. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31468. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31469. vertex.originalOffsets.push(offset);
  31470. if (vertex.id == _this.vertices.length) {
  31471. _this.vertices.push(vertex);
  31472. }
  31473. vertexReferences.push(vertex.id);
  31474. };
  31475. //var totalVertices = mesh.getTotalVertices();
  31476. var totalVertices = submesh.verticesCount;
  31477. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31478. var indicesInit = function (i) {
  31479. var offset = (submesh.indexStart / 3) + i;
  31480. var pos = (offset * 3);
  31481. var i0 = indices[pos + 0];
  31482. var i1 = indices[pos + 1];
  31483. var i2 = indices[pos + 2];
  31484. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31485. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31486. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31487. var triangle = new DecimationTriangle([v0, v1, v2]);
  31488. triangle.originalOffset = pos;
  31489. _this.triangles.push(triangle);
  31490. };
  31491. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31492. _this.init(callback);
  31493. });
  31494. });
  31495. };
  31496. QuadraticErrorSimplification.prototype.init = function (callback) {
  31497. var _this = this;
  31498. var triangleInit1 = function (i) {
  31499. var t = _this.triangles[i];
  31500. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31501. for (var j = 0; j < 3; j++) {
  31502. 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))));
  31503. }
  31504. };
  31505. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31506. var triangleInit2 = function (i) {
  31507. var t = _this.triangles[i];
  31508. for (var j = 0; j < 3; ++j) {
  31509. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31510. }
  31511. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31512. };
  31513. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31514. _this.initialized = true;
  31515. callback();
  31516. });
  31517. });
  31518. };
  31519. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31520. var newTriangles = [];
  31521. var i;
  31522. for (i = 0; i < this.vertices.length; ++i) {
  31523. this.vertices[i].triangleCount = 0;
  31524. }
  31525. var t;
  31526. var j;
  31527. for (i = 0; i < this.triangles.length; ++i) {
  31528. if (!this.triangles[i].deleted) {
  31529. t = this.triangles[i];
  31530. for (j = 0; j < 3; ++j) {
  31531. t.vertices[j].triangleCount = 1;
  31532. }
  31533. newTriangles.push(t);
  31534. }
  31535. }
  31536. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31537. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31538. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31539. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31540. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31541. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31542. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31543. var vertexCount = 0;
  31544. for (i = 0; i < this.vertices.length; ++i) {
  31545. var vertex = this.vertices[i];
  31546. vertex.id = vertexCount;
  31547. if (vertex.triangleCount) {
  31548. vertex.originalOffsets.forEach(function (originalOffset) {
  31549. newPositionData.push(vertex.position.x);
  31550. newPositionData.push(vertex.position.y);
  31551. newPositionData.push(vertex.position.z);
  31552. newNormalData.push(normalData[originalOffset * 3]);
  31553. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31554. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31555. if (uvs && uvs.length) {
  31556. newUVsData.push(uvs[(originalOffset * 2)]);
  31557. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31558. }
  31559. else if (colorsData && colorsData.length) {
  31560. newColorsData.push(colorsData[(originalOffset * 4)]);
  31561. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31562. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31563. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31564. }
  31565. ++vertexCount;
  31566. });
  31567. }
  31568. }
  31569. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31570. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31571. var submeshesArray = this._reconstructedMesh.subMeshes;
  31572. this._reconstructedMesh.subMeshes = [];
  31573. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31574. var originalIndices = this._mesh.getIndices();
  31575. for (i = 0; i < newTriangles.length; ++i) {
  31576. var t = newTriangles[i];
  31577. //now get the new referencing point for each vertex
  31578. [0, 1, 2].forEach(function (idx) {
  31579. var id = originalIndices[t.originalOffset + idx];
  31580. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31581. if (offset < 0)
  31582. offset = 0;
  31583. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31584. });
  31585. }
  31586. //overwriting the old vertex buffers and indices.
  31587. this._reconstructedMesh.setIndices(newIndicesArray);
  31588. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31589. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31590. if (newUVsData.length > 0)
  31591. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31592. if (newColorsData.length > 0)
  31593. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31594. //create submesh
  31595. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31596. if (submeshIndex > 0) {
  31597. this._reconstructedMesh.subMeshes = [];
  31598. submeshesArray.forEach(function (submesh) {
  31599. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31600. });
  31601. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31602. }
  31603. };
  31604. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31605. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31606. this._reconstructedMesh.material = this._mesh.material;
  31607. this._reconstructedMesh.parent = this._mesh.parent;
  31608. this._reconstructedMesh.isVisible = false;
  31609. };
  31610. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31611. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31612. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31613. if (t.deleted)
  31614. continue;
  31615. var s = this.references[vertex1.triangleStart + i].vertexId;
  31616. var v1 = t.vertices[(s + 1) % 3];
  31617. var v2 = t.vertices[(s + 2) % 3];
  31618. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31619. deletedArray[i] = true;
  31620. delTr.push(t);
  31621. continue;
  31622. }
  31623. var d1 = v1.position.subtract(point);
  31624. d1 = d1.normalize();
  31625. var d2 = v2.position.subtract(point);
  31626. d2 = d2.normalize();
  31627. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31628. return true;
  31629. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31630. deletedArray[i] = false;
  31631. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31632. return true;
  31633. }
  31634. return false;
  31635. };
  31636. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31637. var newDeleted = deletedTriangles;
  31638. for (var i = 0; i < vertex.triangleCount; ++i) {
  31639. var ref = this.references[vertex.triangleStart + i];
  31640. var t = this.triangles[ref.triangleId];
  31641. if (t.deleted)
  31642. continue;
  31643. if (deletedArray[i] && t.deletePending) {
  31644. t.deleted = true;
  31645. newDeleted++;
  31646. continue;
  31647. }
  31648. t.vertices[ref.vertexId] = origVertex;
  31649. t.isDirty = true;
  31650. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31651. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31652. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31653. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31654. this.references.push(ref);
  31655. }
  31656. return newDeleted;
  31657. };
  31658. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31659. for (var i = 0; i < this.vertices.length; ++i) {
  31660. var vCount = [];
  31661. var vId = [];
  31662. var v = this.vertices[i];
  31663. var j;
  31664. for (j = 0; j < v.triangleCount; ++j) {
  31665. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31666. for (var ii = 0; ii < 3; ii++) {
  31667. var ofs = 0;
  31668. var vv = triangle.vertices[ii];
  31669. while (ofs < vCount.length) {
  31670. if (vId[ofs] === vv.id)
  31671. break;
  31672. ++ofs;
  31673. }
  31674. if (ofs === vCount.length) {
  31675. vCount.push(1);
  31676. vId.push(vv.id);
  31677. }
  31678. else {
  31679. vCount[ofs]++;
  31680. }
  31681. }
  31682. }
  31683. for (j = 0; j < vCount.length; ++j) {
  31684. if (vCount[j] === 1) {
  31685. this.vertices[vId[j]].isBorder = true;
  31686. }
  31687. else {
  31688. this.vertices[vId[j]].isBorder = false;
  31689. }
  31690. }
  31691. }
  31692. };
  31693. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31694. if (identifyBorders === void 0) { identifyBorders = false; }
  31695. var i;
  31696. if (!identifyBorders) {
  31697. var newTrianglesVector = [];
  31698. for (i = 0; i < this.triangles.length; ++i) {
  31699. if (!this.triangles[i].deleted) {
  31700. newTrianglesVector.push(this.triangles[i]);
  31701. }
  31702. }
  31703. this.triangles = newTrianglesVector;
  31704. }
  31705. for (i = 0; i < this.vertices.length; ++i) {
  31706. this.vertices[i].triangleCount = 0;
  31707. this.vertices[i].triangleStart = 0;
  31708. }
  31709. var t;
  31710. var j;
  31711. var v;
  31712. for (i = 0; i < this.triangles.length; ++i) {
  31713. t = this.triangles[i];
  31714. for (j = 0; j < 3; ++j) {
  31715. v = t.vertices[j];
  31716. v.triangleCount++;
  31717. }
  31718. }
  31719. var tStart = 0;
  31720. for (i = 0; i < this.vertices.length; ++i) {
  31721. this.vertices[i].triangleStart = tStart;
  31722. tStart += this.vertices[i].triangleCount;
  31723. this.vertices[i].triangleCount = 0;
  31724. }
  31725. var newReferences = new Array(this.triangles.length * 3);
  31726. for (i = 0; i < this.triangles.length; ++i) {
  31727. t = this.triangles[i];
  31728. for (j = 0; j < 3; ++j) {
  31729. v = t.vertices[j];
  31730. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31731. v.triangleCount++;
  31732. }
  31733. }
  31734. this.references = newReferences;
  31735. if (identifyBorders) {
  31736. this.identifyBorder();
  31737. }
  31738. };
  31739. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31740. var x = point.x;
  31741. var y = point.y;
  31742. var z = point.z;
  31743. 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
  31744. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31745. };
  31746. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31747. var q = vertex1.q.add(vertex2.q);
  31748. var border = vertex1.isBorder && vertex2.isBorder;
  31749. var error = 0;
  31750. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31751. if (qDet !== 0 && !border) {
  31752. if (!pointResult) {
  31753. pointResult = BABYLON.Vector3.Zero();
  31754. }
  31755. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31756. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31757. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31758. error = this.vertexError(q, pointResult);
  31759. }
  31760. else {
  31761. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31762. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31763. var error1 = this.vertexError(q, vertex1.position);
  31764. var error2 = this.vertexError(q, vertex2.position);
  31765. var error3 = this.vertexError(q, p3);
  31766. error = Math.min(error1, error2, error3);
  31767. if (error === error1) {
  31768. if (pointResult) {
  31769. pointResult.copyFrom(vertex1.position);
  31770. }
  31771. }
  31772. else if (error === error2) {
  31773. if (pointResult) {
  31774. pointResult.copyFrom(vertex2.position);
  31775. }
  31776. }
  31777. else {
  31778. if (pointResult) {
  31779. pointResult.copyFrom(p3);
  31780. }
  31781. }
  31782. }
  31783. return error;
  31784. };
  31785. return QuadraticErrorSimplification;
  31786. })();
  31787. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31788. })(BABYLON || (BABYLON = {}));
  31789. var BABYLON;
  31790. (function (BABYLON) {
  31791. var Analyser = (function () {
  31792. function Analyser(scene) {
  31793. this.SMOOTHING = 0.75;
  31794. this.FFT_SIZE = 512;
  31795. this.BARGRAPHAMPLITUDE = 256;
  31796. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  31797. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  31798. this._scene = scene;
  31799. this._audioEngine = BABYLON.Engine.audioEngine;
  31800. if (this._audioEngine.canUseWebAudio) {
  31801. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  31802. this._webAudioAnalyser.minDecibels = -140;
  31803. this._webAudioAnalyser.maxDecibels = 0;
  31804. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31805. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31806. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  31807. }
  31808. }
  31809. Analyser.prototype.getFrequencyBinCount = function () {
  31810. if (this._audioEngine.canUseWebAudio) {
  31811. return this._webAudioAnalyser.frequencyBinCount;
  31812. }
  31813. else {
  31814. return 0;
  31815. }
  31816. };
  31817. Analyser.prototype.getByteFrequencyData = function () {
  31818. if (this._audioEngine.canUseWebAudio) {
  31819. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31820. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31821. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  31822. }
  31823. return this._byteFreqs;
  31824. };
  31825. Analyser.prototype.getByteTimeDomainData = function () {
  31826. if (this._audioEngine.canUseWebAudio) {
  31827. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31828. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31829. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31830. }
  31831. return this._byteTime;
  31832. };
  31833. Analyser.prototype.getFloatFrequencyData = function () {
  31834. if (this._audioEngine.canUseWebAudio) {
  31835. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31836. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31837. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31838. }
  31839. return this._floatFreqs;
  31840. };
  31841. Analyser.prototype.drawDebugCanvas = function () {
  31842. var _this = this;
  31843. if (this._audioEngine.canUseWebAudio) {
  31844. if (!this._debugCanvas) {
  31845. this._debugCanvas = document.createElement("canvas");
  31846. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31847. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31848. this._debugCanvas.style.position = "absolute";
  31849. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31850. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31851. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31852. document.body.appendChild(this._debugCanvas);
  31853. this._registerFunc = function () {
  31854. _this.drawDebugCanvas();
  31855. };
  31856. this._scene.registerBeforeRender(this._registerFunc);
  31857. }
  31858. if (this._registerFunc) {
  31859. var workingArray = this.getByteFrequencyData();
  31860. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31861. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31862. // Draw the frequency domain chart.
  31863. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31864. var value = workingArray[i];
  31865. var percent = value / this.BARGRAPHAMPLITUDE;
  31866. var height = this.DEBUGCANVASSIZE.height * percent;
  31867. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  31868. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  31869. var hue = i / this.getFrequencyBinCount() * 360;
  31870. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  31871. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  31872. }
  31873. }
  31874. }
  31875. };
  31876. Analyser.prototype.stopDebugCanvas = function () {
  31877. if (this._debugCanvas) {
  31878. this._scene.unregisterBeforeRender(this._registerFunc);
  31879. this._registerFunc = null;
  31880. document.body.removeChild(this._debugCanvas);
  31881. this._debugCanvas = null;
  31882. this._debugCanvasContext = null;
  31883. }
  31884. };
  31885. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  31886. if (this._audioEngine.canUseWebAudio) {
  31887. inputAudioNode.connect(this._webAudioAnalyser);
  31888. this._webAudioAnalyser.connect(outputAudioNode);
  31889. }
  31890. };
  31891. Analyser.prototype.dispose = function () {
  31892. if (this._audioEngine.canUseWebAudio) {
  31893. this._webAudioAnalyser.disconnect();
  31894. }
  31895. };
  31896. return Analyser;
  31897. })();
  31898. BABYLON.Analyser = Analyser;
  31899. })(BABYLON || (BABYLON = {}));
  31900. var BABYLON;
  31901. (function (BABYLON) {
  31902. var DepthRenderer = (function () {
  31903. function DepthRenderer(scene, type) {
  31904. var _this = this;
  31905. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  31906. this._viewMatrix = BABYLON.Matrix.Zero();
  31907. this._projectionMatrix = BABYLON.Matrix.Zero();
  31908. this._transformMatrix = BABYLON.Matrix.Zero();
  31909. this._worldViewProjection = BABYLON.Matrix.Zero();
  31910. this._scene = scene;
  31911. var engine = scene.getEngine();
  31912. // Render target
  31913. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  31914. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31915. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31916. this._depthMap.refreshRate = 1;
  31917. this._depthMap.renderParticles = false;
  31918. this._depthMap.renderList = null;
  31919. // set default depth value to 1.0 (far away)
  31920. this._depthMap.onClear = function (engine) {
  31921. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  31922. };
  31923. // Custom render function
  31924. var renderSubMesh = function (subMesh) {
  31925. var mesh = subMesh.getRenderingMesh();
  31926. var scene = _this._scene;
  31927. var engine = scene.getEngine();
  31928. // Culling
  31929. engine.setState(subMesh.getMaterial().backFaceCulling);
  31930. // Managing instances
  31931. var batch = mesh._getInstancesRenderList(subMesh._id);
  31932. if (batch.mustReturn) {
  31933. return;
  31934. }
  31935. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31936. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31937. engine.enableEffect(_this._effect);
  31938. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31939. var material = subMesh.getMaterial();
  31940. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31941. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31942. // Alpha test
  31943. if (material && material.needAlphaTesting()) {
  31944. var alphaTexture = material.getAlphaTestTexture();
  31945. _this._effect.setTexture("diffuseSampler", alphaTexture);
  31946. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31947. }
  31948. // Bones
  31949. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31950. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31951. }
  31952. // Draw
  31953. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  31954. }
  31955. };
  31956. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  31957. var index;
  31958. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31959. renderSubMesh(opaqueSubMeshes.data[index]);
  31960. }
  31961. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31962. renderSubMesh(alphaTestSubMeshes.data[index]);
  31963. }
  31964. };
  31965. }
  31966. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  31967. var defines = [];
  31968. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31969. var mesh = subMesh.getMesh();
  31970. var scene = mesh.getScene();
  31971. var material = subMesh.getMaterial();
  31972. // Alpha test
  31973. if (material && material.needAlphaTesting()) {
  31974. defines.push("#define ALPHATEST");
  31975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31976. attribs.push(BABYLON.VertexBuffer.UVKind);
  31977. defines.push("#define UV1");
  31978. }
  31979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31980. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31981. defines.push("#define UV2");
  31982. }
  31983. }
  31984. // Bones
  31985. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31986. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31987. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31988. defines.push("#define BONES");
  31989. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31990. }
  31991. // Instances
  31992. if (useInstances) {
  31993. defines.push("#define INSTANCES");
  31994. attribs.push("world0");
  31995. attribs.push("world1");
  31996. attribs.push("world2");
  31997. attribs.push("world3");
  31998. }
  31999. // Get correct effect
  32000. var join = defines.join("\n");
  32001. if (this._cachedDefines !== join) {
  32002. this._cachedDefines = join;
  32003. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32004. }
  32005. return this._effect.isReady();
  32006. };
  32007. DepthRenderer.prototype.getDepthMap = function () {
  32008. return this._depthMap;
  32009. };
  32010. // Methods
  32011. DepthRenderer.prototype.dispose = function () {
  32012. this._depthMap.dispose();
  32013. };
  32014. return DepthRenderer;
  32015. })();
  32016. BABYLON.DepthRenderer = DepthRenderer;
  32017. })(BABYLON || (BABYLON = {}));
  32018. var BABYLON;
  32019. (function (BABYLON) {
  32020. var SSAORenderingPipeline = (function (_super) {
  32021. __extends(SSAORenderingPipeline, _super);
  32022. /**
  32023. * @constructor
  32024. * @param {string} name - The rendering pipeline name
  32025. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32026. * @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 }
  32027. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32028. */
  32029. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32030. var _this = this;
  32031. _super.call(this, scene.getEngine(), name);
  32032. // Members
  32033. /**
  32034. * The PassPostProcess id in the pipeline that contains the original scene color
  32035. * @type {string}
  32036. */
  32037. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32038. /**
  32039. * The SSAO PostProcess id in the pipeline
  32040. * @type {string}
  32041. */
  32042. this.SSAORenderEffect = "SSAORenderEffect";
  32043. /**
  32044. * The horizontal blur PostProcess id in the pipeline
  32045. * @type {string}
  32046. */
  32047. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32048. /**
  32049. * The vertical blur PostProcess id in the pipeline
  32050. * @type {string}
  32051. */
  32052. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32053. /**
  32054. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32055. * @type {string}
  32056. */
  32057. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32058. /**
  32059. * The output strength of the SSAO post-process. Default value is 1.0.
  32060. * @type {number}
  32061. */
  32062. this.totalStrength = 1.0;
  32063. /**
  32064. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32065. * @type {number}
  32066. */
  32067. this.radius = 0.0002;
  32068. /**
  32069. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32070. * Must not be equal to fallOff and superior to fallOff.
  32071. * Default value is 0.0075
  32072. * @type {number}
  32073. */
  32074. this.area = 0.0075;
  32075. /**
  32076. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32077. * Must not be equal to area and inferior to area.
  32078. * Default value is 0.0002
  32079. * @type {number}
  32080. */
  32081. this.fallOff = 0.0002;
  32082. this._firstUpdate = true;
  32083. this._scene = scene;
  32084. // Set up assets
  32085. this._createRandomTexture();
  32086. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32087. var ssaoRatio = ratio.ssaoRatio || ratio;
  32088. var combineRatio = ratio.combineRatio || ratio;
  32089. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32090. this._createSSAOPostProcess(ssaoRatio);
  32091. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32092. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32093. this._createSSAOCombinePostProcess(combineRatio);
  32094. // Set up pipeline
  32095. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32097. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32100. // Finish
  32101. scene.postProcessRenderPipelineManager.addPipeline(this);
  32102. if (cameras)
  32103. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32104. }
  32105. // Public Methods
  32106. /**
  32107. * Returns the horizontal blur PostProcess
  32108. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32109. */
  32110. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32111. return this._blurHPostProcess;
  32112. };
  32113. /**
  32114. * Returns the vertical blur PostProcess
  32115. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32116. */
  32117. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32118. return this._blurVPostProcess;
  32119. };
  32120. /**
  32121. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32122. */
  32123. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32124. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32125. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32126. this._originalColorPostProcess = undefined;
  32127. this._ssaoPostProcess = undefined;
  32128. this._blurHPostProcess = undefined;
  32129. this._blurVPostProcess = undefined;
  32130. this._ssaoCombinePostProcess = undefined;
  32131. this._randomTexture.dispose();
  32132. if (disableDepthRender)
  32133. this._scene.disableDepthRenderer();
  32134. };
  32135. // Private Methods
  32136. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32137. var _this = this;
  32138. var sampleSphere = [
  32139. 0.5381, 0.1856, -0.4319,
  32140. 0.1379, 0.2486, 0.4430,
  32141. 0.3371, 0.5679, -0.0057,
  32142. -0.6999, -0.0451, -0.0019,
  32143. 0.0689, -0.1598, -0.8547,
  32144. 0.0560, 0.0069, -0.1843,
  32145. -0.0146, 0.1402, 0.0762,
  32146. 0.0100, -0.1924, -0.0344,
  32147. -0.3577, -0.5301, -0.4358,
  32148. -0.3169, 0.1063, 0.0158,
  32149. 0.0103, -0.5869, 0.0046,
  32150. -0.0897, -0.4940, 0.3287,
  32151. 0.7119, -0.0154, -0.0918,
  32152. -0.0533, 0.0596, -0.5411,
  32153. 0.0352, -0.0631, 0.5460,
  32154. -0.4776, 0.2847, -0.0271
  32155. ];
  32156. var samplesFactor = 1.0 / 16.0;
  32157. 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);
  32158. this._ssaoPostProcess.onApply = function (effect) {
  32159. if (_this._firstUpdate) {
  32160. effect.setArray3("sampleSphere", sampleSphere);
  32161. effect.setFloat("samplesFactor", samplesFactor);
  32162. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32163. _this._firstUpdate = false;
  32164. }
  32165. effect.setFloat("totalStrength", _this.totalStrength);
  32166. effect.setFloat("radius", _this.radius);
  32167. effect.setFloat("area", _this.area);
  32168. effect.setFloat("fallOff", _this.fallOff);
  32169. effect.setTexture("textureSampler", _this._depthTexture);
  32170. effect.setTexture("randomSampler", _this._randomTexture);
  32171. };
  32172. };
  32173. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32174. var _this = this;
  32175. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32176. this._ssaoCombinePostProcess.onApply = function (effect) {
  32177. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32178. };
  32179. };
  32180. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32181. var size = 512;
  32182. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32183. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32184. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32185. var context = this._randomTexture.getContext();
  32186. var rand = function (min, max) {
  32187. return Math.random() * (max - min) + min;
  32188. };
  32189. for (var x = 0; x < size; x++) {
  32190. for (var y = 0; y < size; y++) {
  32191. var randVector = BABYLON.Vector3.Zero();
  32192. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32193. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32194. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32195. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32196. context.fillRect(x, y, 1, 1);
  32197. }
  32198. }
  32199. this._randomTexture.update(false);
  32200. };
  32201. return SSAORenderingPipeline;
  32202. })(BABYLON.PostProcessRenderPipeline);
  32203. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32204. })(BABYLON || (BABYLON = {}));
  32205. var BABYLON;
  32206. (function (BABYLON) {
  32207. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32208. var VolumetricLightScatteringPostProcess = (function (_super) {
  32209. __extends(VolumetricLightScatteringPostProcess, _super);
  32210. /**
  32211. * @constructor
  32212. * @param {string} name - The post-process name
  32213. * @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)
  32214. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32215. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32216. * @param {number} samples - The post-process quality, default 100
  32217. * @param {number} samplingMode - The post-process filtering mode
  32218. * @param {BABYLON.Engine} engine - The babylon engine
  32219. * @param {boolean} reusable - If the post-process is reusable
  32220. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32221. */
  32222. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32223. var _this = this;
  32224. if (samples === void 0) { samples = 100; }
  32225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32226. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32227. this._screenCoordinates = BABYLON.Vector2.Zero();
  32228. /**
  32229. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32230. * @type {boolean}
  32231. */
  32232. this.useCustomMeshPosition = false;
  32233. /**
  32234. * If the post-process should inverse the light scattering direction
  32235. * @type {boolean}
  32236. */
  32237. this.invert = true;
  32238. /**
  32239. * Set to true to use the diffuseColor instead of the diffuseTexture
  32240. * @type {boolean}
  32241. */
  32242. this.useDiffuseColor = false;
  32243. /**
  32244. * Array containing the excluded meshes not rendered in the internal pass
  32245. */
  32246. this.excludedMeshes = new Array();
  32247. /**
  32248. * Controls the overall intensity of the post-process
  32249. * @type {number}
  32250. */
  32251. this.exposure = 0.3;
  32252. /**
  32253. * Dissipates each sample's contribution in range [0, 1]
  32254. * @type {number}
  32255. */
  32256. this.decay = 0.96815;
  32257. /**
  32258. * Controls the overall intensity of each sample
  32259. * @type {number}
  32260. */
  32261. this.weight = 0.58767;
  32262. /**
  32263. * Controls the density of each sample
  32264. * @type {number}
  32265. */
  32266. this.density = 0.926;
  32267. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32268. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32269. // Configure mesh
  32270. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32271. // Configure
  32272. this._createPass(scene, ratio.passRatio || ratio);
  32273. this.onApply = function (effect) {
  32274. _this._updateMeshScreenCoordinates(scene);
  32275. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32276. effect.setFloat("exposure", _this.exposure);
  32277. effect.setFloat("decay", _this.decay);
  32278. effect.setFloat("weight", _this.weight);
  32279. effect.setFloat("density", _this.density);
  32280. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32281. };
  32282. }
  32283. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32284. var mesh = subMesh.getMesh();
  32285. var defines = [];
  32286. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32287. var material = subMesh.getMaterial();
  32288. var needUV = false;
  32289. // Render this.mesh as default
  32290. if (mesh === this.mesh) {
  32291. if (this.useDiffuseColor) {
  32292. defines.push("#define DIFFUSE_COLOR_RENDER");
  32293. }
  32294. else if (material) {
  32295. if (material.diffuseTexture !== undefined) {
  32296. defines.push("#define BASIC_RENDER");
  32297. }
  32298. else {
  32299. defines.push("#define DIFFUSE_COLOR_RENDER");
  32300. }
  32301. }
  32302. defines.push("#define NEED_UV");
  32303. needUV = true;
  32304. }
  32305. // Alpha test
  32306. if (material) {
  32307. if (material.needAlphaTesting()) {
  32308. defines.push("#define ALPHATEST");
  32309. }
  32310. if (material.opacityTexture !== undefined) {
  32311. defines.push("#define OPACITY");
  32312. if (material.opacityTexture.getAlphaFromRGB) {
  32313. defines.push("#define OPACITYRGB");
  32314. }
  32315. if (!needUV) {
  32316. defines.push("#define NEED_UV");
  32317. }
  32318. }
  32319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32320. attribs.push(BABYLON.VertexBuffer.UVKind);
  32321. defines.push("#define UV1");
  32322. }
  32323. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32324. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32325. defines.push("#define UV2");
  32326. }
  32327. }
  32328. // Bones
  32329. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32330. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32331. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32332. defines.push("#define BONES");
  32333. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32334. }
  32335. // Instances
  32336. if (useInstances) {
  32337. defines.push("#define INSTANCES");
  32338. attribs.push("world0");
  32339. attribs.push("world1");
  32340. attribs.push("world2");
  32341. attribs.push("world3");
  32342. }
  32343. // Get correct effect
  32344. var join = defines.join("\n");
  32345. if (this._cachedDefines !== join) {
  32346. this._cachedDefines = join;
  32347. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32348. }
  32349. return this._volumetricLightScatteringPass.isReady();
  32350. };
  32351. /**
  32352. * Sets the new light position for light scattering effect
  32353. * @param {BABYLON.Vector3} The new custom light position
  32354. */
  32355. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32356. this._customMeshPosition = position;
  32357. };
  32358. /**
  32359. * Returns the light position for light scattering effect
  32360. * @return {BABYLON.Vector3} The custom light position
  32361. */
  32362. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32363. return this._customMeshPosition;
  32364. };
  32365. /**
  32366. * Disposes the internal assets and detaches the post-process from the camera
  32367. */
  32368. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32369. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32370. if (rttIndex !== -1) {
  32371. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32372. }
  32373. this._volumetricLightScatteringRTT.dispose();
  32374. _super.prototype.dispose.call(this, camera);
  32375. };
  32376. /**
  32377. * Returns the render target texture used by the post-process
  32378. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32379. */
  32380. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32381. return this._volumetricLightScatteringRTT;
  32382. };
  32383. // Private methods
  32384. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32385. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32386. return true;
  32387. }
  32388. return false;
  32389. };
  32390. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32391. var _this = this;
  32392. var engine = scene.getEngine();
  32393. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32394. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32395. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32396. this._volumetricLightScatteringRTT.renderList = null;
  32397. this._volumetricLightScatteringRTT.renderParticles = false;
  32398. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32399. // Custom render function for submeshes
  32400. var renderSubMesh = function (subMesh) {
  32401. var mesh = subMesh.getRenderingMesh();
  32402. if (_this._meshExcluded(mesh)) {
  32403. return;
  32404. }
  32405. var scene = mesh.getScene();
  32406. var engine = scene.getEngine();
  32407. // Culling
  32408. engine.setState(subMesh.getMaterial().backFaceCulling);
  32409. // Managing instances
  32410. var batch = mesh._getInstancesRenderList(subMesh._id);
  32411. if (batch.mustReturn) {
  32412. return;
  32413. }
  32414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32415. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32416. engine.enableEffect(_this._volumetricLightScatteringPass);
  32417. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32418. var material = subMesh.getMaterial();
  32419. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32420. // Alpha test
  32421. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32422. var alphaTexture = material.getAlphaTestTexture();
  32423. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32424. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32425. }
  32426. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32427. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32428. if (alphaTexture) {
  32429. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32430. }
  32431. }
  32432. if (material.opacityTexture !== undefined) {
  32433. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32434. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32435. }
  32436. }
  32437. // Bones
  32438. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32439. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32440. }
  32441. // Draw
  32442. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32443. }
  32444. };
  32445. // Render target texture callbacks
  32446. var savedSceneClearColor;
  32447. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32448. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32449. savedSceneClearColor = scene.clearColor;
  32450. scene.clearColor = sceneClearColor;
  32451. };
  32452. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32453. scene.clearColor = savedSceneClearColor;
  32454. };
  32455. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32456. var engine = scene.getEngine();
  32457. var index;
  32458. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32459. renderSubMesh(opaqueSubMeshes.data[index]);
  32460. }
  32461. engine.setAlphaTesting(true);
  32462. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32463. renderSubMesh(alphaTestSubMeshes.data[index]);
  32464. }
  32465. engine.setAlphaTesting(false);
  32466. if (transparentSubMeshes.length) {
  32467. // Sort sub meshes
  32468. for (index = 0; index < transparentSubMeshes.length; index++) {
  32469. var submesh = transparentSubMeshes.data[index];
  32470. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32471. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32472. }
  32473. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32474. sortedArray.sort(function (a, b) {
  32475. // Alpha index first
  32476. if (a._alphaIndex > b._alphaIndex) {
  32477. return 1;
  32478. }
  32479. if (a._alphaIndex < b._alphaIndex) {
  32480. return -1;
  32481. }
  32482. // Then distance to camera
  32483. if (a._distanceToCamera < b._distanceToCamera) {
  32484. return 1;
  32485. }
  32486. if (a._distanceToCamera > b._distanceToCamera) {
  32487. return -1;
  32488. }
  32489. return 0;
  32490. });
  32491. // Render sub meshes
  32492. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32493. for (index = 0; index < sortedArray.length; index++) {
  32494. renderSubMesh(sortedArray[index]);
  32495. }
  32496. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32497. }
  32498. };
  32499. };
  32500. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32501. var transform = scene.getTransformMatrix();
  32502. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32503. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32504. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32505. if (this.invert)
  32506. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32507. };
  32508. // Static methods
  32509. /**
  32510. * Creates a default mesh for the Volumeric Light Scattering post-process
  32511. * @param {string} The mesh name
  32512. * @param {BABYLON.Scene} The scene where to create the mesh
  32513. * @return {BABYLON.Mesh} the default mesh
  32514. */
  32515. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32516. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32517. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32518. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32519. return mesh;
  32520. };
  32521. return VolumetricLightScatteringPostProcess;
  32522. })(BABYLON.PostProcess);
  32523. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32524. })(BABYLON || (BABYLON = {}));
  32525. var BABYLON;
  32526. (function (BABYLON) {
  32527. var LensRenderingPipeline = (function (_super) {
  32528. __extends(LensRenderingPipeline, _super);
  32529. /**
  32530. * @constructor
  32531. *
  32532. * Effect parameters are as follow:
  32533. * {
  32534. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32535. * edge_blur: number; // from 0 to x (1 for realism)
  32536. * distortion: number; // from 0 to x (1 for realism)
  32537. * grain_amount: number; // from 0 to 1
  32538. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32539. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32540. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32541. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32542. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32543. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32544. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32545. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32546. * }
  32547. * Note: if an effect parameter is unset, effect is disabled
  32548. *
  32549. * @param {string} name - The rendering pipeline name
  32550. * @param {object} parameters - An object containing all parameters (see above)
  32551. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32552. * @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)
  32553. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32554. */
  32555. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32556. var _this = this;
  32557. if (ratio === void 0) { ratio = 1.0; }
  32558. _super.call(this, scene.getEngine(), name);
  32559. // Lens effects can be of the following:
  32560. // - chromatic aberration (slight shift of RGB colors)
  32561. // - blur on the edge of the lens
  32562. // - lens distortion
  32563. // - depth-of-field blur & highlights enhancing
  32564. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32565. // - grain effect (noise or custom texture)
  32566. // Two additional texture samplers are needed:
  32567. // - depth map (for depth-of-field)
  32568. // - grain texture
  32569. /**
  32570. * The chromatic aberration PostProcess id in the pipeline
  32571. * @type {string}
  32572. */
  32573. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32574. /**
  32575. * The highlights enhancing PostProcess id in the pipeline
  32576. * @type {string}
  32577. */
  32578. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32579. /**
  32580. * The depth-of-field PostProcess id in the pipeline
  32581. * @type {string}
  32582. */
  32583. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32584. this._scene = scene;
  32585. // Fetch texture samplers
  32586. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32587. if (parameters.grain_texture) {
  32588. this._grainTexture = parameters.grain_texture;
  32589. }
  32590. else {
  32591. this._createGrainTexture();
  32592. }
  32593. // save parameters
  32594. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32595. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32596. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32597. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32598. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32599. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32600. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32601. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32602. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32603. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32604. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32605. // Create effects
  32606. this._createChromaticAberrationPostProcess(ratio);
  32607. this._createHighlightsPostProcess(ratio);
  32608. this._createDepthOfFieldPostProcess(ratio / 4);
  32609. // Set up pipeline
  32610. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32613. if (this._highlightsGain == -1) {
  32614. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32615. }
  32616. // Finish
  32617. scene.postProcessRenderPipelineManager.addPipeline(this);
  32618. if (cameras) {
  32619. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32620. }
  32621. }
  32622. // public methods (self explanatory)
  32623. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32624. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32625. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32626. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32627. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32628. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32629. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32630. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32631. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32632. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32633. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32634. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32635. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32636. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32637. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32638. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32639. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32640. this._highlightsGain = amount;
  32641. };
  32642. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32643. if (this._highlightsGain == -1) {
  32644. this._highlightsGain = 1.0;
  32645. }
  32646. this._highlightsThreshold = amount;
  32647. };
  32648. LensRenderingPipeline.prototype.disableHighlights = function () {
  32649. this._highlightsGain = -1;
  32650. };
  32651. /**
  32652. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32653. */
  32654. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32655. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32656. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32657. this._chromaticAberrationPostProcess = undefined;
  32658. this._highlightsPostProcess = undefined;
  32659. this._depthOfFieldPostProcess = undefined;
  32660. this._grainTexture.dispose();
  32661. if (disableDepthRender)
  32662. this._scene.disableDepthRenderer();
  32663. };
  32664. // colors shifting and distortion
  32665. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32666. var _this = this;
  32667. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32668. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32669. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32670. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32671. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32672. };
  32673. };
  32674. // highlights enhancing
  32675. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32676. var _this = this;
  32677. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32678. this._highlightsPostProcess.onApply = function (effect) {
  32679. effect.setFloat('gain', _this._highlightsGain);
  32680. effect.setFloat('threshold', _this._highlightsThreshold);
  32681. effect.setBool('pentagon', _this._dofPentagon);
  32682. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32683. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32684. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32685. };
  32686. };
  32687. // colors shifting and distortion
  32688. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32689. var _this = this;
  32690. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32691. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32692. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32693. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32694. this._depthOfFieldPostProcess.onApply = function (effect) {
  32695. effect.setTexture("depthSampler", _this._depthTexture);
  32696. effect.setTexture("grainSampler", _this._grainTexture);
  32697. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  32698. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  32699. effect.setFloat('grain_amount', _this._grainAmount);
  32700. effect.setBool('blur_noise', _this._blurNoise);
  32701. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32702. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32703. effect.setFloat('distortion', _this._distortion);
  32704. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  32705. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  32706. effect.setFloat('aperture', _this._dofAperture);
  32707. effect.setFloat('darken', _this._dofDarken);
  32708. effect.setFloat('edge_blur', _this._edgeBlur);
  32709. effect.setBool('highlights', (_this._highlightsGain != -1));
  32710. effect.setFloat('near', _this._scene.activeCamera.minZ);
  32711. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  32712. };
  32713. };
  32714. // creates a black and white random noise texture, 512x512
  32715. LensRenderingPipeline.prototype._createGrainTexture = function () {
  32716. var size = 512;
  32717. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32718. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32719. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32720. var context = this._grainTexture.getContext();
  32721. var rand = function (min, max) {
  32722. return Math.random() * (max - min) + min;
  32723. };
  32724. var value;
  32725. for (var x = 0; x < size; x++) {
  32726. for (var y = 0; y < size; y++) {
  32727. value = Math.floor(rand(0.42, 0.58) * 255);
  32728. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  32729. context.fillRect(x, y, 1, 1);
  32730. }
  32731. }
  32732. this._grainTexture.update(false);
  32733. };
  32734. return LensRenderingPipeline;
  32735. })(BABYLON.PostProcessRenderPipeline);
  32736. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  32737. })(BABYLON || (BABYLON = {}));
  32738. //
  32739. // This post-process allows the modification of rendered colors by using
  32740. // a 'look-up table' (LUT). This effect is also called Color Grading.
  32741. //
  32742. // The object needs to be provided an url to a texture containing the color
  32743. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  32744. // Use an image editing software to tweak the LUT to match your needs.
  32745. //
  32746. // For an example of a color LUT, see here:
  32747. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  32748. // For explanations on color grading, see here:
  32749. // http://udn.epicgames.com/Three/ColorGrading.html
  32750. //
  32751. var BABYLON;
  32752. (function (BABYLON) {
  32753. var ColorCorrectionPostProcess = (function (_super) {
  32754. __extends(ColorCorrectionPostProcess, _super);
  32755. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  32756. var _this = this;
  32757. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  32758. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  32759. this._colorTableTexture.anisotropicFilteringLevel = 1;
  32760. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32761. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32762. this.onApply = function (effect) {
  32763. effect.setTexture("colorTable", _this._colorTableTexture);
  32764. };
  32765. }
  32766. return ColorCorrectionPostProcess;
  32767. })(BABYLON.PostProcess);
  32768. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  32769. })(BABYLON || (BABYLON = {}));
  32770. var BABYLON;
  32771. (function (BABYLON) {
  32772. var AnaglyphFreeCamera = (function (_super) {
  32773. __extends(AnaglyphFreeCamera, _super);
  32774. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  32775. _super.call(this, name, position, scene);
  32776. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32777. }
  32778. return AnaglyphFreeCamera;
  32779. })(BABYLON.FreeCamera);
  32780. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  32781. var AnaglyphArcRotateCamera = (function (_super) {
  32782. __extends(AnaglyphArcRotateCamera, _super);
  32783. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  32784. _super.call(this, name, alpha, beta, radius, target, scene);
  32785. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32786. }
  32787. return AnaglyphArcRotateCamera;
  32788. })(BABYLON.ArcRotateCamera);
  32789. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  32790. var AnaglyphGamepadCamera = (function (_super) {
  32791. __extends(AnaglyphGamepadCamera, _super);
  32792. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  32793. _super.call(this, name, position, scene);
  32794. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32795. }
  32796. return AnaglyphGamepadCamera;
  32797. })(BABYLON.GamepadCamera);
  32798. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  32799. var StereoscopicFreeCamera = (function (_super) {
  32800. __extends(StereoscopicFreeCamera, _super);
  32801. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32802. _super.call(this, name, position, scene);
  32803. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32804. }
  32805. return StereoscopicFreeCamera;
  32806. })(BABYLON.FreeCamera);
  32807. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  32808. var StereoscopicArcRotateCamera = (function (_super) {
  32809. __extends(StereoscopicArcRotateCamera, _super);
  32810. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  32811. _super.call(this, name, alpha, beta, radius, target, scene);
  32812. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32813. }
  32814. return StereoscopicArcRotateCamera;
  32815. })(BABYLON.ArcRotateCamera);
  32816. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  32817. var StereoscopicGamepadCamera = (function (_super) {
  32818. __extends(StereoscopicGamepadCamera, _super);
  32819. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32820. _super.call(this, name, position, scene);
  32821. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32822. }
  32823. return StereoscopicGamepadCamera;
  32824. })(BABYLON.GamepadCamera);
  32825. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  32826. })(BABYLON || (BABYLON = {}));
  32827. var BABYLON;
  32828. (function (BABYLON) {
  32829. var HDRRenderingPipeline = (function (_super) {
  32830. __extends(HDRRenderingPipeline, _super);
  32831. /**
  32832. * @constructor
  32833. * @param {string} name - The rendering pipeline name
  32834. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32835. * @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)
  32836. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  32837. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32838. */
  32839. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  32840. var _this = this;
  32841. if (originalPostProcess === void 0) { originalPostProcess = null; }
  32842. _super.call(this, scene.getEngine(), name);
  32843. /**
  32844. * Public members
  32845. */
  32846. // Gaussian Blur
  32847. /**
  32848. * Gaussian blur coefficient
  32849. * @type {number}
  32850. */
  32851. this.gaussCoeff = 0.3;
  32852. /**
  32853. * Gaussian blur mean
  32854. * @type {number}
  32855. */
  32856. this.gaussMean = 1.0;
  32857. /**
  32858. * Gaussian blur standard deviation
  32859. * @type {number}
  32860. */
  32861. this.gaussStandDev = 0.8;
  32862. // HDR
  32863. /**
  32864. * Exposure, controls the overall intensity of the pipeline
  32865. * @type {number}
  32866. */
  32867. this.exposure = 1.0;
  32868. /**
  32869. * Minimum luminance that the post-process can output. Luminance is >= 0
  32870. * @type {number}
  32871. */
  32872. this.minimumLuminance = 1.0;
  32873. /**
  32874. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  32875. * @type {number}
  32876. */
  32877. this.maximumLuminance = 1e20;
  32878. /**
  32879. * Increase rate for luminance: eye adaptation speed to dark
  32880. * @type {number}
  32881. */
  32882. this.luminanceIncreaserate = 0.5;
  32883. /**
  32884. * Decrease rate for luminance: eye adaptation speed to bright
  32885. * @type {number}
  32886. */
  32887. this.luminanceDecreaseRate = 0.5;
  32888. // Bright pass
  32889. /**
  32890. * Minimum luminance needed to compute HDR
  32891. * @type {number}
  32892. */
  32893. this.brightThreshold = 0.8;
  32894. this._needUpdate = true;
  32895. this._scene = scene;
  32896. // Bright pass
  32897. this._createBrightPassPostProcess(scene, ratio);
  32898. // Down sample X4
  32899. this._createDownSampleX4PostProcess(scene, ratio);
  32900. // Create gaussian blur post-processes
  32901. this._createGaussianBlurPostProcess(scene, ratio);
  32902. // Texture adder
  32903. this._createTextureAdderPostProcess(scene, ratio);
  32904. // Luminance generator
  32905. this._createLuminanceGeneratorPostProcess(scene);
  32906. // HDR
  32907. this._createHDRPostProcess(scene, ratio);
  32908. // Pass postprocess
  32909. if (originalPostProcess === null) {
  32910. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32911. }
  32912. else {
  32913. this._originalPostProcess = originalPostProcess;
  32914. }
  32915. // Configure pipeline
  32916. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  32917. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  32918. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  32919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  32920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  32921. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  32922. var addDownSamplerPostProcess = function (id) {
  32923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  32924. };
  32925. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  32926. addDownSamplerPostProcess(i);
  32927. }
  32928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  32929. // Finish
  32930. scene.postProcessRenderPipelineManager.addPipeline(this);
  32931. if (cameras !== null) {
  32932. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32933. }
  32934. this.update();
  32935. }
  32936. /**
  32937. * Tells the pipeline to update its post-processes
  32938. */
  32939. HDRRenderingPipeline.prototype.update = function () {
  32940. this._needUpdate = true;
  32941. };
  32942. /**
  32943. * Returns the current calculated luminance
  32944. */
  32945. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  32946. return this._hdrCurrentLuminance;
  32947. };
  32948. /**
  32949. * Returns the currently drawn luminance
  32950. */
  32951. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  32952. return this._hdrOutputLuminance;
  32953. };
  32954. /**
  32955. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  32956. */
  32957. HDRRenderingPipeline.prototype.dispose = function () {
  32958. this._originalPostProcess = undefined;
  32959. this._brightPassPostProcess = undefined;
  32960. this._downSampleX4PostProcess = undefined;
  32961. this._guassianBlurHPostProcess = undefined;
  32962. this._guassianBlurVPostProcess = undefined;
  32963. this._textureAdderPostProcess = undefined;
  32964. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  32965. this._downSamplePostProcesses[i] = undefined;
  32966. }
  32967. this._hdrPostProcess = undefined;
  32968. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32969. };
  32970. /**
  32971. * Creates the HDR post-process and computes the luminance adaptation
  32972. */
  32973. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  32974. var _this = this;
  32975. var hdrLastLuminance = 0.0;
  32976. this._hdrOutputLuminance = -1.0;
  32977. this._hdrCurrentLuminance = 1.0;
  32978. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  32979. this._hdrPostProcess.onApply = function (effect) {
  32980. if (_this._hdrOutputLuminance < 0.0) {
  32981. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  32982. }
  32983. else {
  32984. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  32985. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  32986. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  32987. }
  32988. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  32989. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  32990. }
  32991. else {
  32992. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  32993. }
  32994. }
  32995. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  32996. hdrLastLuminance += scene.getEngine().getDeltaTime();
  32997. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  32998. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  32999. effect.setFloat("exposure", _this.exposure);
  33000. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33001. _this._needUpdate = false;
  33002. };
  33003. };
  33004. /**
  33005. * Texture Adder post-process
  33006. */
  33007. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33008. var _this = this;
  33009. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33010. this._textureAdderPostProcess.onApply = function (effect) {
  33011. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33012. };
  33013. };
  33014. /**
  33015. * Down sample X4 post-process
  33016. */
  33017. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33018. var _this = this;
  33019. var downSampleX4Offsets = new Array(32);
  33020. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33021. this._downSampleX4PostProcess.onApply = function (effect) {
  33022. if (_this._needUpdate) {
  33023. var id = 0;
  33024. for (var i = -2; i < 2; i++) {
  33025. for (var j = -2; j < 2; j++) {
  33026. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33027. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33028. id += 2;
  33029. }
  33030. }
  33031. }
  33032. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33033. };
  33034. };
  33035. /**
  33036. * Bright pass post-process
  33037. */
  33038. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33039. var _this = this;
  33040. var brightOffsets = new Array(8);
  33041. var brightPassCallback = function (effect) {
  33042. if (_this._needUpdate) {
  33043. var sU = (1.0 / _this._brightPassPostProcess.width);
  33044. var sV = (1.0 / _this._brightPassPostProcess.height);
  33045. brightOffsets[0] = -0.5 * sU;
  33046. brightOffsets[1] = 0.5 * sV;
  33047. brightOffsets[2] = 0.5 * sU;
  33048. brightOffsets[3] = 0.5 * sV;
  33049. brightOffsets[4] = -0.5 * sU;
  33050. brightOffsets[5] = -0.5 * sV;
  33051. brightOffsets[6] = 0.5 * sU;
  33052. brightOffsets[7] = -0.5 * sV;
  33053. }
  33054. effect.setArray2("dsOffsets", brightOffsets);
  33055. effect.setFloat("brightThreshold", _this.brightThreshold);
  33056. };
  33057. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33058. this._brightPassPostProcess.onApply = brightPassCallback;
  33059. };
  33060. /**
  33061. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33062. */
  33063. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33064. var _this = this;
  33065. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33066. var luminanceOffsets = new Array(8);
  33067. var downSampleOffsets = new Array(18);
  33068. var halfDestPixelSize;
  33069. this._downSamplePostProcesses = new Array(lumSteps);
  33070. // Utils for luminance
  33071. var luminanceUpdateSourceOffsets = function (width, height) {
  33072. var sU = (1.0 / width);
  33073. var sV = (1.0 / height);
  33074. luminanceOffsets[0] = -0.5 * sU;
  33075. luminanceOffsets[1] = 0.5 * sV;
  33076. luminanceOffsets[2] = 0.5 * sU;
  33077. luminanceOffsets[3] = 0.5 * sV;
  33078. luminanceOffsets[4] = -0.5 * sU;
  33079. luminanceOffsets[5] = -0.5 * sV;
  33080. luminanceOffsets[6] = 0.5 * sU;
  33081. luminanceOffsets[7] = -0.5 * sV;
  33082. };
  33083. var luminanceUpdateDestOffsets = function (width, height) {
  33084. var id = 0;
  33085. for (var x = -1; x < 2; x++) {
  33086. for (var y = -1; y < 2; y++) {
  33087. downSampleOffsets[id] = (x) / width;
  33088. downSampleOffsets[id + 1] = (y) / height;
  33089. id += 2;
  33090. }
  33091. }
  33092. };
  33093. // Luminance callback
  33094. var luminanceCallback = function (effect) {
  33095. if (_this._needUpdate) {
  33096. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33097. }
  33098. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33099. effect.setArray2("lumOffsets", luminanceOffsets);
  33100. };
  33101. // Down sample callbacks
  33102. var downSampleCallback = function (indice) {
  33103. var i = indice;
  33104. return function (effect) {
  33105. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33106. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33107. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33108. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33109. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33110. effect.setArray2("dsOffsets", downSampleOffsets);
  33111. };
  33112. };
  33113. var downSampleAfterRenderCallback = function (effect) {
  33114. // Unpack result
  33115. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33116. 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);
  33117. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33118. };
  33119. // Create luminance post-process
  33120. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33121. 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);
  33122. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33123. // Create down sample post-processes
  33124. for (var i = lumSteps - 2; i >= 0; i--) {
  33125. var length = Math.pow(3, i);
  33126. ratio = { width: length, height: length };
  33127. var defines = "#define DOWN_SAMPLE\n";
  33128. if (i === 0) {
  33129. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33130. }
  33131. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33132. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33133. if (i === 0) {
  33134. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33135. }
  33136. }
  33137. };
  33138. /**
  33139. * Gaussian blur post-processes. Horizontal and Vertical
  33140. */
  33141. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33142. var _this = this;
  33143. var blurOffsetsW = new Array(9);
  33144. var blurOffsetsH = new Array(9);
  33145. var blurWeights = new Array(9);
  33146. var uniforms = ["blurOffsets", "blurWeights"];
  33147. // Utils for gaussian blur
  33148. var calculateBlurOffsets = function (height) {
  33149. var lastOutputDimensions = {
  33150. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33151. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33152. };
  33153. for (var i = 0; i < 9; i++) {
  33154. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33155. if (height) {
  33156. blurOffsetsH[i] = value;
  33157. }
  33158. else {
  33159. blurOffsetsW[i] = value;
  33160. }
  33161. }
  33162. };
  33163. var calculateWeights = function () {
  33164. var x = 0.0;
  33165. for (var i = 0; i < 9; i++) {
  33166. x = (i - 4.0) / 4.0;
  33167. 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));
  33168. }
  33169. };
  33170. // Callback
  33171. var gaussianBlurCallback = function (height) {
  33172. return function (effect) {
  33173. if (_this._needUpdate) {
  33174. calculateWeights();
  33175. calculateBlurOffsets(height);
  33176. }
  33177. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33178. effect.setArray("blurWeights", blurWeights);
  33179. };
  33180. };
  33181. // Create horizontal gaussian blur post-processes
  33182. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33183. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33184. // Create vertical gaussian blur post-process
  33185. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33186. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33187. };
  33188. // Luminance generator
  33189. HDRRenderingPipeline.LUM_STEPS = 6;
  33190. return HDRRenderingPipeline;
  33191. })(BABYLON.PostProcessRenderPipeline);
  33192. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33193. })(BABYLON || (BABYLON = {}));
  33194. 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\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)\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 visibility;\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)\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 1.0 - ChebychevInequality(moments, depth.z, bias);\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);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\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);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\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);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\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);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\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\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).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}","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}","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}"};
  33195. 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 o=function(){function o(t,o,i){void 0===t&&(t=0),void 0===o&&(o=0),void 0===i&&(i=0),this.r=t,this.g=o,this.b=i}return o.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},o.prototype.toArray=function(t,o){return void 0===o&&(o=0),t[o]=this.r,t[o+1]=this.g,t[o+2]=this.b,this},o.prototype.toColor4=function(t){return void 0===t&&(t=1),new i(this.r,this.g,this.b,t)},o.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},o.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},o.prototype.multiply=function(t){return new o(this.r*t.r,this.g*t.g,this.b*t.b)},o.prototype.multiplyToRef=function(t,o){return o.r=this.r*t.r,o.g=this.g*t.g,o.b=this.b*t.b,this},o.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},o.prototype.equalsFloats=function(t,o,i){return this.r===t&&this.g===o&&this.b===i},o.prototype.scale=function(t){return new o(this.r*t,this.g*t,this.b*t)},o.prototype.scaleToRef=function(t,o){return o.r=this.r*t,o.g=this.g*t,o.b=this.b*t,this},o.prototype.add=function(t){return new o(this.r+t.r,this.g+t.g,this.b+t.b)},o.prototype.addToRef=function(t,o){return o.r=this.r+t.r,o.g=this.g+t.g,o.b=this.b+t.b,this},o.prototype.subtract=function(t){return new o(this.r-t.r,this.g-t.g,this.b-t.b)},o.prototype.subtractToRef=function(t,o){return o.r=this.r-t.r,o.g=this.g-t.g,o.b=this.b-t.b,this},o.prototype.clone=function(){return new o(this.r,this.g,this.b)},o.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},o.prototype.copyFromFloats=function(t,o,i){return this.r=t,this.g=o,this.b=i,this},o.prototype.toHexString=function(){var o=255*this.r|0,i=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(o)+t.Tools.ToHex(i)+t.Tools.ToHex(r)},o.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!=i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new o(0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return o.FromInts(r,n,s)},o.FromArray=function(t,i){return void 0===i&&(i=0),new o(t[i],t[i+1],t[i+2])},o.FromInts=function(t,i,r){return new o(t/255,i/255,r/255)},o.Lerp=function(t,i,r){var n=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new o(n,s,e)},o.Red=function(){return new o(1,0,0)},o.Green=function(){return new o(0,1,0)},o.Blue=function(){return new o(0,0,1)},o.Black=function(){return new o(0,0,0)},o.White=function(){return new o(1,1,1)},o.Purple=function(){return new o(.5,0,.5)},o.Magenta=function(){return new o(1,0,1)},o.Yellow=function(){return new o(1,1,0)},o.Gray=function(){return new o(.5,.5,.5)},o}();t.Color3=o;var i=function(){function o(t,o,i,r){this.r=t,this.g=o,this.b=i,this.a=r}return o.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},o.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},o.prototype.toArray=function(t,o){return void 0===o&&(o=0),t[o]=this.r,t[o+1]=this.g,t[o+2]=this.b,t[o+3]=this.a,this},o.prototype.add=function(t){return new o(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},o.prototype.subtract=function(t){return new o(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},o.prototype.subtractToRef=function(t,o){return o.r=this.r-t.r,o.g=this.g-t.g,o.b=this.b-t.b,o.a=this.a-t.a,this},o.prototype.scale=function(t){return new o(this.r*t,this.g*t,this.b*t,this.a*t)},o.prototype.scaleToRef=function(t,o){return o.r=this.r*t,o.g=this.g*t,o.b=this.b*t,o.a=this.a*t,this},o.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},o.prototype.clone=function(){return new o(this.r,this.g,this.b,this.a)},o.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},o.prototype.toHexString=function(){var o=255*this.r|0,i=255*this.g|0,r=255*this.b|0,n=255*this.a|0;return\"#\"+t.Tools.ToHex(o)+t.Tools.ToHex(i)+t.Tools.ToHex(r)+t.Tools.ToHex(n)},o.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!=i.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new o(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return o.FromInts(r,n,s,e)},o.Lerp=function(t,i,r){var n=new o(0,0,0,0);return o.LerpToRef(t,i,r,n),n},o.LerpToRef=function(t,o,i,r){r.r=t.r+(o.r-t.r)*i,r.g=t.g+(o.g-t.g)*i,r.b=t.b+(o.b-t.b)*i,r.a=t.a+(o.a-t.a)*i},o.FromArray=function(t,i){return void 0===i&&(i=0),new o(t[i],t[i+1],t[i+2],t[i+3])},o.FromInts=function(t,i,r,n){return new o(t/255,i/255,r/255,n/255)},o}();t.Color4=i;var r=function(){function o(t,o){this.x=t,this.y=o}return o.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},o.prototype.toArray=function(t,o){return void 0===o&&(o=0),t[o]=this.x,t[o+1]=this.y,this},o.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},o.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},o.prototype.copyFromFloats=function(t,o){return this.x=t,this.y=o,this},o.prototype.add=function(t){return new o(this.x+t.x,this.y+t.y)},o.prototype.addVector3=function(t){return new o(this.x+t.x,this.y+t.y)},o.prototype.subtract=function(t){return new o(this.x-t.x,this.y-t.y)},o.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},o.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},o.prototype.multiply=function(t){return new o(this.x*t.x,this.y*t.y)},o.prototype.multiplyToRef=function(t,o){return o.x=this.x*t.x,o.y=this.y*t.y,this},o.prototype.multiplyByFloats=function(t,i){return new o(this.x*t,this.y*i)},o.prototype.divide=function(t){return new o(this.x/t.x,this.y/t.y)},o.prototype.divideToRef=function(t,o){return o.x=this.x/t.x,o.y=this.y/t.y,this},o.prototype.negate=function(){return new o(-this.x,-this.y)},o.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},o.prototype.scale=function(t){return new o(this.x*t,this.y*t)},o.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},o.prototype.equalsWithEpsilon=function(o,i){return void 0===i&&(i=t.Engine.Epsilon),o&&t.Tools.WithinEpsilon(this.x,o.x,i)&&t.Tools.WithinEpsilon(this.y,o.y,i)},o.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},o.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},o.prototype.normalize=function(){var t=this.length();if(0===t)return this;var o=1/t;return this.x*=o,this.y*=o,this},o.prototype.clone=function(){return new o(this.x,this.y)},o.Zero=function(){return new o(0,0)},o.FromArray=function(t,i){return void 0===i&&(i=0),new o(t[i],t[i+1])},o.FromArrayToRef=function(t,o,i){i.x=t[o],i.y=t[o+1]},o.CatmullRom=function(t,i,r,n,s){var e=s*s,a=s*e,h=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-n.x)*e+(-t.x+3*i.x-3*r.x+n.x)*a),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-n.y)*e+(-t.y+3*i.y-3*r.y+n.y)*a);return new o(h,u)},o.Clamp=function(t,i,r){var n=t.x;n=n>r.x?r.x:n,n=n<i.x?i.x:n;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new o(n,s)},o.Hermite=function(t,i,r,n,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+r.x*u+i.x*l+n.x*m,x=t.y*h+r.y*u+i.y*l+n.y*m;return new o(f,x)},o.Lerp=function(t,i,r){var n=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new o(n,s)},o.Dot=function(t,o){return t.x*o.x+t.y*o.y},o.Normalize=function(t){var o=t.clone();return o.normalize(),o},o.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,n=t.y<i.y?t.y:i.y;return new o(r,n)},o.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,n=t.y>i.y?t.y:i.y;return new o(r,n)},o.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],n=t.x*i.m[1]+t.y*i.m[5];return new o(r,n)},o.Distance=function(t,i){return Math.sqrt(o.DistanceSquared(t,i))},o.DistanceSquared=function(t,o){var i=t.x-o.x,r=t.y-o.y;return i*i+r*r},o}();t.Vector2=r;var n=function(){function o(t,o,i){this.x=t,this.y=o,this.z=i}return o.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},o.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},o.prototype.toArray=function(t,o){return void 0===o&&(o=0),t[o]=this.x,t[o+1]=this.y,t[o+2]=this.z,this},o.prototype.toQuaternion=function(){var t=new e(0,0,0,1),o=Math.cos(.5*(this.x+this.z)),i=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),n=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=r*a,t.y=-n*a,t.z=i*s,t.w=o*s,t},o.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},o.prototype.add=function(t){return new o(this.x+t.x,this.y+t.y,this.z+t.z)},o.prototype.addToRef=function(t,o){return o.x=this.x+t.x,o.y=this.y+t.y,o.z=this.z+t.z,this},o.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},o.prototype.subtract=function(t){return new o(this.x-t.x,this.y-t.y,this.z-t.z)},o.prototype.subtractToRef=function(t,o){return o.x=this.x-t.x,o.y=this.y-t.y,o.z=this.z-t.z,this},o.prototype.subtractFromFloats=function(t,i,r){return new o(this.x-t,this.y-i,this.z-r)},o.prototype.subtractFromFloatsToRef=function(t,o,i,r){return r.x=this.x-t,r.y=this.y-o,r.z=this.z-i,this},o.prototype.negate=function(){return new o(-this.x,-this.y,-this.z)},o.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},o.prototype.scale=function(t){return new o(this.x*t,this.y*t,this.z*t)},o.prototype.scaleToRef=function(t,o){o.x=this.x*t,o.y=this.y*t,o.z=this.z*t},o.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},o.prototype.equalsWithEpsilon=function(o,i){return void 0===i&&(i=t.Engine.Epsilon),o&&t.Tools.WithinEpsilon(this.x,o.x,i)&&t.Tools.WithinEpsilon(this.y,o.y,i)&&t.Tools.WithinEpsilon(this.z,o.z,i)},o.prototype.equalsToFloats=function(t,o,i){return this.x===t&&this.y===o&&this.z===i},o.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},o.prototype.multiply=function(t){return new o(this.x*t.x,this.y*t.y,this.z*t.z)},o.prototype.multiplyToRef=function(t,o){return o.x=this.x*t.x,o.y=this.y*t.y,o.z=this.z*t.z,this},o.prototype.multiplyByFloats=function(t,i,r){return new o(this.x*t,this.y*i,this.z*r)},o.prototype.divide=function(t){return new o(this.x/t.x,this.y/t.y,this.z/t.z)},o.prototype.divideToRef=function(t,o){return o.x=this.x/t.x,o.y=this.y/t.y,o.z=this.z/t.z,this},o.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},o.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},o.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},o.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},o.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var o=1/t;return this.x*=o,this.y*=o,this.z*=o,this},o.prototype.clone=function(){return new o(this.x,this.y,this.z)},o.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},o.prototype.copyFromFloats=function(t,o,i){return this.x=t,this.y=o,this.z=i,this},o.GetClipFactor=function(t,i,r,n){var s=o.Dot(t,r)-n,e=o.Dot(i,r)-n,a=s/(s-e);return a},o.FromArray=function(t,i){return i||(i=0),new o(t[i],t[i+1],t[i+2])},o.FromFloatArray=function(t,i){return i||(i=0),new o(t[i],t[i+1],t[i+2])},o.FromArrayToRef=function(t,o,i){i.x=t[o],i.y=t[o+1],i.z=t[o+2]},o.FromFloatArrayToRef=function(t,o,i){i.x=t[o],i.y=t[o+1],i.z=t[o+2]},o.FromFloatsToRef=function(t,o,i,r){r.x=t,r.y=o,r.z=i},o.Zero=function(){return new o(0,0,0)},o.Up=function(){return new o(0,1,0)},o.TransformCoordinates=function(t,i){var r=o.Zero();return o.TransformCoordinatesToRef(t,i,r),r},o.TransformCoordinatesToRef=function(t,o,i){var r=t.x*o.m[0]+t.y*o.m[4]+t.z*o.m[8]+o.m[12],n=t.x*o.m[1]+t.y*o.m[5]+t.z*o.m[9]+o.m[13],s=t.x*o.m[2]+t.y*o.m[6]+t.z*o.m[10]+o.m[14],e=t.x*o.m[3]+t.y*o.m[7]+t.z*o.m[11]+o.m[15];i.x=r/e,i.y=n/e,i.z=s/e},o.TransformCoordinatesFromFloatsToRef=function(t,o,i,r,n){var s=t*r.m[0]+o*r.m[4]+i*r.m[8]+r.m[12],e=t*r.m[1]+o*r.m[5]+i*r.m[9]+r.m[13],a=t*r.m[2]+o*r.m[6]+i*r.m[10]+r.m[14],h=t*r.m[3]+o*r.m[7]+i*r.m[11]+r.m[15];n.x=s/h,n.y=e/h,n.z=a/h},o.TransformCoordinatesToRefSIMD=function(t,o,i){var r=SIMD.float32x4.loadXYZ(t._data,0),n=SIMD.float32x4.load(o.m,0),s=SIMD.float32x4.load(o.m,4),e=SIMD.float32x4.load(o.m,8),a=SIMD.float32x4.load(o.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,0,0,0,0),n),SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(i._data,0,h)},o.TransformCoordinatesFromFloatsToRefSIMD=function(t,o,i,r,n){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(o),a=SIMD.float32x4.splat(i),h=SIMD.float32x4.load(r.m,0),u=SIMD.float32x4.load(r.m,4),l=SIMD.float32x4.load(r.m,8),m=SIMD.float32x4.load(r.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(n._data,0,f)},o.TransformNormal=function(t,i){var r=o.Zero();return o.TransformNormalToRef(t,i,r),r},o.TransformNormalToRef=function(t,o,i){i.x=t.x*o.m[0]+t.y*o.m[4]+t.z*o.m[8],i.y=t.x*o.m[1]+t.y*o.m[5]+t.z*o.m[9],i.z=t.x*o.m[2]+t.y*o.m[6]+t.z*o.m[10]},o.TransformNormalFromFloatsToRef=function(t,o,i,r,n){n.x=t*r.m[0]+o*r.m[4]+i*r.m[8],n.y=t*r.m[1]+o*r.m[5]+i*r.m[9],n.z=t*r.m[2]+o*r.m[6]+i*r.m[10]},o.CatmullRom=function(t,i,r,n,s){var e=s*s,a=s*e,h=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-n.x)*e+(-t.x+3*i.x-3*r.x+n.x)*a),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-n.y)*e+(-t.y+3*i.y-3*r.y+n.y)*a),l=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-n.z)*e+(-t.z+3*i.z-3*r.z+n.z)*a);return new o(h,u,l)},o.Clamp=function(t,i,r){var n=t.x;n=n>r.x?r.x:n,n=n<i.x?i.x:n;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new o(n,s,e)},o.Hermite=function(t,i,r,n,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+r.x*u+i.x*l+n.x*m,x=t.y*h+r.y*u+i.y*l+n.y*m,y=t.z*h+r.z*u+i.z*l+n.z*m;return new o(f,x,y)},o.Lerp=function(t,i,r){var n=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new o(n,s,e)},o.Dot=function(t,o){return t.x*o.x+t.y*o.y+t.z*o.z},o.Cross=function(t,i){var r=o.Zero();return o.CrossToRef(t,i,r),r},o.CrossToRef=function(t,o,i){i.x=t.y*o.z-t.z*o.y,i.y=t.z*o.x-t.x*o.z,i.z=t.x*o.y-t.y*o.x},o.Normalize=function(t){var i=o.Zero();return o.NormalizeToRef(t,i),i},o.NormalizeToRef=function(t,o){o.copyFrom(t),o.normalize()},o.Project=function(t,i,r,n){var s=n.width,e=n.height,h=n.x,u=n.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=i.multiply(r).multiply(l);return o.TransformCoordinates(t,m)},o.UnprojectFromTransform=function(i,r,n,s,e){var a=s.multiply(e);a.invert(),i.x=i.x/r*2-1,i.y=-(i.y/n*2-1);var h=o.TransformCoordinates(i,a),u=i.x*a.m[3]+i.y*a.m[7]+i.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},o.Unproject=function(i,r,n,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),i.x=i.x/r*2-1,i.y=-(i.y/n*2-1);var u=o.TransformCoordinates(i,h),l=i.x*h.m[3]+i.y*h.m[7]+i.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(l,1)&&(u=u.scale(1/l)),u},o.Minimize=function(t,o){var i=t.clone();return i.MinimizeInPlace(o),i},o.Maximize=function(t,o){var i=t.clone();return i.MaximizeInPlace(o),i},o.Distance=function(t,i){return Math.sqrt(o.DistanceSquared(t,i))},o.DistanceSquared=function(t,o){var i=t.x-o.x,r=t.y-o.y,n=t.z-o.z;return i*i+r*r+n*n},o.Center=function(t,o){var i=t.add(o);return i.scaleInPlace(.5),i},o.RotationFromAxis=function(t,i,r){var n,s,e,a=o.Normalize(t),h=(o.Normalize(i),o.Normalize(r)),u=f.X,l=f.Y,m=(f.Z,0),x=0,y=0,c=0,p=0,z=0,M=0,w=-1,d=(Math.PI,0),I=0;0==h.z?z=1:0==h.x?c=1:(M=h.z/h.x,c=-M*Math.sqrt(1/(1+M*M)),z=Math.sqrt(1/(1+M*M))),s=new o(c,p,z),e=o.Cross(h,s),n=o.Cross(a,s),o.Dot(h,n)<0&&(w=1),I=o.Dot(a,s),y=Math.acos(I)*w,o.Dot(s,u)<0&&(y=Math.PI+y,s=s.scaleInPlace(-1),e=e.scaleInPlace(-1),d++);var D,S;return c=0,p=0,z=0,w=-1,0==h.z?c=1:(M=s.z/s.x,c=-M*Math.sqrt(1/(1+M*M)),z=Math.sqrt(1/(1+M*M))),D=new o(c,p,z),S=o.Cross(D,s),n=o.Cross(h,D),o.Dot(s,n)<0&&(w=1),I=o.Dot(h,D),x=Math.acos(I)*w,o.Dot(S,l)<0&&(x=Math.PI+x,S=S.scaleInPlace(-1),D=D.scaleInPlace(-1),d++),w=-1,n=o.Cross(u,s),o.Dot(n,l)<0&&(w=1),I=o.Dot(s,u),m=-Math.acos(I)*w,0>I&&2>d&&(m=Math.PI+m),new o(x,m,y)},o}();t.Vector3=n;var s=function(){function o(t,o,i,r){this.x=t,this.y=o,this.z=i,this.w=r}return o.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},o.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},o.prototype.toArray=function(t,o){return void 0===o&&(o=0),t[o]=this.x,t[o+1]=this.y,t[o+2]=this.z,t[o+3]=this.w,this},o.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},o.prototype.add=function(t){return new o(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},o.prototype.addToRef=function(t,o){return o.x=this.x+t.x,o.y=this.y+t.y,o.z=this.z+t.z,o.w=this.w+t.w,this},o.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},o.prototype.subtract=function(t){return new o(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},o.prototype.subtractToRef=function(t,o){return o.x=this.x-t.x,o.y=this.y-t.y,o.z=this.z-t.z,o.w=this.w-t.w,this},o.prototype.subtractFromFloats=function(t,i,r,n){return new o(this.x-t,this.y-i,this.z-r,this.w-n)},o.prototype.subtractFromFloatsToRef=function(t,o,i,r,n){return n.x=this.x-t,n.y=this.y-o,n.z=this.z-i,n.w=this.w-r,this},o.prototype.negate=function(){return new o(-this.x,-this.y,-this.z,-this.w)},o.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},o.prototype.scale=function(t){return new o(this.x*t,this.y*t,this.z*t,this.w*t)},o.prototype.scaleToRef=function(t,o){o.x=this.x*t,o.y=this.y*t,o.z=this.z*t,o.w=this.w*t},o.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},o.prototype.equalsWithEpsilon=function(o,i){return void 0===i&&(i=t.Engine.Epsilon),o&&t.Tools.WithinEpsilon(this.x,o.x,i)&&t.Tools.WithinEpsilon(this.y,o.y,i)&&t.Tools.WithinEpsilon(this.z,o.z,i)&&t.Tools.WithinEpsilon(this.w,o.w,i)},o.prototype.equalsToFloats=function(t,o,i,r){return this.x===t&&this.y===o&&this.z===i&&this.w===r},o.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},o.prototype.multiply=function(t){return new o(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},o.prototype.multiplyToRef=function(t,o){return o.x=this.x*t.x,o.y=this.y*t.y,o.z=this.z*t.z,o.w=this.w*t.w,this},o.prototype.multiplyByFloats=function(t,i,r,n){return new o(this.x*t,this.y*i,this.z*r,this.w*n)},o.prototype.divide=function(t){return new o(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},o.prototype.divideToRef=function(t,o){return o.x=this.x/t.x,o.y=this.y/t.y,o.z=this.z/t.z,o.w=this.w/t.w,this},o.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},o.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},o.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},o.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},o.prototype.normalize=function(){var t=this.length();if(0===t)return this;var o=1/t;return this.x*=o,this.y*=o,this.z*=o,this.w*=o,this},o.prototype.clone=function(){return new o(this.x,this.y,this.z,this.w)},o.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},o.prototype.copyFromFloats=function(t,o,i,r){return this.x=t,this.y=o,this.z=i,this.w=r,this},o.FromArray=function(t,i){return i||(i=0),new o(t[i],t[i+1],t[i+2],t[i+3])},o.FromArrayToRef=function(t,o,i){i.x=t[o],i.y=t[o+1],i.z=t[o+2],i.w=t[o+3]},o.FromFloatArrayToRef=function(t,o,i){i.x=t[o],i.y=t[o+1],i.z=t[o+2],i.w=t[o+3]},o.FromFloatsToRef=function(t,o,i,r,n){n.x=t,n.y=o,n.z=i,n.w=r},o.Zero=function(){return new o(0,0,0,0)},o.Normalize=function(t){var i=o.Zero();return o.NormalizeToRef(t,i),i},o.NormalizeToRef=function(t,o){o.copyFrom(t),o.normalize()},o.Minimize=function(t,o){var i=t.clone();return i.MinimizeInPlace(o),i},o.Maximize=function(t,o){var i=t.clone();return i.MaximizeInPlace(o),i},o.Distance=function(t,i){return Math.sqrt(o.DistanceSquared(t,i))},o.DistanceSquared=function(t,o){var i=t.x-o.x,r=t.y-o.y,n=t.z-o.z,s=t.w-o.w;return i*i+r*r+n*n+s*s},o.Center=function(t,o){var i=t.add(o);return i.scaleInPlace(.5),i},o}();t.Vector4=s;var e=function(){function t(t,o,i,r){void 0===t&&(t=0),void 0===o&&(o=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=t,this.y=o,this.z=i,this.w=r}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,o,i,r){return this.x=t,this.y=o,this.z=i,this.w=r,this},t.prototype.add=function(o){return new t(this.x+o.x,this.y+o.y,this.z+o.z,this.w+o.w)},t.prototype.subtract=function(o){return new t(this.x-o.x,this.y-o.y,this.z-o.z,this.w-o.w)},t.prototype.scale=function(o){return new t(this.x*o,this.y*o,this.z*o,this.w*o)},t.prototype.multiply=function(o){var i=new t(0,0,0,1);return this.multiplyToRef(o,i),i},t.prototype.multiplyToRef=function(t,o){var i=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,n=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 o.copyFromFloats(i,r,n,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=n.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var o=this.x,i=this.y,r=this.z,n=this.w,s=o*i,e=o*r,a=n*i,h=n*r,u=n*o,l=i*r,m=o*o,f=i*i,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-r*r)):(t.x=Math.atan2(s-h,.5-f-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var o=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=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*(i+r),t.m[1]=2*(n+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(n-s),t.m[5]=1-2*(r+o),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*(i+o),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(o){return t.FromRotationMatrixToRef(o,this),this},t.FromRotationMatrix=function(o){var i=new t;return t.FromRotationMatrixToRef(o,i),i},t.FromRotationMatrixToRef=function(t,o){var i,r=t.m,n=r[0],s=r[4],e=r[8],a=r[1],h=r[5],u=r[9],l=r[2],m=r[6],f=r[10],x=n+h+f;x>0?(i=.5/Math.sqrt(x+1),o.w=.25/i,o.x=(m-u)*i,o.y=(e-l)*i,o.z=(a-s)*i):n>h&&n>f?(i=2*Math.sqrt(1+n-h-f),o.w=(m-u)/i,o.x=.25*i,o.y=(s+a)/i,o.z=(e+l)/i):h>f?(i=2*Math.sqrt(1+h-n-f),o.w=(e-l)/i,o.x=(s+a)/i,o.y=.25*i,o.z=(u+m)/i):(i=2*Math.sqrt(1+f-n-h),o.w=(a-s)/i,o.x=(e+l)/i,o.y=(u+m)/i,o.z=.25*i)},t.Inverse=function(o){return new t(-o.x,-o.y,-o.z,o.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(o,i){var r=new t,n=Math.sin(i/2);return r.w=Math.cos(i/2),r.x=o.x*n,r.y=o.y*n,r.z=o.z*n,r},t.FromArray=function(o,i){return i||(i=0),new t(o[i],o[i+1],o[i+2],o[i+3])},t.RotationYawPitchRoll=function(o,i,r){var n=new t;return t.RotationYawPitchRollToRef(o,i,r,n),n},t.RotationYawPitchRollToRef=function(t,o,i,r){var n=.5*i,s=.5*o,e=.5*t,a=Math.sin(n),h=Math.cos(n),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);r.x=f*u*h+m*l*a,r.y=m*l*h-f*u*a,r.z=f*l*a-m*u*h,r.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(o,i,r){var n=new t;return t.RotationAlphaBetaGammaToRef(o,i,r,n),n},t.RotationAlphaBetaGammaToRef=function(t,o,i,r){var n=.5*(i+t),s=.5*(i-t),e=.5*o;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(n)*Math.cos(e),r.w=Math.cos(n)*Math.cos(e)},t.Slerp=function(o,i,r){var n,s,e=r,a=o.x*i.x+o.y*i.y+o.z*i.z+o.w*i.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,n=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,n=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*o.x+n*i.x,s*o.y+n*i.y,s*o.z+n*i.z,s*o.w+n*i.w)},t}();t.Quaternion=e;var a=function(){function o(){this.m=new Float32Array(16)}return o.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},o.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],o=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=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]*o+this.m[7]*i)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*o-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*s)},o.prototype.toArray=function(){return this.m},o.prototype.asArray=function(){return this.toArray()},o.prototype.invert=function(){return this.invertToRef(this),this},o.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},o.prototype.add=function(t){var i=new o;return this.addToRef(t,i),i},o.prototype.addToRef=function(t,o){for(var i=0;16>i;i++)o.m[i]=this.m[i]+t.m[i];return this},o.prototype.addToSelf=function(t){for(var o=0;16>o;o++)this.m[o]+=t.m[o];return this},o.prototype.invertToRef=function(t){var o=this.m[0],i=this.m[1],r=this.m[2],n=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/(o*S+i*v+r*g+n*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,L=a*f-h*m,q=e*f-h*l,E=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,N=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]=-(i*z-r*M+n*w)*R,t.m[5]=(o*z-r*d+n*I)*R,t.m[9]=-(o*M-i*d+n*D)*R,t.m[13]=(o*w-i*I+r*D)*R,t.m[2]=(i*_-r*b+n*F)*R,t.m[6]=-(o*_-r*A+n*P)*R,t.m[10]=(o*b-i*A+n*C)*R,t.m[14]=-(o*F-i*P+r*C)*R,t.m[3]=-(i*L-r*q+n*E)*R,t.m[7]=(o*L-r*Z+n*H)*R,t.m[11]=-(o*q-i*Z+n*N)*R,t.m[15]=(o*E-i*H+r*N)*R,this},o.prototype.invertToRefSIMD=function(t){var o,i,r,n,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),i=SIMD.float32x4.shuffle(c,p,0,1,4,5),o=SIMD.float32x4.shuffle(s,i,0,2,4,6),i=SIMD.float32x4.shuffle(i,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),n=SIMD.float32x4.shuffle(c,p,2,3,6,7),r=SIMD.float32x4.shuffle(s,n,0,2,4,6),n=SIMD.float32x4.shuffle(n,s,1,3,5,7),s=SIMD.float32x4.mul(r,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(i,s),a=SIMD.float32x4.mul(o,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),u=SIMD.float32x4.mul(o,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(i,2,3,0,1),n),s=SIMD.float32x4.swizzle(s,1,0,3,2),r=SIMD.float32x4.swizzle(r,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),h=SIMD.float32x4.mul(o,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(o,i),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(r,s)),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(i,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(i,s)),s=SIMD.float32x4.mul(o,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(i,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(i,s),u),l=SIMD.float32x4.mul(o,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},o.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},o.prototype.multiply=function(t){var i=new o;return this.multiplyToRef(t,i),i},o.prototype.copyFrom=function(t){for(var o=0;16>o;o++)this.m[o]=t.m[o];return this},o.prototype.copyToArray=function(t,o){void 0===o&&(o=0);for(var i=0;16>i;i++)t[o+i]=this.m[i];return this},o.prototype.multiplyToRef=function(t,o){return this.multiplyToArray(t,o.m,0),this},o.prototype.multiplyToArray=function(t,o,i){var r=this.m[0],n=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],L=t.m[15];return o[i]=r*w+n*S+s*R+e*A,o[i+1]=r*d+n*v+s*_+e*P,o[i+2]=r*I+n*g+s*b+e*C,o[i+3]=r*D+n*T+s*F+e*L,o[i+4]=a*w+h*S+u*R+l*A,o[i+5]=a*d+h*v+u*_+l*P,o[i+6]=a*I+h*g+u*b+l*C,o[i+7]=a*D+h*T+u*F+l*L,o[i+8]=m*w+f*S+x*R+y*A,o[i+9]=m*d+f*v+x*_+y*P,o[i+10]=m*I+f*g+x*b+y*C,o[i+11]=m*D+f*T+x*F+y*L,o[i+12]=c*w+p*S+z*R+M*A,o[i+13]=c*d+p*v+z*_+M*P,o[i+14]=c*I+p*g+z*b+M*C,o[i+15]=c*D+p*T+z*F+M*L,this},o.prototype.multiplyToArraySIMD=function(t,o,i){void 0===i&&(i=0);var r=this.m,n=t.m,s=SIMD.float32x4.load(n,0),e=SIMD.float32x4.load(n,4),a=SIMD.float32x4.load(n,8),h=SIMD.float32x4.load(n,12),u=SIMD.float32x4.load(r,0);SIMD.float32x4.store(o,i+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)))));var l=SIMD.float32x4.load(r,4);SIMD.float32x4.store(o,i+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)))));\n\nvar m=SIMD.float32x4.load(r,8);SIMD.float32x4.store(o,i+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(r,12);SIMD.float32x4.store(o,i+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)))))},o.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]},o.prototype.clone=function(){return o.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])},o.prototype.decompose=function(i,r,n){n.x=this.m[12],n.y=this.m[13],n.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(i.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),i.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),i.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===i.x||0===i.y||0===i.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=o.FromValues(this.m[0]/i.x,this.m[1]/i.x,this.m[2]/i.x,0,this.m[4]/i.y,this.m[5]/i.y,this.m[6]/i.y,0,this.m[8]/i.z,this.m[9]/i.z,this.m[10]/i.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},o.FromArray=function(t,i){var r=new o;return i||(i=0),o.FromArrayToRef(t,i,r),r},o.FromArrayToRef=function(t,o,i){for(var r=0;16>r;r++)i.m[r]=t[r+o]},o.FromFloat32ArrayToRefScaled=function(t,o,i,r){for(var n=0;16>n;n++)r.m[n]=t[n+o]*i},o.FromValuesToRef=function(t,o,i,r,n,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=o,p.m[2]=i,p.m[3]=r,p.m[4]=n,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},o.FromValues=function(t,i,r,n,s,e,a,h,u,l,m,f,x,y,c,p){var z=new o;return z.m[0]=t,z.m[1]=i,z.m[2]=r,z.m[3]=n,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},o.Compose=function(t,i,r){var n=o.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=o.Identity();return i.toRotationMatrix(s),n=n.multiply(s),n.setTranslation(r),n},o.Identity=function(){return o.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},o.IdentityToRef=function(t){o.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},o.Zero=function(){return o.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},o.RotationX=function(t){var i=new o;return o.RotationXToRef(t,i),i},o.Invert=function(t){var i=new o;return t.invertToRef(i),i},o.RotationXToRef=function(t,o){var i=Math.sin(t),r=Math.cos(t);o.m[0]=1,o.m[15]=1,o.m[5]=r,o.m[10]=r,o.m[9]=-i,o.m[6]=i,o.m[1]=0,o.m[2]=0,o.m[3]=0,o.m[4]=0,o.m[7]=0,o.m[8]=0,o.m[11]=0,o.m[12]=0,o.m[13]=0,o.m[14]=0},o.RotationY=function(t){var i=new o;return o.RotationYToRef(t,i),i},o.RotationYToRef=function(t,o){var i=Math.sin(t),r=Math.cos(t);o.m[5]=1,o.m[15]=1,o.m[0]=r,o.m[2]=-i,o.m[8]=i,o.m[10]=r,o.m[1]=0,o.m[3]=0,o.m[4]=0,o.m[6]=0,o.m[7]=0,o.m[9]=0,o.m[11]=0,o.m[12]=0,o.m[13]=0,o.m[14]=0},o.RotationZ=function(t){var i=new o;return o.RotationZToRef(t,i),i},o.RotationZToRef=function(t,o){var i=Math.sin(t),r=Math.cos(t);o.m[10]=1,o.m[15]=1,o.m[0]=r,o.m[1]=i,o.m[4]=-i,o.m[5]=r,o.m[2]=0,o.m[3]=0,o.m[6]=0,o.m[7]=0,o.m[8]=0,o.m[9]=0,o.m[11]=0,o.m[12]=0,o.m[13]=0,o.m[14]=0},o.RotationAxis=function(t,i){var r=Math.sin(-i),n=Math.cos(-i),s=1-n;t.normalize();var e=o.Zero();return e.m[0]=t.x*t.x*s+n,e.m[1]=t.x*t.y*s-t.z*r,e.m[2]=t.x*t.z*s+t.y*r,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*r,e.m[5]=t.y*t.y*s+n,e.m[6]=t.y*t.z*s-t.x*r,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*r,e.m[9]=t.z*t.y*s+t.x*r,e.m[10]=t.z*t.z*s+n,e.m[11]=0,e.m[15]=1,e},o.RotationYawPitchRoll=function(t,i,r){var n=new o;return o.RotationYawPitchRollToRef(t,i,r,n),n},o.RotationYawPitchRollToRef=function(t,o,i,r){e.RotationYawPitchRollToRef(t,o,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},o.Scaling=function(t,i,r){var n=o.Zero();return o.ScalingToRef(t,i,r,n),n},o.ScalingToRef=function(t,o,i,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=o,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},o.Translation=function(t,i,r){var n=o.Identity();return o.TranslationToRef(t,i,r,n),n},o.TranslationToRef=function(t,i,r,n){o.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},o.LookAtLH=function(t,i,r){var n=o.Zero();return o.LookAtLHToRef(t,i,r,n),n},o.LookAtLHToRef=function(t,i,r,s){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),h=-n.Dot(this._zAxis,t);return o.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)},o.LookAtLHToRefSIMD=function(t,o,i,r){var n=r.m,s=SIMD.float32x4(o.x,o.y,o.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(i.x,i.y,i.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(n,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(n,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(n,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(n,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)))))},o.OrthoLH=function(t,i,r,n){var s=o.Zero();return o.OrthoLHToRef(t,i,r,n,s),s},o.OrthoLHToRef=function(t,i,r,n,s){var e=2/t,a=2/i,h=1/(n-r),u=r/(r-n);o.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},o.OrthoOffCenterLH=function(t,i,r,n,s,e){var a=o.Zero();return o.OrthoOffCenterLHToRef(t,i,r,n,s,e,a),a},o.OrthoOffCenterLHToRef=function(t,o,i,r,n,s,e){e.m[0]=2/(o-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-i),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(n-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+o)/(t-o),e.m[13]=(r+i)/(i-r),e.m[14]=n/(n-s),e.m[15]=1},o.PerspectiveLH=function(t,i,r,n){var s=o.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/i,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-n/(r-n),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n),s},o.PerspectiveFovLH=function(t,i,r,n){var s=o.Zero();return o.PerspectiveFovLHToRef(t,i,r,n,s),s},o.PerspectiveFovLHToRef=function(o,i,r,n,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*o),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/i:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*i,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-n/(r-n),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n)},o.GetFinalMatrix=function(t,i,r,n,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=o.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 i.multiply(r).multiply(n).multiply(m)},o.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},o.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]])},o.Transpose=function(t){var i=new o;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},o.Reflection=function(t){var i=new o;return o.ReflectionToRef(t,i),i},o.ReflectionToRef=function(t,o){t.normalize();var i=t.normal.x,r=t.normal.y,n=t.normal.z,s=-2*i,e=-2*r,a=-2*n;o.m[0]=s*i+1,o.m[1]=e*i,o.m[2]=a*i,o.m[3]=0,o.m[4]=s*r,o.m[5]=e*r+1,o.m[6]=a*r,o.m[7]=0,o.m[8]=s*n,o.m[9]=e*n,o.m[10]=a*n+1,o.m[11]=0,o.m[12]=s*t.d,o.m[13]=e*t.d,o.m[14]=a*t.d,o.m[15]=1},o._tempQuaternion=new e,o._xAxis=n.Zero(),o._yAxis=n.Zero(),o._zAxis=n.Zero(),o}();t.Matrix=a;var h=function(){function t(t,o,i,r){this.normal=new n(t,o,i),this.d=r}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),o=0;return 0!==t&&(o=1/t),this.normal.x*=o,this.normal.y*=o,this.normal.z*=o,this.d*=o,this},t.prototype.transform=function(o){var i=a.Transpose(o),r=this.normal.x,n=this.normal.y,s=this.normal.z,e=this.d,h=r*i.m[0]+n*i.m[1]+s*i.m[2]+e*i.m[3],u=r*i.m[4]+n*i.m[5]+s*i.m[6]+e*i.m[7],l=r*i.m[8]+n*i.m[9]+s*i.m[10]+e*i.m[11],m=r*i.m[12]+n*i.m[13]+s*i.m[14]+e*i.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,o,i){var r,n=o.x-t.x,s=o.y-t.y,e=o.z-t.z,a=i.x-t.x,h=i.y-t.y,u=i.z-t.z,l=s*u-e*h,m=e*a-n*u,f=n*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return r=0!==x?1/x:0,this.normal.x=l*r,this.normal.y=m*r,this.normal.z=f*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,o){var i=n.Dot(this.normal,t);return o>=i},t.prototype.signedDistanceTo=function(t){return n.Dot(t,this.normal)+this.d},t.FromArray=function(o){return new t(o[0],o[1],o[2],o[3])},t.FromPoints=function(o,i,r){var n=new t(0,0,0,0);return n.copyFromPoints(o,i,r),n},t.FromPositionAndNormal=function(o,i){var r=new t(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*o.x+i.y*o.y+i.z*o.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,o,i){var r=-(o.x*t.x+o.y*t.y+o.z*t.z);return n.Dot(i,o)+r},t}();t.Plane=h;var u=function(){function t(t,o,i,r){this.x=t,this.y=o,this.width=i,this.height=r}return t.prototype.toGlobal=function(o){var i=o.getRenderWidth(),r=o.getRenderHeight();return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(o){for(var i=[],r=0;6>r;r++)i.push(new h(0,0,0,0));return t.GetPlanesToRef(o,i),i},t.GetPlanesToRef=function(t,o){o[0].normal.x=t.m[3]+t.m[2],o[0].normal.y=t.m[7]+t.m[6],o[0].normal.z=t.m[10]+t.m[10],o[0].d=t.m[15]+t.m[14],o[0].normalize(),o[1].normal.x=t.m[3]-t.m[2],o[1].normal.y=t.m[7]-t.m[6],o[1].normal.z=t.m[11]-t.m[10],o[1].d=t.m[15]-t.m[14],o[1].normalize(),o[2].normal.x=t.m[3]+t.m[0],o[2].normal.y=t.m[7]+t.m[4],o[2].normal.z=t.m[11]+t.m[8],o[2].d=t.m[15]+t.m[12],o[2].normalize(),o[3].normal.x=t.m[3]-t.m[0],o[3].normal.y=t.m[7]-t.m[4],o[3].normal.z=t.m[11]-t.m[8],o[3].d=t.m[15]-t.m[12],o[3].normalize(),o[4].normal.x=t.m[3]-t.m[1],o[4].normal.y=t.m[7]-t.m[5],o[4].normal.z=t.m[11]-t.m[9],o[4].d=t.m[15]-t.m[13],o[4].normalize(),o[5].normal.x=t.m[3]+t.m[1],o[5].normal.y=t.m[7]+t.m[5],o[5].normal.z=t.m[11]+t.m[9],o[5].d=t.m[15]+t.m[13],o[5].normalize()},t}();t.Frustum=l;var m=function(){function o(t,o,i){void 0===i&&(i=Number.MAX_VALUE),this.origin=t,this.direction=o,this.length=i}return o.prototype.intersectsBoxMinMax=function(t,o){var i=0,r=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>o.x)return!1}else{var n=1/this.direction.x,s=(t.x-this.origin.x)*n,e=(o.x-this.origin.x)*n;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(i=Math.max(s,i),r=Math.min(e,r),i>r)return!1}if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>o.y)return!1}else if(n=1/this.direction.y,s=(t.y-this.origin.y)*n,e=(o.y-this.origin.y)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),i=Math.max(s,i),r=Math.min(e,r),i>r)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>o.z)return!1}else if(n=1/this.direction.z,s=(t.z-this.origin.z)*n,e=(o.z-this.origin.z)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),i=Math.max(s,i),r=Math.min(e,r),i>r)return!1;return!0},o.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},o.prototype.intersectsSphere=function(t){var o=t.center.x-this.origin.x,i=t.center.y-this.origin.y,r=t.center.z-this.origin.z,n=o*o+i*i+r*r,s=t.radius*t.radius;if(s>=n)return!0;var e=o*this.direction.x+i*this.direction.y+r*this.direction.z;if(0>e)return!1;var a=n-e*e;return s>=a},o.prototype.intersectsTriangle=function(o,i,r){this._edge1||(this._edge1=n.Zero(),this._edge2=n.Zero(),this._pvec=n.Zero(),this._tvec=n.Zero(),this._qvec=n.Zero()),i.subtractToRef(o,this._edge1),r.subtractToRef(o,this._edge2),n.CrossToRef(this.direction,this._edge2,this._pvec);var s=n.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(o,this._tvec);var a=n.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;n.CrossToRef(this._tvec,this._edge1,this._qvec);var h=n.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=n.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},o.CreateNew=function(t,i,r,s,e,a,h){var u=n.Unproject(new n(t,i,0),r,s,e,a,h),l=n.Unproject(new n(t,i,1),r,s,e,a,h),m=l.subtract(u);return m.normalize(),new o(u,m)},o.CreateNewFromTo=function(t,i,r){void 0===r&&(r=a.Identity());var n=i.subtract(t),s=Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z);return n.normalize(),o.Transform(new o(t,n,s),r)},o.Transform=function(t,i){var r=n.TransformCoordinates(t.origin,i),s=n.TransformNormal(t.direction,i);return new o(r,s,t.length)},o}();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 n(1,0,0),t.Y=new n(0,1,0),t.Z=new n(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,o,i,r,n){for(var s=1-3*r+3*o,e=3*r-6*o,a=3*o,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*i+3*(1-h)*Math.pow(h,2)*n+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 o=this;this.degrees=function(){return 180*o._radians/Math.PI},this.radians=function(){return o._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(o,i){var r=i.subtract(o),n=Math.atan2(r.y,r.x);return new t(n)},t.FromRadians=function(o){return new t(o)},t.FromDegrees=function(o){return new t(o*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,o,i){this.startPoint=t,this.midPoint=o,this.endPoint=i;var n=Math.pow(o.x,2)+Math.pow(o.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,e=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(t.x-o.x)*(o.y-i.y)-(o.x-i.x)*(t.y-o.y);this.centerPoint=new r((s*(o.y-i.y)-e*(t.y-o.y))/a,((t.x-o.x)*e-(o.x-i.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 n(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(o){return o(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function o(t,o){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,o))}return o.prototype.addLineTo=function(o,i){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var n=new r(o,i),s=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(s).length(),this},o.prototype.addArcTo=function(o,i,n,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 r(o,i),u=new r(n,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},o.prototype.close=function(){return this.closed=!0,this},o.prototype.length=function(){var t=this._length;if(!this.closed){var o=this._points[this._points.length-1],i=this._points[0];t+=i.subtract(o).length()}return t},o.prototype.getPoints=function(){return this._points},o.prototype.getPointAtLengthPosition=function(o){if(0>o||o>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var i=o*this.length(),n=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()+n;if(i>=n&&l>=i){var m=u.normalize(),f=i-n;return new r(a.x+m.x*f,a.y+m.y*f)}n=l}return t.Tools.Error(\"internal error\"),r.Zero()},o.StartingAt=function(t,i){return new o(t,i)},o}();t.Path2=M;var w=function(){function t(t,o){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 i=0;i<t.length;i++)this._curve[i]=t[i].clone();this._compute(o)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,o){for(var i=0;i<t.length;i++)this._curve[i].x=t[i].x,this._curve[i].y=t[i].y,this._curve[i].z=t[i].z;return this._compute(o),this},t.prototype._compute=function(t){var o=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[o-1]=this._curve[o-1].subtract(this._curve[o-2]),this._tangents[o-1].normalize();var i=this._tangents[0],r=this._normalVector(this._curve[0],i,t);this._normals[0]=r,this._normals[0].normalize(),this._binormals[0]=n.Cross(i,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,l=1;o>l;l++)s=this._getLastNonNullVector(l),o-1>l&&(e=this._getFirstNonNullVector(l),this._tangents[l]=s.add(e),this._tangents[l].normalize()),this._distances[l]=this._distances[l-1]+s.length(),a=this._tangents[l],h=this._normals[l-1],u=this._binormals[l-1],this._normals[l]=n.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=n.Cross(a,this._normals[l]),this._binormals[l].normalize()},t.prototype._getFirstNonNullVector=function(t){for(var o=1,i=this._curve[t+o].subtract(this._curve[t]);0==i.length()&&t+o+1<this._curve.length;)o++,i=this._curve[t+o].subtract(this._curve[t]);return i},t.prototype._getLastNonNullVector=function(t){for(var o=1,i=this._curve[t].subtract(this._curve[t-o]);0==i.length()&&t>o+1;)o++,i=this._curve[t].subtract(this._curve[t-o]);return i},t.prototype._normalVector=function(t,o,i){var r;if(void 0===i||null===i){var s;1!==o.y?s=new n(0,-1,0):1!==o.x?s=new n(1,0,0):1!==o.z&&(s=new n(0,0,1)),r=n.Cross(o,s)}else r=n.Cross(o,i),n.CrossToRef(r,o,r);return r.normalize(),r},t}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(o,i,r,s){s=s>2?s:3;for(var e=new Array,a=function(t,o,i,r){var n=(1-t)*(1-t)*o+2*t*(1-t)*i+t*t*r;return n},h=0;s>=h;h++)e.push(new n(a(h/s,o.x,i.x,r.x),a(h/s,o.y,i.y,r.y),a(h/s,o.z,i.z,r.z)));return new t(e)},t.CreateCubicBezier=function(o,i,r,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,o,i,r,n){var s=(1-t)*(1-t)*(1-t)*o+3*t*(1-t)*(1-t)*i+3*t*t*(1-t)*r+t*t*t*n;return s},u=0;e>=u;u++)a.push(new n(h(u/e,o.x,i.x,r.x,s.x),h(u/e,o.y,i.y,r.y,s.y),h(u/e,o.z,i.z,r.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(o,i,r,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(n.Hermite(o,i,r,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(o){for(var i=this._points[this._points.length-1],r=this._points.slice(),n=o.getPoints(),s=1;s<n.length;s++)r.push(n[s].subtract(n[0]).add(i));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var o=0,i=1;i<t.length;i++)o+=t[i].subtract(t[i-1]).length();return o},t}();t.Curve3=d;var I=function(){function t(t,o){void 0===t&&(t=n.Zero()),void 0===o&&(o=n.Up()),this.position=t,this.normal=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,o,i){void 0===t&&(t=n.Zero()),void 0===o&&(o=n.Up()),void 0===i&&(i=r.Zero()),this.position=t,this.normal=o,this.uv=i}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=n.TransformCoordinatesToRef,R=n.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,n.TransformCoordinatesToRef=T,n.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,n.TransformCoordinatesToRef=n.TransformCoordinatesToRefSIMD,n.TransformCoordinatesFromFloatsToRef=n.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(n.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(n.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(n.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={}));";
  33196. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33197. module.exports = BABYLON;
  33198. };